code
stringlengths
4
1.01M
language
stringclasses
2 values
#ifndef COMPAT_H_RD1Z6YZA #define COMPAT_H_RD1Z6YZA namespace oak { inline void set_thread_name (char const* threadName) { pthread_setname_np(threadName); } inline size_t get_gestalt (OSType selector) { SInt32 res; Gestalt(selector, &res); return res; } inline size_t os_major () { return get_gestalt(gestaltSystemVersionMajor); } inline size_t os_minor () { return get_gestalt(gestaltSystemVersionMinor); } inline size_t os_patch () { return get_gestalt(gestaltSystemVersionBugFix); } inline OSStatus execute_with_privileges (AuthorizationRef authorization, std::string const& pathToTool, AuthorizationFlags options, char* const* arguments, FILE** communicationsPipe) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return AuthorizationExecuteWithPrivileges(authorization, pathToTool.c_str(), options, arguments, communicationsPipe); #pragma clang diagnostic pop } } /* oak */ #endif /* end of include guard: COMPAT_H_RD1Z6YZA */
Java
/* * Copyright (c) 2002 Brian Foley * Copyright (c) 2002 Dieter Shirley * Copyright (c) 2003-2004 Romain Dolbeau <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_PPC_DSPUTIL_ALTIVEC_H #define AVCODEC_PPC_DSPUTIL_ALTIVEC_H #include <stdint.h> extern int has_altivec(void); void put_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h); void avg_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h); #endif /* AVCODEC_PPC_DSPUTIL_ALTIVEC_H */
Java
// Copyright (C) 2012 Tuma Solutions, LLC // Team Functionality Add-ons for the Process Dashboard // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // Additional permissions also apply; see the README-license.txt // file in the project root directory for more information. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // // The author(s) may be contacted at: // [email protected] // [email protected] package teamdash.wbs.columns; import teamdash.wbs.WBSModel; import teamdash.wbs.WBSNode; import teamdash.wbs.WBSNodeTest; public class ErrorNotesColumn extends AbstractNotesColumn { /** The ID we use for this column in the data model */ public static final String COLUMN_ID = "Error Notes"; /** The attribute this column uses to store task notes for a WBS node */ public static final String VALUE_ATTR = "Error Notes"; public ErrorNotesColumn(String authorName) { super(VALUE_ATTR, authorName); this.columnID = COLUMN_ID; this.columnName = resources.getString("Error_Notes.Name"); } @Override protected String getEditDialogTitle() { return columnName; } @Override protected Object getEditDialogHeader(WBSNode node) { return new Object[] { resources.getStrings("Error_Notes.Edit_Dialog_Header"), " " }; } public static String getTextAt(WBSNode node) { return getTextAt(node, VALUE_ATTR); } public static String getTooltipAt(WBSNode node, boolean includeByline) { return getTooltipAt(node, includeByline, VALUE_ATTR); } /** * Find nodes that have errors attached, and expand their ancestors as * needed to ensure that they are visible. * * @param wbs * the WBSModel * @param belowNode * an optional starting point for the search, to limit expansion * to a particular branch of the tree; can be null to search from * the root * @param condition * an optional condition to test; only nodes matching the * condition will be made visible. Can be null to show all nodes * with errors */ public static void showNodesWithErrors(WBSModel wbs, WBSNode belowNode, WBSNodeTest condition) { if (belowNode == null) belowNode = wbs.getRoot(); for (WBSNode node : wbs.getDescendants(belowNode)) { String errText = getTextAt(node, VALUE_ATTR); if (errText != null && errText.trim().length() > 0) { if (condition == null || condition.test(node)) wbs.makeVisible(node); } } } }
Java
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtEnginio module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef ENGINIOCLIENT_H #define ENGINIOCLIENT_H #include <Enginio/enginioclient_global.h> #include <Enginio/enginioclientconnection.h> #include <QtCore/qjsonobject.h> QT_BEGIN_NAMESPACE class QNetworkAccessManager; class QNetworkReply; class EnginioReply; class EnginioClientPrivate; class ENGINIOCLIENT_EXPORT EnginioClient : public EnginioClientConnection { Q_OBJECT Q_ENUMS(Enginio::Operation) // TODO remove me QTBUG-33577 Q_ENUMS(Enginio::AuthenticationState) // TODO remove me QTBUG-33577 Q_DECLARE_PRIVATE(EnginioClient) public: explicit EnginioClient(QObject *parent = 0); ~EnginioClient(); Q_INVOKABLE EnginioReply *customRequest(const QUrl &url, const QByteArray &httpOperation, const QJsonObject &data = QJsonObject()); Q_INVOKABLE EnginioReply *fullTextSearch(const QJsonObject &query); Q_INVOKABLE EnginioReply *query(const QJsonObject &query, const Enginio::Operation operation = Enginio::ObjectOperation); Q_INVOKABLE EnginioReply *create(const QJsonObject &object, const Enginio::Operation operation = Enginio::ObjectOperation); Q_INVOKABLE EnginioReply *update(const QJsonObject &object, const Enginio::Operation operation = Enginio::ObjectOperation); Q_INVOKABLE EnginioReply *remove(const QJsonObject &object, const Enginio::Operation operation = Enginio::ObjectOperation); Q_INVOKABLE EnginioReply *uploadFile(const QJsonObject &associatedObject, const QUrl &file); Q_INVOKABLE EnginioReply *downloadUrl(const QJsonObject &object); Q_SIGNALS: void sessionAuthenticated(EnginioReply *reply) const; void sessionAuthenticationError(EnginioReply *reply) const; void sessionTerminated() const; void finished(EnginioReply *reply); void error(EnginioReply *reply); }; QT_END_NAMESPACE #endif // ENGINIOCLIENT_H
Java
<?php /** Copyright 2011-2014 Nick Korbel This file is part of Booked Scheduler is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Booked Scheduler. If not, see <http://www.gnu.org/licenses/>. */ require_once(ROOT_DIR . 'lib/Graphics/Image.php'); require_once(ROOT_DIR . 'lib/Graphics/ImageFactory.php'); ?>
Java
' Instat-R ' Copyright (C) 2015 ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License k ' along with this program. If not, see <http://www.gnu.org/licenses/>. Imports instat.Translations Public Class dlgReplaceValues Public bFirstLoad As Boolean = True Private bReset As Boolean = True Private Sub dlgReplace_Load(sender As Object, e As EventArgs) Handles MyBase.Load autoTranslate(Me) If bFirstLoad Then InitialiseDialog() bFirstLoad = False End If If bReset Then SetDefaults() End If SetRCodeForControls(bReset) bReset = False TestOKEnabled() End Sub Private Sub InitialiseDialog() ucrBase.iHelpTopicID = 47 'ucrSelector ucrSelectorReplace.SetParameter(New RParameter("data_name", 0)) ucrSelectorReplace.SetParameterIsString() 'ucrReceiver ucrReceiverReplace.SetParameter(New RParameter("col_names", 1)) ucrReceiverReplace.Selector = ucrSelectorReplace ucrReceiverReplace.SetMeAsReceiver() ucrReceiverReplace.SetSingleTypeStatus(True) ucrReceiverReplace.SetParameterIsString() ucrReceiverReplace.SetExcludedDataTypes({"Date"}) rdoNewFromAbove.Enabled = False '' Old: ucrPnlOld.AddRadioButton(rdoOldValue) ucrPnlOld.AddRadioButton(rdoOldMissing) ucrPnlOld.AddRadioButton(rdoOldInterval) ucrPnlOld.AddParameterPresentCondition(rdoOldValue, "old_value") ucrPnlOld.AddParameterValuesCondition(rdoOldMissing, "old_is_missing", "TRUE") ucrPnlOld.AddParameterPresentCondition(rdoOldInterval, "start_value") ucrPnlOld.AddParameterPresentCondition(rdoOldInterval, "end_value") ucrPnlOld.AddToLinkedControls(ucrInputOldValue, {rdoOldValue}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True) ucrPnlOld.AddToLinkedControls(ucrInputRangeFrom, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True, objNewDefaultState:=0) ucrPnlOld.AddToLinkedControls(ucrInputRangeTo, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True, objNewDefaultState:=1) ucrPnlOld.AddToLinkedControls(ucrChkMin, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True) ucrPnlOld.AddToLinkedControls(ucrChkMax, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True) 'ucrInputOldValue ucrInputOldValue.SetParameter(New RParameter("old_value", 2)) ucrInputOldValue.bAddRemoveParameter = False 'ucrInputRangeFrom ucrInputRangeFrom.SetParameter(New RParameter("start_value", 2)) ucrInputRangeFrom.AddQuotesIfUnrecognised = False ucrInputRangeFrom.bAddRemoveParameter = False ucrInputRangeFrom.SetLinkedDisplayControl(lblRangeMin) ucrChkMin.SetParameter(New RParameter("closed_start_value")) ucrChkMin.SetText("Including") ucrChkMin.SetValuesCheckedAndUnchecked("TRUE", "FALSE") ucrChkMin.bAddRemoveParameter = False ucrChkMin.SetRDefault("FALSE") 'ucrInputRangeTo ucrInputRangeTo.SetParameter(New RParameter("end_value", 3)) ucrInputRangeTo.AddQuotesIfUnrecognised = False ucrInputRangeTo.bAddRemoveParameter = False ucrInputRangeTo.SetLinkedDisplayControl(lblRangeMax) ucrChkMax.SetParameter(New RParameter("closed_end_value")) ucrChkMax.SetText("Including") ucrChkMax.SetValuesCheckedAndUnchecked("TRUE", "FALSE") ucrChkMax.bAddRemoveParameter = False ucrChkMax.SetRDefault("FALSE") '' NEW VALUES: ucrPnlNew.AddRadioButton(rdoNewValue) ucrPnlNew.AddRadioButton(rdoNewMissing) 'ucrPnlNew.AddRadioButton(rdoNewFromAbove) ucrPnlNew.AddParameterPresentCondition(rdoNewValue, "new_value") ucrPnlNew.AddParameterValuesCondition(rdoNewMissing, "new_is_missing", "TRUE") ucrPnlNew.AddToLinkedControls(ucrInputNewValue, {rdoNewValue}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True, objNewDefaultState:=1) ''ucrInputNewValue ucrInputNewValue.SetParameter(New RParameter("new_value", 4)) ucrInputNewValue.bAddRemoveParameter = False End Sub Private Sub SetDefaults() Dim clsDefaultFunction As New RFunction ucrSelectorReplace.Reset() EnableRange() clsDefaultFunction.SetRCommand(frmMain.clsRLink.strInstatDataObject & "$replace_value_in_data") clsDefaultFunction.AddParameter("old_value", "-99") clsDefaultFunction.AddParameter("new_is_missing", "TRUE") ucrBase.clsRsyntax.SetBaseRFunction(clsDefaultFunction.Clone()) End Sub Private Sub SetRCodeForControls(bReset As Boolean) SetRCode(Me, ucrBase.clsRsyntax.clsBaseFunction, bReset) End Sub Private Sub ReopenDialog() End Sub Private Sub TestOKEnabled() If (Not ucrReceiverReplace.IsEmpty()) Then If ((rdoOldValue.Checked AndAlso Not ucrInputOldValue.IsEmpty) OrElse (rdoOldInterval.Checked AndAlso Not ucrInputRangeFrom.IsEmpty() AndAlso Not ucrInputRangeTo.IsEmpty()) OrElse rdoOldMissing.Checked) AndAlso ((rdoNewValue.Checked AndAlso Not ucrInputNewValue.IsEmpty) OrElse rdoNewMissing.Checked) Then ucrBase.OKEnabled(True) Else ucrBase.OKEnabled(False) End If Else ucrBase.OKEnabled(False) End If End Sub Private Sub ucrBaseReplace_ClickReset(sender As Object, e As EventArgs) Handles ucrBase.ClickReset SetDefaults() SetRCodeForControls(True) TestOKEnabled() End Sub Private Sub InputValue() Dim strVarType As String If Not ucrReceiverReplace.IsEmpty Then strVarType = ucrReceiverReplace.GetCurrentItemTypes(True)(0) If rdoOldValue.Checked Then If (strVarType = "numeric" OrElse strVarType = "integer") Then ucrInputOldValue.AddQuotesIfUnrecognised = False Else ucrInputOldValue.AddQuotesIfUnrecognised = True End If ucrBase.clsRsyntax.RemoveParameter("old_is_missing") ElseIf rdoOldMissing.Checked Then ucrBase.clsRsyntax.AddParameter("old_is_missing", "TRUE") Else ucrBase.clsRsyntax.RemoveParameter("old_is_missing") End If If rdoNewValue.Checked Then If (strVarType = "numeric" OrElse strVarType = "integer") Then ucrInputNewValue.AddQuotesIfUnrecognised = False Else ucrInputNewValue.AddQuotesIfUnrecognised = True End If ucrBase.clsRsyntax.RemoveParameter("new_is_missing") ElseIf rdoNewMissing.Checked Then ucrBase.clsRsyntax.AddParameter("new_is_missing", "TRUE") Else ucrBase.clsRsyntax.RemoveParameter("new_is_missing") End If End If End Sub Private Sub EnableRange() Dim strVarType As String If Not ucrReceiverReplace.IsEmpty Then strVarType = ucrReceiverReplace.GetCurrentItemTypes(True)(0) Else strVarType = "" End If If strVarType = "" OrElse strVarType = "numeric" OrElse strVarType = "integer" Then rdoOldInterval.Enabled = True Else rdoOldInterval.Enabled = False End If If rdoOldInterval.Enabled = False Then If rdoOldInterval.Checked = True Then rdoOldValue.Checked = True rdoOldInterval.Checked = False End If End If End Sub Private Sub ucrReceiverReplace_ControlContentsChanged(ucrChangedControl As ucrCore) Handles ucrReceiverReplace.ControlContentsChanged, ucrPnlNew.ControlContentsChanged, ucrPnlOld.ControlContentsChanged, ucrInputNewValue.ControlContentsChanged, ucrInputOldValue.ControlContentsChanged, ucrInputRangeFrom.ControlContentsChanged, ucrInputRangeTo.ControlContentsChanged TestOKEnabled() End Sub Private Sub ucrPnlOld_ControlValueChanged(ucrChangedControl As ucrCore) Handles ucrPnlOld.ControlValueChanged, ucrPnlNew.ControlValueChanged InputValue() EnableRange() End Sub Private Sub ucrReceiverReplace_ControlValueChanged(ucrChangedControl As ucrCore) Handles ucrReceiverReplace.ControlValueChanged InputValue() EnableRange() End Sub End Class
Java
package gobol // Error - defines a common http error interface type Error interface { error StatusCode() int Message() string Package() string Function() string ErrorCode() string }
Java
namespace Hfr.Model { public enum View { Connect, Main, Editor, Settings, CategoriesList, CategoryThreadsList, PrivateChatsList, PrivateChat } }
Java
//===- RegisterBankEmitter.cpp - Generate a Register Bank Desc. -*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This tablegen backend is responsible for emitting a description of a target // register bank for a code generator. // //===----------------------------------------------------------------------===// #include "llvm/ADT/BitVector.h" #include "llvm/Support/Debug.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" #include "CodeGenHwModes.h" #include "CodeGenRegisters.h" #include "CodeGenTarget.h" #define DEBUG_TYPE "register-bank-emitter" using namespace llvm; namespace { class RegisterBank { /// A vector of register classes that are included in the register bank. typedef std::vector<const CodeGenRegisterClass *> RegisterClassesTy; private: const Record &TheDef; /// The register classes that are covered by the register bank. RegisterClassesTy RCs; /// The register class with the largest register size. const CodeGenRegisterClass *RCWithLargestRegsSize; public: RegisterBank(const Record &TheDef) : TheDef(TheDef), RCs(), RCWithLargestRegsSize(nullptr) {} /// Get the human-readable name for the bank. StringRef getName() const { return TheDef.getValueAsString("Name"); } /// Get the name of the enumerator in the ID enumeration. std::string getEnumeratorName() const { return (TheDef.getName() + "ID").str(); } /// Get the name of the array holding the register class coverage data; std::string getCoverageArrayName() const { return (TheDef.getName() + "CoverageData").str(); } /// Get the name of the global instance variable. StringRef getInstanceVarName() const { return TheDef.getName(); } const Record &getDef() const { return TheDef; } /// Get the register classes listed in the RegisterBank.RegisterClasses field. std::vector<const CodeGenRegisterClass *> getExplicitlySpecifiedRegisterClasses( const CodeGenRegBank &RegisterClassHierarchy) const { std::vector<const CodeGenRegisterClass *> RCs; for (const auto *RCDef : getDef().getValueAsListOfDefs("RegisterClasses")) RCs.push_back(RegisterClassHierarchy.getRegClass(RCDef)); return RCs; } /// Add a register class to the bank without duplicates. void addRegisterClass(const CodeGenRegisterClass *RC) { if (llvm::is_contained(RCs, RC)) return; // FIXME? We really want the register size rather than the spill size // since the spill size may be bigger on some targets with // limited load/store instructions. However, we don't store the // register size anywhere (we could sum the sizes of the subregisters // but there may be additional bits too) and we can't derive it from // the VT's reliably due to Untyped. if (RCWithLargestRegsSize == nullptr) RCWithLargestRegsSize = RC; else if (RCWithLargestRegsSize->RSI.get(DefaultMode).SpillSize < RC->RSI.get(DefaultMode).SpillSize) RCWithLargestRegsSize = RC; assert(RCWithLargestRegsSize && "RC was nullptr?"); RCs.emplace_back(RC); } const CodeGenRegisterClass *getRCWithLargestRegsSize() const { return RCWithLargestRegsSize; } iterator_range<typename RegisterClassesTy::const_iterator> register_classes() const { return llvm::make_range(RCs.begin(), RCs.end()); } }; class RegisterBankEmitter { private: CodeGenTarget Target; RecordKeeper &Records; void emitHeader(raw_ostream &OS, const StringRef TargetName, const std::vector<RegisterBank> &Banks); void emitBaseClassDefinition(raw_ostream &OS, const StringRef TargetName, const std::vector<RegisterBank> &Banks); void emitBaseClassImplementation(raw_ostream &OS, const StringRef TargetName, std::vector<RegisterBank> &Banks); public: RegisterBankEmitter(RecordKeeper &R) : Target(R), Records(R) {} void run(raw_ostream &OS); }; } // end anonymous namespace /// Emit code to declare the ID enumeration and external global instance /// variables. void RegisterBankEmitter::emitHeader(raw_ostream &OS, const StringRef TargetName, const std::vector<RegisterBank> &Banks) { // <Target>RegisterBankInfo.h OS << "namespace llvm {\n" << "namespace " << TargetName << " {\n" << "enum : unsigned {\n"; OS << " InvalidRegBankID = ~0u,\n"; unsigned ID = 0; for (const auto &Bank : Banks) OS << " " << Bank.getEnumeratorName() << " = " << ID++ << ",\n"; OS << " NumRegisterBanks,\n" << "};\n" << "} // end namespace " << TargetName << "\n" << "} // end namespace llvm\n"; } /// Emit declarations of the <Target>GenRegisterBankInfo class. void RegisterBankEmitter::emitBaseClassDefinition( raw_ostream &OS, const StringRef TargetName, const std::vector<RegisterBank> &Banks) { OS << "private:\n" << " static RegisterBank *RegBanks[];\n\n" << "protected:\n" << " " << TargetName << "GenRegisterBankInfo();\n" << "\n"; } /// Visit each register class belonging to the given register bank. /// /// A class belongs to the bank iff any of these apply: /// * It is explicitly specified /// * It is a subclass of a class that is a member. /// * It is a class containing subregisters of the registers of a class that /// is a member. This is known as a subreg-class. /// /// This function must be called for each explicitly specified register class. /// /// \param RC The register class to search. /// \param Kind A debug string containing the path the visitor took to reach RC. /// \param VisitFn The action to take for each class visited. It may be called /// multiple times for a given class if there are multiple paths /// to the class. static void visitRegisterBankClasses( const CodeGenRegBank &RegisterClassHierarchy, const CodeGenRegisterClass *RC, const Twine &Kind, std::function<void(const CodeGenRegisterClass *, StringRef)> VisitFn, SmallPtrSetImpl<const CodeGenRegisterClass *> &VisitedRCs) { // Make sure we only visit each class once to avoid infinite loops. if (VisitedRCs.count(RC)) return; VisitedRCs.insert(RC); // Visit each explicitly named class. VisitFn(RC, Kind.str()); for (const auto &PossibleSubclass : RegisterClassHierarchy.getRegClasses()) { std::string TmpKind = (Kind + " (" + PossibleSubclass.getName() + ")").str(); // Visit each subclass of an explicitly named class. if (RC != &PossibleSubclass && RC->hasSubClass(&PossibleSubclass)) visitRegisterBankClasses(RegisterClassHierarchy, &PossibleSubclass, TmpKind + " " + RC->getName() + " subclass", VisitFn, VisitedRCs); // Visit each class that contains only subregisters of RC with a common // subregister-index. // // More precisely, PossibleSubclass is a subreg-class iff Reg:SubIdx is in // PossibleSubclass for all registers Reg from RC using any // subregister-index SubReg for (const auto &SubIdx : RegisterClassHierarchy.getSubRegIndices()) { BitVector BV(RegisterClassHierarchy.getRegClasses().size()); PossibleSubclass.getSuperRegClasses(&SubIdx, BV); if (BV.test(RC->EnumValue)) { std::string TmpKind2 = (Twine(TmpKind) + " " + RC->getName() + " class-with-subregs: " + RC->getName()) .str(); VisitFn(&PossibleSubclass, TmpKind2); } } } } void RegisterBankEmitter::emitBaseClassImplementation( raw_ostream &OS, StringRef TargetName, std::vector<RegisterBank> &Banks) { const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank(); OS << "namespace llvm {\n" << "namespace " << TargetName << " {\n"; for (const auto &Bank : Banks) { std::vector<std::vector<const CodeGenRegisterClass *>> RCsGroupedByWord( (RegisterClassHierarchy.getRegClasses().size() + 31) / 32); for (const auto &RC : Bank.register_classes()) RCsGroupedByWord[RC->EnumValue / 32].push_back(RC); OS << "const uint32_t " << Bank.getCoverageArrayName() << "[] = {\n"; unsigned LowestIdxInWord = 0; for (const auto &RCs : RCsGroupedByWord) { OS << " // " << LowestIdxInWord << "-" << (LowestIdxInWord + 31) << "\n"; for (const auto &RC : RCs) { std::string QualifiedRegClassID = (Twine(RC->Namespace) + "::" + RC->getName() + "RegClassID").str(); OS << " (1u << (" << QualifiedRegClassID << " - " << LowestIdxInWord << ")) |\n"; } OS << " 0,\n"; LowestIdxInWord += 32; } OS << "};\n"; } OS << "\n"; for (const auto &Bank : Banks) { std::string QualifiedBankID = (TargetName + "::" + Bank.getEnumeratorName()).str(); const CodeGenRegisterClass &RC = *Bank.getRCWithLargestRegsSize(); unsigned Size = RC.RSI.get(DefaultMode).SpillSize; OS << "RegisterBank " << Bank.getInstanceVarName() << "(/* ID */ " << QualifiedBankID << ", /* Name */ \"" << Bank.getName() << "\", /* Size */ " << Size << ", " << "/* CoveredRegClasses */ " << Bank.getCoverageArrayName() << ", /* NumRegClasses */ " << RegisterClassHierarchy.getRegClasses().size() << ");\n"; } OS << "} // end namespace " << TargetName << "\n" << "\n"; OS << "RegisterBank *" << TargetName << "GenRegisterBankInfo::RegBanks[] = {\n"; for (const auto &Bank : Banks) OS << " &" << TargetName << "::" << Bank.getInstanceVarName() << ",\n"; OS << "};\n\n"; OS << TargetName << "GenRegisterBankInfo::" << TargetName << "GenRegisterBankInfo()\n" << " : RegisterBankInfo(RegBanks, " << TargetName << "::NumRegisterBanks) {\n" << " // Assert that RegBank indices match their ID's\n" << "#ifndef NDEBUG\n" << " unsigned Index = 0;\n" << " for (const auto &RB : RegBanks)\n" << " assert(Index++ == RB->getID() && \"Index != ID\");\n" << "#endif // NDEBUG\n" << "}\n" << "} // end namespace llvm\n"; } void RegisterBankEmitter::run(raw_ostream &OS) { StringRef TargetName = Target.getName(); const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank(); Records.startTimer("Analyze records"); std::vector<RegisterBank> Banks; for (const auto &V : Records.getAllDerivedDefinitions("RegisterBank")) { SmallPtrSet<const CodeGenRegisterClass *, 8> VisitedRCs; RegisterBank Bank(*V); for (const CodeGenRegisterClass *RC : Bank.getExplicitlySpecifiedRegisterClasses(RegisterClassHierarchy)) { visitRegisterBankClasses( RegisterClassHierarchy, RC, "explicit", [&Bank](const CodeGenRegisterClass *RC, StringRef Kind) { LLVM_DEBUG(dbgs() << "Added " << RC->getName() << "(" << Kind << ")\n"); Bank.addRegisterClass(RC); }, VisitedRCs); } Banks.push_back(Bank); } // Warn about ambiguous MIR caused by register bank/class name clashes. Records.startTimer("Warn ambiguous"); for (const auto &Class : RegisterClassHierarchy.getRegClasses()) { for (const auto &Bank : Banks) { if (Bank.getName().lower() == StringRef(Class.getName()).lower()) { PrintWarning(Bank.getDef().getLoc(), "Register bank names should be " "distinct from register classes " "to avoid ambiguous MIR"); PrintNote(Bank.getDef().getLoc(), "RegisterBank was declared here"); PrintNote(Class.getDef()->getLoc(), "RegisterClass was declared here"); } } } Records.startTimer("Emit output"); emitSourceFileHeader("Register Bank Source Fragments", OS); OS << "#ifdef GET_REGBANK_DECLARATIONS\n" << "#undef GET_REGBANK_DECLARATIONS\n"; emitHeader(OS, TargetName, Banks); OS << "#endif // GET_REGBANK_DECLARATIONS\n\n" << "#ifdef GET_TARGET_REGBANK_CLASS\n" << "#undef GET_TARGET_REGBANK_CLASS\n"; emitBaseClassDefinition(OS, TargetName, Banks); OS << "#endif // GET_TARGET_REGBANK_CLASS\n\n" << "#ifdef GET_TARGET_REGBANK_IMPL\n" << "#undef GET_TARGET_REGBANK_IMPL\n"; emitBaseClassImplementation(OS, TargetName, Banks); OS << "#endif // GET_TARGET_REGBANK_IMPL\n"; } namespace llvm { void EmitRegisterBank(RecordKeeper &RK, raw_ostream &OS) { RegisterBankEmitter(RK).run(OS); } } // end namespace llvm
Java
# -*- coding: utf-8 -*- """ pythoner.net Copyright (C) 2013 PYTHONER.ORG This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from django.contrib import admin from models import * class ProfileAdmin(admin.ModelAdmin): list_display = ('screen_name','city','introduction') admin.site.register(UserProfile,ProfileAdmin)
Java
// // MainWindow.h // fakeThunder // // Created by Martian on 12-8-15. // Copyright (c) 2012年 MartianZ. All rights reserved. // #import <Cocoa/Cocoa.h> @interface MainWindow : NSWindowController @end
Java
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2017 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) #include <GTEnginePCH.h> #include <Graphics/GteViewVolumeNode.h> using namespace gte; ViewVolumeNode::ViewVolumeNode(std::shared_ptr<ViewVolume> const& viewVolume) : mOnUpdate([](ViewVolumeNode*){}) { SetViewVolume(viewVolume); } void ViewVolumeNode::SetViewVolume(std::shared_ptr<ViewVolume> const& viewVolume) { mViewVolume = viewVolume; if (mViewVolume) { Matrix4x4<float> rotate; #if defined(GTE_USE_MAT_VEC) rotate.SetCol(0, mViewVolume->GetDVector()); rotate.SetCol(1, mViewVolume->GetUVector()); rotate.SetCol(2, mViewVolume->GetRVector()); rotate.SetCol(3, { 0.0f, 0.0f, 0.0f, 1.0f }); #else rotate.SetRow(0, mViewVolume->GetDVector()); rotate.SetRow(1, mViewVolume->GetUVector()); rotate.SetRow(2, mViewVolume->GetRVector()); rotate.SetRow(3, { 0.0f, 0.0f, 0.0f, 1.0f }); #endif localTransform.SetTranslation(mViewVolume->GetPosition()); localTransform.SetRotation(rotate); Update(); } } void ViewVolumeNode::UpdateWorldData(double applicationTime) { Node::UpdateWorldData(applicationTime); if (mViewVolume) { Vector4<float> position = worldTransform.GetTranslationW1(); Matrix4x4<float> const& rotate = worldTransform.GetHMatrix(); #if defined(GTE_USE_MAT_VEC) Vector4<float> dVector = rotate.GetCol(0); Vector4<float> uVector = rotate.GetCol(1); Vector4<float> rVector = rotate.GetCol(2); #else Vector4<float> dVector = rotate.GetRow(0); Vector4<float> uVector = rotate.GetRow(1); Vector4<float> rVector = rotate.GetRow(2); #endif mViewVolume->SetFrame(position, dVector, uVector, rVector); mOnUpdate(this); } }
Java
from django.conf.urls.defaults import * from indivo.views import * from indivo.lib.utils import MethodDispatcher urlpatterns = patterns('', (r'^$', MethodDispatcher({ 'DELETE' : carenet_delete})), (r'^/rename$', MethodDispatcher({ 'POST' : carenet_rename})), (r'^/record$', MethodDispatcher({'GET':carenet_record})), # Manage documents (r'^/documents/', include('indivo.urls.carenet_documents')), # Manage accounts (r'^/accounts/$', MethodDispatcher({ 'GET' : carenet_account_list, 'POST' : carenet_account_create })), (r'^/accounts/(?P<account_id>[^/]+)$', MethodDispatcher({ 'DELETE' : carenet_account_delete })), # Manage apps (r'^/apps/$', MethodDispatcher({ 'GET' : carenet_apps_list})), (r'^/apps/(?P<pha_email>[^/]+)$', MethodDispatcher({ 'PUT' : carenet_apps_create, 'DELETE': carenet_apps_delete})), # Permissions Calls (r'^/accounts/(?P<account_id>[^/]+)/permissions$', MethodDispatcher({ 'GET' : carenet_account_permissions })), (r'^/apps/(?P<pha_email>[^/]+)/permissions$', MethodDispatcher({ 'GET' : carenet_app_permissions })), # Reporting Calls (r'^/reports/minimal/procedures/$', MethodDispatcher({'GET':carenet_procedure_list})), (r'^/reports/minimal/simple-clinical-notes/$', MethodDispatcher({'GET':carenet_simple_clinical_notes_list})), (r'^/reports/minimal/equipment/$', MethodDispatcher({'GET':carenet_equipment_list})), (r'^/reports/minimal/measurements/(?P<lab_code>[^/]+)/$', MethodDispatcher({'GET':carenet_measurement_list})), (r'^/reports/(?P<data_model>[^/]+)/$', MethodDispatcher({'GET':carenet_generic_list})), # Demographics (r'^/demographics$', MethodDispatcher({'GET': read_demographics_carenet})), )
Java
# coding: utf-8 import json import logging import dateutil.parser import pytz from werkzeug import urls from odoo import api, fields, models, _ from odoo.addons.payment.models.payment_acquirer import ValidationError from odoo.addons.payment_paypal.controllers.main import PaypalController from odoo.tools.float_utils import float_compare _logger = logging.getLogger(__name__) class AcquirerPaypal(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection(selection_add=[('paypal', 'Paypal')]) paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user') paypal_seller_account = fields.Char( 'Paypal Merchant ID', groups='base.group_user', help='The Merchant ID is used to ensure communications coming from Paypal are valid and secured.') paypal_use_ipn = fields.Boolean('Use IPN', default=True, help='Paypal Instant Payment Notification', groups='base.group_user') paypal_pdt_token = fields.Char(string='Paypal PDT Token', help='Payment Data Transfer allows you to receive notification of successful payments as they are made.', groups='base.group_user') # Server 2 server paypal_api_enabled = fields.Boolean('Use Rest API', default=False) paypal_api_username = fields.Char('Rest API Username', groups='base.group_user') paypal_api_password = fields.Char('Rest API Password', groups='base.group_user') paypal_api_access_token = fields.Char('Access Token', groups='base.group_user') paypal_api_access_token_validity = fields.Datetime('Access Token Validity', groups='base.group_user') # Default paypal fees fees_dom_fixed = fields.Float(default=0.35) fees_dom_var = fields.Float(default=3.4) fees_int_fixed = fields.Float(default=0.35) fees_int_var = fields.Float(default=3.9) def _get_feature_support(self): """Get advanced feature support by provider. Each provider should add its technical in the corresponding key for the following features: * fees: support payment fees computations * authorize: support authorizing payment (separates authorization and capture) * tokenize: support saving payment data in a payment.tokenize object """ res = super(AcquirerPaypal, self)._get_feature_support() res['fees'].append('paypal') return res @api.model def _get_paypal_urls(self, environment): """ Paypal URLS """ if environment == 'prod': return { 'paypal_form_url': 'https://www.paypal.com/cgi-bin/webscr', 'paypal_rest_url': 'https://api.paypal.com/v1/oauth2/token', } else: return { 'paypal_form_url': 'https://www.sandbox.paypal.com/cgi-bin/webscr', 'paypal_rest_url': 'https://api.sandbox.paypal.com/v1/oauth2/token', } @api.multi def paypal_compute_fees(self, amount, currency_id, country_id): """ Compute paypal fees. :param float amount: the amount to pay :param integer country_id: an ID of a res.country, or None. This is the customer's country, to be compared to the acquirer company country. :return float fees: computed fees """ if not self.fees_active: return 0.0 country = self.env['res.country'].browse(country_id) if country and self.company_id.country_id.id == country.id: percentage = self.fees_dom_var fixed = self.fees_dom_fixed else: percentage = self.fees_int_var fixed = self.fees_int_fixed fees = (percentage / 100.0 * amount + fixed) / (1 - percentage / 100.0) return fees @api.multi def paypal_form_generate_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') paypal_tx_values = dict(values) paypal_tx_values.update({ 'cmd': '_xclick', 'business': self.paypal_email_account, 'item_name': '%s: %s' % (self.company_id.name, values['reference']), 'item_number': values['reference'], 'amount': values['amount'], 'currency_code': values['currency'] and values['currency'].name or '', 'address1': values.get('partner_address'), 'city': values.get('partner_city'), 'country': values.get('partner_country') and values.get('partner_country').code or '', 'state': values.get('partner_state') and (values.get('partner_state').code or values.get('partner_state').name) or '', 'email': values.get('partner_email'), 'zip_code': values.get('partner_zip'), 'first_name': values.get('partner_first_name'), 'last_name': values.get('partner_last_name'), 'paypal_return': urls.url_join(base_url, PaypalController._return_url), 'notify_url': urls.url_join(base_url, PaypalController._notify_url), 'cancel_return': urls.url_join(base_url, PaypalController._cancel_url), 'handling': '%.2f' % paypal_tx_values.pop('fees', 0.0) if self.fees_active else False, 'custom': json.dumps({'return_url': '%s' % paypal_tx_values.pop('return_url')}) if paypal_tx_values.get('return_url') else False, }) return paypal_tx_values @api.multi def paypal_get_form_action_url(self): return self._get_paypal_urls(self.environment)['paypal_form_url'] class TxPaypal(models.Model): _inherit = 'payment.transaction' paypal_txn_type = fields.Char('Transaction type') # -------------------------------------------------- # FORM RELATED METHODS # -------------------------------------------------- @api.model def _paypal_form_get_tx_from_data(self, data): reference, txn_id = data.get('item_number'), data.get('txn_id') if not reference or not txn_id: error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id) _logger.info(error_msg) raise ValidationError(error_msg) # find tx -> @TDENOTE use txn_id ? txs = self.env['payment.transaction'].search([('reference', '=', reference)]) if not txs or len(txs) > 1: error_msg = 'Paypal: received data for reference %s' % (reference) if not txs: error_msg += '; no order found' else: error_msg += '; multiple order found' _logger.info(error_msg) raise ValidationError(error_msg) return txs[0] @api.multi def _paypal_form_get_invalid_parameters(self, data): invalid_parameters = [] _logger.info('Received a notification from Paypal with IPN version %s', data.get('notify_version')) if data.get('test_ipn'): _logger.warning( 'Received a notification from Paypal using sandbox' ), # TODO: txn_id: shoudl be false at draft, set afterwards, and verified with txn details if self.acquirer_reference and data.get('txn_id') != self.acquirer_reference: invalid_parameters.append(('txn_id', data.get('txn_id'), self.acquirer_reference)) # check what is buyed if float_compare(float(data.get('mc_gross', '0.0')), (self.amount + self.fees), 2) != 0: invalid_parameters.append(('mc_gross', data.get('mc_gross'), '%.2f' % self.amount)) # mc_gross is amount + fees if data.get('mc_currency') != self.currency_id.name: invalid_parameters.append(('mc_currency', data.get('mc_currency'), self.currency_id.name)) if 'handling_amount' in data and float_compare(float(data.get('handling_amount')), self.fees, 2) != 0: invalid_parameters.append(('handling_amount', data.get('handling_amount'), self.fees)) # check buyer if self.payment_token_id and data.get('payer_id') != self.payment_token_id.acquirer_ref: invalid_parameters.append(('payer_id', data.get('payer_id'), self.payment_token_id.acquirer_ref)) # check seller if data.get('receiver_id') and self.acquirer_id.paypal_seller_account and data['receiver_id'] != self.acquirer_id.paypal_seller_account: invalid_parameters.append(('receiver_id', data.get('receiver_id'), self.acquirer_id.paypal_seller_account)) if not data.get('receiver_id') or not self.acquirer_id.paypal_seller_account: # Check receiver_email only if receiver_id was not checked. # In Paypal, this is possible to configure as receiver_email a different email than the business email (the login email) # In Odoo, there is only one field for the Paypal email: the business email. This isn't possible to set a receiver_email # different than the business email. Therefore, if you want such a configuration in your Paypal, you are then obliged to fill # the Merchant ID in the Paypal payment acquirer in Odoo, so the check is performed on this variable instead of the receiver_email. # At least one of the two checks must be done, to avoid fraudsters. if data.get('receiver_email') != self.acquirer_id.paypal_email_account: invalid_parameters.append(('receiver_email', data.get('receiver_email'), self.acquirer_id.paypal_email_account)) return invalid_parameters @api.multi def _paypal_form_validate(self, data): status = data.get('payment_status') res = { 'acquirer_reference': data.get('txn_id'), 'paypal_txn_type': data.get('payment_type'), } if status in ['Completed', 'Processed']: _logger.info('Validated Paypal payment for tx %s: set as done' % (self.reference)) try: # dateutil and pytz don't recognize abbreviations PDT/PST tzinfos = { 'PST': -8 * 3600, 'PDT': -7 * 3600, } date = dateutil.parser.parse(data.get('payment_date'), tzinfos=tzinfos).astimezone(pytz.utc) except: date = fields.Datetime.now() res.update(date=date) self._set_transaction_done() return self.write(res) elif status in ['Pending', 'Expired']: _logger.info('Received notification for Paypal payment %s: set as pending' % (self.reference)) res.update(state_message=data.get('pending_reason', '')) self._set_transaction_pending() return self.write(res) else: error = 'Received unrecognized status for Paypal payment %s: %s, set as error' % (self.reference, status) _logger.info(error) res.update(state_message=error) self._set_transaction_cancel() return self.write(res)
Java
=head1 NAME apt-cudf.conf - Configuration file for apt-cudf =head1 DESCRIPTION The configuration file allows one to define default optimization criterias for all solvers known by apt-cudf =head1 SYNTAX solver: <solver list> | '*' A comma-separated list of solvers. The character will make the optimization criteria as default for all solvers without a more specific definition. upgrade: <optimization criteria> dist-upgrade: <optimization criteria> install: <optimization criteria> remove: <optimization criteria> Default optimization criteria associated to apt-get actions. The optimization criteria is solver specific. Specifying a incorrect criteria will result in an error from the underlying cudf solver. Please refere to the solver man page for the correct syntax trendy: <optimization criteria> paranoid: <optimization criteria> <keyword>: <optimization criteria> Define a shortcut for an optimization criteria. The shortcut can then be used by apt-get to pass a specific optimization criteria for a cudf solver apt-get install gnome --solver aspcud -o "APT::Solver::aspcud::Preferences=trendy" =head1 EXAMPLE solver: mccs-cbc , mccs-lpsolve upgrade: -lex[-new,-removed,-notuptodate] dist-upgrade: -lex[-notuptodate,-new] install: -lex[-removed,-changed] remove: -lex[-removed,-changed] trendy: -lex[-removed,-notuptodate,-unsat_recommends,-new] paranoid: -lex[-removed,-changed] solver: * upgrade: -new,-removed,-notuptodate dist-upgrade: -notuptodate,-new install: -removed,-changed remove: -removed,-changed trendy: -removed,-notuptodate,-unsat_recommends,-new paranoid: -removed,-changed =head1 SEE ALSO apt-cudf(8), apt-get(8), update-cudf-solvers(8), L<README.cudf-solvers|file:///usr/share/doc/apt-cudf/README.cudf-solvers>, L<README.Debian|file:///usr/share/doc/apt-cudf/README.Debian> =head1 AUTHOR Copyright: (C) 2011 Pietro Abate <[email protected]> Copyright: (C) 2011 Stefano Zacchiroli <[email protected]> License: GNU Lesser General Public License (GPL), version 3 or above =cut
Java
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def test_plot_experiment(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False) def suite(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop()
Java
<div class="container" style="background-color:%textbackgroundcolor{.75}%;"> <span class="time_initial"> %time% </span> <span class="buddyicon"> <img src="%userIconPath%" width="24" height="24" /> </span> <div class="placeholder" visible="%userIconPath%"> <span class="sender incoming"> %sender% </span> <span class="message incoming_link"> <br>%message% </span> </div> <span class="clear"></span> </div> <span id="insert"></span>
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>io_service::strand::get_io_service</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../io_service__strand.html" title="io_service::strand"> <link rel="prev" href="dispatch.html" title="io_service::strand::dispatch"> <link rel="next" href="post.html" title="io_service::strand::post"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="dispatch.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../io_service__strand.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="post.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.io_service__strand.get_io_service"></a><a class="link" href="get_io_service.html" title="io_service::strand::get_io_service">io_service::strand::get_io_service</a> </h4></div></div></div> <p> <a class="indexterm" name="idm45773618405744"></a> Get the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> associated with the strand. </p> <pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span> <span class="special">&amp;</span> <span class="identifier">get_io_service</span><span class="special">();</span> </pre> <p> This function may be used to obtain the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object that the strand uses to dispatch handlers for asynchronous operations. </p> <h6> <a name="boost_asio.reference.io_service__strand.get_io_service.h0"></a> <span class="phrase"><a name="boost_asio.reference.io_service__strand.get_io_service.return_value"></a></span><a class="link" href="get_io_service.html#boost_asio.reference.io_service__strand.get_io_service.return_value">Return Value</a> </h6> <p> A reference to the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object that the strand will use to dispatch handlers. Ownership is not transferred to the caller. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="dispatch.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../io_service__strand.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="post.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenCL.Net; namespace Conv.NET { [Serializable] public class FullyConnectedLayer : Layer { #region Fields private double dropoutParameter; // Host private float[] weightsHost; private float[] biasesHost; // Device [NonSerialized] private Mem dropoutMaskGPU; [NonSerialized] private Mem weightsGPU; [NonSerialized] private Mem biasesGPU; [NonSerialized] private Mem weightsGradientsGPU; [NonSerialized] private Mem biasesGradientsGPU; [NonSerialized] private Mem weightsSpeedGPU; [NonSerialized] private Mem biasesSpeedGPU; // Global and local work-group sizes (for OpenCL kernels) - will be set in SetWorkGroupSizes(); private IntPtr[] forwardGlobalWorkSizePtr; private IntPtr[] forwardLocalWorkSizePtr; private IntPtr[] backwardGlobalWorkSizePtr; private IntPtr[] backwardLocalWorkSizePtr; private IntPtr[] updateGlobalWorkSizePtr; private IntPtr[] updateLocalWorkSizePtr; private IntPtr[] constrainNormGlobalWorkSizePtr; private IntPtr[] constrainNormLocalWorkSizePtr; #endregion #region Properties public override Mem WeightsGPU { get { return weightsGPU; } } public override double DropoutParameter { set { this.dropoutParameter = value; } } #endregion #region Setup methods /// <summary> /// Constructor of fully connected layer type. Specify number of units as argument. /// </summary> /// <param name="nUnits"></param> public FullyConnectedLayer(int nUnits) { this.type = "FullyConnected"; this.nOutputUnits = nUnits; } public override void SetupOutput() { this.outputDepth = nOutputUnits; this.outputHeight = 1; this.outputWidth = 1; this.outputNeurons = new Neurons(this.nOutputUnits); #if OPENCL_ENABLED this.dropoutMaskGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context, MemFlags.ReadWrite, (IntPtr)(sizeof(bool) * nOutputUnits * inputNeurons.MiniBatchSize), out OpenCLSpace.ClError); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "InitializeParameters(): Cl.CreateBuffer"); OpenCLSpace.WipeBuffer(dropoutMaskGPU, nOutputUnits * inputNeurons.MiniBatchSize, typeof(bool)); #endif } public override void InitializeParameters(string Option) { base.InitializeParameters(Option); // makes sure this method is only call AFTER "SetupOutput()" if (Option == "random") // sample new parameters { // WEIGHTS are initialized as normally distributed numbers with mean 0 and std equals to sqrt(2/nInputUnits) // BIASES are initialized to a small positive number, e.g. 0.001 this.weightsHost = new float[nOutputUnits * nInputUnits]; this.biasesHost = new float[nOutputUnits]; double weightsStdDev = Math.Sqrt(2.0 / (10 * nInputUnits)); double uniformRand1; double uniformRand2; double tmp; for (int iRow = 0; iRow < nOutputUnits; iRow++) { for (int iCol = 0; iCol < nInputUnits; iCol++) { uniformRand1 = Global.rng.NextDouble(); uniformRand2 = Global.rng.NextDouble(); // Use a Box-Muller transform to get a random normal(0,1) tmp = Math.Sqrt(-2.0 * Math.Log(uniformRand1)) * Math.Sin(2.0 * Math.PI * uniformRand2); tmp = weightsStdDev * tmp; // rescale weightsHost[iRow * nInputUnits + iCol] = (float)tmp; } biasesHost[iRow] = 0.00f; } } // else Option must be ''load'' => do not sample parameters, just load them from host to device int weightBufferSize = sizeof(float) * (outputNeurons.NumberOfUnits * inputNeurons.NumberOfUnits); int biasesBufferSize = sizeof(float) * outputNeurons.NumberOfUnits; this.weightsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context, MemFlags.ReadWrite | MemFlags.CopyHostPtr, (IntPtr)weightBufferSize, weightsHost, out OpenCLSpace.ClError); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer"); this.biasesGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context, MemFlags.ReadWrite | MemFlags.CopyHostPtr, (IntPtr)biasesBufferSize, biasesHost, out OpenCLSpace.ClError); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer"); // Also create weightsGradients and biasesGradients buffers and initialize them to zero this.weightsGradientsGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context, MemFlags.ReadWrite, (IntPtr)weightBufferSize, out OpenCLSpace.ClError); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer"); OpenCLSpace.WipeBuffer(weightsGradientsGPU, (nInputUnits * nOutputUnits), typeof(float)); this.biasesGradientsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context, MemFlags.ReadWrite, (IntPtr)biasesBufferSize, out OpenCLSpace.ClError); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer"); OpenCLSpace.WipeBuffer(biasesGradientsGPU, nOutputUnits, typeof(float)); // Also create weightsSpeed and biasesSpeed buffers and initialize them to zero this.weightsSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context, MemFlags.ReadWrite, (IntPtr)weightBufferSize, out OpenCLSpace.ClError); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer"); OpenCLSpace.WipeBuffer(weightsSpeedGPU, (nInputUnits * nOutputUnits), typeof(float)); this.biasesSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context, MemFlags.ReadWrite, (IntPtr)biasesBufferSize, out OpenCLSpace.ClError); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer"); OpenCLSpace.WipeBuffer(biasesSpeedGPU, nOutputUnits, typeof(float)); } public override void SetWorkGroups() { // Work group sizes will be set as follows: // global work size = smallest multiple of OPTIMAL_GROUP_SIZE larger than // the total number of processes needed (for efficiency). // local work size = as close as possible to OPTIMAL_GROUP_SIZE (making sure // that global worksize is a multiple of this) // OPTIMAL_GROUP_SIZE is a small multiple of BASE_GROUP_SIZE, which in turn is a // constant multiple of 2, platform-dependent, e.g. 32 (Nvidia // WARP) or 64 (AMD WAVEFRONT). int miniBatchSize = outputNeurons.MiniBatchSize; // FeedForward (2D) ________________________________________________________________________________ // Local int optimalToBaseRatio = OpenCLSpace.OPTIMAL_GROUP_SIZE / OpenCLSpace.BASE_GROUP_SIZE; this.forwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio }; // Global int smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE)); int smallestMultiple1 = (int)(optimalToBaseRatio * Math.Ceiling((double)(miniBatchSize) / (double)optimalToBaseRatio)); this.forwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 }; // BackPropagate (2D) _________________________________________________________________________________ // Local this.backwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio }; // Global smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE)); // input this time! this.backwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 }; // UpdateSpeeds and UpdateParameters (2D) ________________________________________________________________ // Local this.updateLocalWorkSizePtr = new IntPtr[] { (IntPtr)optimalToBaseRatio, (IntPtr)OpenCLSpace.BASE_GROUP_SIZE }; // product is OPTIMAL_WORK_SIZE // Global smallestMultiple0 = (int)(optimalToBaseRatio * Math.Ceiling((double)(nOutputUnits) / (double)optimalToBaseRatio)); smallestMultiple1 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE)); this.updateGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 }; // Max norm constrain this.constrainNormLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE }; int smallestMultipleAux = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE)); this.constrainNormGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultipleAux }; } public override void CopyBuffersToHost() { OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue, weightsGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nInputUnits * nOutputUnits), weightsHost, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer weightsGPU"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue, biasesGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nOutputUnits), biasesHost, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer biasesGPU"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); // Speeds are not saved. } #endregion #region Methods public override void FeedForward() { #if TIMING_LAYERS Utils.FCForwardTimer.Start(); #endif #if OPENCL_ENABLED // Set kernel arguments OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCForward, 0, outputNeurons.ActivationsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 1, inputNeurons.ActivationsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 2, weightsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 3, biasesGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 4, (IntPtr)sizeof(int), nInputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 5, (IntPtr)sizeof(int), nOutputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 7, (IntPtr)sizeof(float), (float)dropoutParameter); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 8, (IntPtr)sizeof(ulong), (ulong)Guid.NewGuid().GetHashCode()); // this should be quite a good random seed OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 9, dropoutMaskGPU); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.SetKernelArg"); // Run kernel OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue, OpenCLSpace.FCForward, 2, null, forwardGlobalWorkSizePtr, forwardLocalWorkSizePtr, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.EnqueueNDRangeKernel"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); #else // TODO: add dropout CPU // Generate dropout mask if (dropoutParameter < 1) { for (int iUnit = 0; iUnit < nOutputUnits * inputNeurons.MiniBatchSize; ++iUnit) dropoutMask[iUnit] = Global.RandomDouble() < dropoutParameter; } for (int m = 0; m < inputNeurons.MiniBatchSize; m++) { double[] unbiasedOutput = Utils.MultiplyMatrixByVector(weights, inputNeurons.GetHost()[m]); this.outputNeurons.SetHost(m, unbiasedOutput.Zip(biases, (x, y) => x + y).ToArray()); } #endif #if TIMING_LAYERS Utils.FCForwardTimer.Stop(); #endif } public override void BackPropagate() { #if TIMING_LAYERS Utils.FCBackpropTimer.Start(); #endif #if OPENCL_ENABLED // Set kernel arguments OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 0, inputNeurons.DeltaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 1, outputNeurons.DeltaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 2, weightsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 3, dropoutMaskGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 4, (IntPtr)sizeof(int), nInputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 5, (IntPtr)sizeof(int), nOutputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.SetKernelArg"); // Run kernel OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue, OpenCLSpace.FCBackward, 2, null, backwardGlobalWorkSizePtr, backwardLocalWorkSizePtr, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.EnqueueNDRangeKernel"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); #else for (int m = 0; m < inputNeurons.MiniBatchSize; m++) { inputNeurons.DeltaHost[m] = Utils.MultiplyMatrixTranspByVector(weights, outputNeurons.DeltaHost[m]); } #endif #if TIMING_LAYERS Utils.FCBackpropTimer.Stop(); #endif } public override void UpdateSpeeds(double learningRate, double momentumCoefficient, double weightDecayCoefficient) { #if TIMING_LAYERS Utils.FCUpdateSpeedsTimer.Start(); #endif #if DEBUGGING_STEPBYSTEP_FC float[,] weightsBeforeUpdate = new float[output.NumberOfUnits, input.NumberOfUnits]; /* ------------------------- DEBUGGING --------------------------------------------- */ #if OPENCL_ENABLED // Display weights before update OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, weightsGPU, // source Bool.True, (IntPtr)0, (IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)), weightsBeforeUpdate, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsBeforeUpdate"); #else weightsBeforeUpdate = weights; #endif Console.WriteLine("\nWeights BEFORE update:"); for (int i = 0; i < weightsBeforeUpdate.GetLength(0); i++) { for (int j = 0; j < weightsBeforeUpdate.GetLength(1); j++) Console.Write("{0} ", weightsBeforeUpdate[i, j]); Console.WriteLine(); } Console.WriteLine(); Console.ReadKey(); // Display biases before update float[] biasesBeforeUpdate = new float[output.NumberOfUnits]; #if OPENCL_ENABLED OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, biasesGPU, // source Bool.True, (IntPtr)0, (IntPtr)(output.NumberOfUnits * sizeof(float)), biasesBeforeUpdate, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer biasesBeforeUpdate"); #else biasesBeforeUpdate = biases; #endif Console.WriteLine("\nBiases BEFORE update:"); for (int i = 0; i < biasesBeforeUpdate.Length; i++) { Console.Write("{0} ", biasesBeforeUpdate[i]); } Console.WriteLine(); Console.ReadKey(); // Display weight update speed before update float[,] tmpWeightsUpdateSpeed = new float[output.NumberOfUnits, input.NumberOfUnits]; #if OPENCL_ENABLED OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, weightsUpdateSpeedGPU, // source Bool.True, (IntPtr)0, (IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)), tmpWeightsUpdateSpeed, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsUpdateSpeed"); #else tmpWeightsUpdateSpeed = weightsUpdateSpeed; #endif Console.WriteLine("\nWeight update speed BEFORE update:"); for (int i = 0; i < tmpWeightsUpdateSpeed.GetLength(0); i++) { for (int j = 0; j < tmpWeightsUpdateSpeed.GetLength(1); j++) Console.Write("{0} ", tmpWeightsUpdateSpeed[i, j]); Console.WriteLine(); } Console.WriteLine(); Console.ReadKey(); // Display input activations before update /* float[] inputActivations = new float[input.NumberOfUnits]; OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, input.ActivationsGPU, // source Bool.True, (IntPtr)0, (IntPtr)(input.NumberOfUnits * sizeof(float)), inputActivations, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer inputActivations"); Console.WriteLine("\nInput activations BEFORE update:"); for (int j = 0; j < inputActivations.Length; j++) { Console.Write("{0} ", inputActivations[j]); } Console.WriteLine(); Console.ReadKey(); // Display output delta before update float[] outputDelta = new float[output.NumberOfUnits]; OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, output.DeltaGPU, // source Bool.True, (IntPtr)0, (IntPtr)(output.NumberOfUnits * sizeof(float)), outputDelta, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer outputDelta"); Console.WriteLine("\nOutput delta BEFORE update:"); for (int i = 0; i < outputDelta.Length; i++) { Console.Write("{0}", outputDelta[i]); Console.WriteLine(); } Console.WriteLine(); Console.ReadKey(); */ /*------------------------- END DEBUGGING --------------------------------------------- */ #endif #if OPENCL_ENABLED // Set kernel arguments OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 0, weightsSpeedGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 1, biasesSpeedGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 2, weightsGradientsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 3, biasesGradientsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 4, inputNeurons.ActivationsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 5, outputNeurons.DeltaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 6, dropoutMaskGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 7, (IntPtr)sizeof(int), nInputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 8, (IntPtr)sizeof(int), nOutputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 9, (IntPtr)sizeof(float), (float)momentumCoefficient); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 10, (IntPtr)sizeof(float), (float)learningRate); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 11, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 12, weightsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 13, (IntPtr)sizeof(float), (float)weightDecayCoefficient); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.SetKernelArg"); // Run kernel OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue, OpenCLSpace.FCUpdateSpeeds, 2, null, updateGlobalWorkSizePtr, updateLocalWorkSizePtr, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.EnqueueNDRangeKernel"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); #else int miniBatchSize = inputNeurons.MiniBatchSize; for (int m = 0; m < miniBatchSize; m++) { for (int i = 0; i < nOutputUnits; i++) { // weights speed for (int j = 0; j < nInputUnits; j++) { if (m == 0) weightsUpdateSpeed[i, j] *= momentumCoefficient; weightsUpdateSpeed[i, j] -= learningRate/miniBatchSize * inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i]; #if GRADIENT_CHECK weightsGradients[i, j] = inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i]; #endif } // update biases if (m == 0) biasesUpdateSpeed[i] *= momentumCoefficient; biasesUpdateSpeed[i] -= learningRate/miniBatchSize * outputNeurons.DeltaHost[m][i]; #if GRADIENT_CHECK biasesGradients[i] = outputNeurons.DeltaHost[m][i]; #endif } } // end loop over mini-batch #endif #if TIMING_LAYERS Utils.FCUpdateSpeedsTimer.Stop(); #endif } public override void UpdateParameters(double weightMaxNorm) { #if TIMING_LAYERS Utils.FCUpdateParametersTimer.Start(); #endif #if OPENCL_ENABLED // Set kernel arguments OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 0, weightsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 1, biasesGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 2, weightsSpeedGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 3, biasesSpeedGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 4, (IntPtr)sizeof(int), nInputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 5, (IntPtr)sizeof(int), nOutputUnits); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.SetKernelArg"); // Run kernel OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue, OpenCLSpace.FCUpdateParameters, 2, null, updateGlobalWorkSizePtr, updateLocalWorkSizePtr, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.EnqueueNDRangeKernel"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); // Now constrain norm of each weight vector if (!double.IsInfinity(weightMaxNorm)) { // Set kernel arguments OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 0, weightsGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 1, (IntPtr)sizeof(int), nOutputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 2, (IntPtr)sizeof(int), nInputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 3, (IntPtr)sizeof(float), (float)weightMaxNorm); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.SetKernelArg"); // Run kernel OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel(OpenCLSpace.Queue, OpenCLSpace.FCConstrainWeightNorm, 1, null, constrainNormGlobalWorkSizePtr, constrainNormLocalWorkSizePtr, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.EnqueueNDRangeKernel"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); } OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); #else for (int i = 0; i < nOutputUnits; i++) { // weights update for (int j = 0; j < nInputUnits; j++) { weights[i, j] += weightsUpdateSpeed[i, j]; } // update biases biases[i] += biasesUpdateSpeed[i]; } #endif #if TIMING_LAYERS Utils.FCUpdateParametersTimer.Stop(); #endif } #endregion #region Gradient check public override double[] GetParameters() { int nParameters = nInputUnits * nOutputUnits + nOutputUnits; double[] parameters = new double[nParameters]; // Copy weights and biases buffers to host float[] tmpWeights = new float[nInputUnits * nOutputUnits]; OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, weightsGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nInputUnits * nOutputUnits), tmpWeights, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); float[] tmpBiases = new float[nOutputUnits]; OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, biasesGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nOutputUnits), tmpBiases, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); // Convert to double and write into parameters array for (int i = 0; i < nInputUnits*nOutputUnits; ++i) { parameters[i] = (double)tmpWeights[i]; } for (int i = 0; i < nOutputUnits; ++i) { parameters[nInputUnits * nOutputUnits + i] = (double)tmpBiases[i]; } return parameters; } public override double[] GetParameterGradients() { int nParameters = nInputUnits * nOutputUnits + nOutputUnits; double[] parameterGradients = new double[nParameters]; // Copy weights and biases gradients buffers to host float[] tmpWeightsGrad = new float[nInputUnits * nOutputUnits]; OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, weightsGradientsGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nInputUnits * nOutputUnits), tmpWeightsGrad, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); float[] tmpBiasesGrad = new float[nOutputUnits]; OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, biasesGradientsGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nOutputUnits), tmpBiasesGrad, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); // Convert to double and write into parameterGradients //Console.WriteLine("Weight gradients:\n"); for (int i = 0; i < nInputUnits * nOutputUnits; ++i) { parameterGradients[i] = (double)tmpWeightsGrad[i]; //Console.Write(" {0}", tmpWeightsGrad[i]); } //Console.ReadKey(); for (int i = 0; i < nOutputUnits; ++i) { parameterGradients[nInputUnits * nOutputUnits + i] = (double)tmpBiasesGrad[i]; } return parameterGradients; } public override void SetParameters(double[] NewParameters) { // Convert to float and write into tmp arrays float[] tmpWeights = new float[nInputUnits * nOutputUnits]; float[] tmpBiases = new float[nOutputUnits]; for (int i = 0; i < nInputUnits * nOutputUnits; ++i) { tmpWeights[i] = (float)NewParameters[i]; } for (int i = 0; i < nOutputUnits; ++i) { tmpBiases[i] = (float)NewParameters[nInputUnits * nOutputUnits + i]; } // Write arrays into buffers on device OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue, weightsGPU, OpenCL.Net.Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nInputUnits * nOutputUnits), tmpWeights, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue, biasesGPU, OpenCL.Net.Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nOutputUnits), tmpBiases, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); } #endregion } }
Java
# Contributing to Viewer ## How to report bugs ### Make sure it is a Viewer bug Most bugs reported to our bug tracker are actually bugs in user code, not in Viewer code. Keep in mind that just because your code throws an error inside of Viewer, this does *not* mean the bug is a Viewer bug. Ask for help first in a discussion forum like [Stack Overflow](http://stackoverflow.com/). You will get much quicker support, and you will help avoid tying up the Viewer team with invalid bug reports. ### Disable browser extensions Make sure you have reproduced the bug with all browser extensions and add-ons disabled, as these can sometimes cause things to break in interesting and unpredictable ways. Try using incognito, stealth or anonymous browsing modes. ### Try the latest version of Viewer Bugs in old versions of Viewer may have already been fixed. In order to avoid reporting known issues, make sure you are always testing against the [latest release](https://github.com/fengyuanchen/viewerjs/releases/latest). We cannot fix bugs in older released files, if a bug has been fixed in a subsequent version of Viewer the site should upgrade. ### Simplify the test case When experiencing a problem, [reduce your code](http://webkit.org/quality/reduction.html) to the bare minimum required to reproduce the issue. This makes it *much* easier to isolate and fix the offending code. Bugs reported without reduced test cases take on average 9001% longer to fix than bugs that are submitted with them, so you really should try to do this if at all possible. ### Search for related or duplicate issues Go to the [Viewer issue tracker](https://github.com/fengyuanchen/viewerjs/issues) and make sure the problem hasn't already been reported. If not, create a new issue there and include your test case. ### Browser support Remember that Viewer supports multiple browsers and their versions; any contributed code must work in all of them. You can refer to the [browser support page](README.md#browser-support) for the current list of supported browsers. ## Notes for pull request - Run the test suites in the `test` directory first. - Don't modify any files in the `dist` directory. - Follow the same code style as the library.
Java
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Code\Scanner; use Zend\Code\Annotation\AnnotationManager; use Zend\Code\Exception; use Zend\Code\NameInformation; use function array_slice; use function count; use function is_int; use function is_string; use function ltrim; use function strtolower; use function substr_count; use function var_export; class MethodScanner implements ScannerInterface { /** * @var bool */ protected $isScanned = false; /** * @var string */ protected $docComment; /** * @var ClassScanner */ protected $scannerClass; /** * @var string */ protected $class; /** * @var string */ protected $name; /** * @var int */ protected $lineStart; /** * @var int */ protected $lineEnd; /** * @var bool */ protected $isFinal = false; /** * @var bool */ protected $isAbstract = false; /** * @var bool */ protected $isPublic = true; /** * @var bool */ protected $isProtected = false; /** * @var bool */ protected $isPrivate = false; /** * @var bool */ protected $isStatic = false; /** * @var string */ protected $body = ''; /** * @var array */ protected $tokens = []; /** * @var NameInformation */ protected $nameInformation; /** * @var array */ protected $infos = []; /** * @param array $methodTokens * @param NameInformation $nameInformation */ public function __construct(array $methodTokens, NameInformation $nameInformation = null) { $this->tokens = $methodTokens; $this->nameInformation = $nameInformation; } /** * @param string $class * @return MethodScanner */ public function setClass($class) { $this->class = (string) $class; return $this; } /** * @param ClassScanner $scannerClass * @return MethodScanner */ public function setScannerClass(ClassScanner $scannerClass) { $this->scannerClass = $scannerClass; return $this; } /** * @return ClassScanner */ public function getClassScanner() { return $this->scannerClass; } /** * @return string */ public function getName() { $this->scan(); return $this->name; } /** * @return int */ public function getLineStart() { $this->scan(); return $this->lineStart; } /** * @return int */ public function getLineEnd() { $this->scan(); return $this->lineEnd; } /** * @return string */ public function getDocComment() { $this->scan(); return $this->docComment; } /** * @param AnnotationManager $annotationManager * @return AnnotationScanner|false */ public function getAnnotations(AnnotationManager $annotationManager) { if (($docComment = $this->getDocComment()) == '') { return false; } return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation); } /** * @return bool */ public function isFinal() { $this->scan(); return $this->isFinal; } /** * @return bool */ public function isAbstract() { $this->scan(); return $this->isAbstract; } /** * @return bool */ public function isPublic() { $this->scan(); return $this->isPublic; } /** * @return bool */ public function isProtected() { $this->scan(); return $this->isProtected; } /** * @return bool */ public function isPrivate() { $this->scan(); return $this->isPrivate; } /** * @return bool */ public function isStatic() { $this->scan(); return $this->isStatic; } /** * Override the given name for a method, this is necessary to * support traits. * * @param string $name * @return self */ public function setName($name) { $this->name = $name; return $this; } /** * Visibility must be of T_PUBLIC, T_PRIVATE or T_PROTECTED * Needed to support traits * * @param int $visibility T_PUBLIC | T_PRIVATE | T_PROTECTED * @return self * @throws \Zend\Code\Exception\InvalidArgumentException */ public function setVisibility($visibility) { switch ($visibility) { case T_PUBLIC: $this->isPublic = true; $this->isPrivate = false; $this->isProtected = false; break; case T_PRIVATE: $this->isPublic = false; $this->isPrivate = true; $this->isProtected = false; break; case T_PROTECTED: $this->isPublic = false; $this->isPrivate = false; $this->isProtected = true; break; default: throw new Exception\InvalidArgumentException('Invalid visibility argument passed to setVisibility.'); } return $this; } /** * @return int */ public function getNumberOfParameters() { return count($this->getParameters()); } /** * @param bool $returnScanner * @return array */ public function getParameters($returnScanner = false) { $this->scan(); $return = []; foreach ($this->infos as $info) { if ($info['type'] != 'parameter') { continue; } if (! $returnScanner) { $return[] = $info['name']; } else { $return[] = $this->getParameter($info['name']); } } return $return; } /** * @param int|string $parameterNameOrInfoIndex * @return ParameterScanner * @throws Exception\InvalidArgumentException */ public function getParameter($parameterNameOrInfoIndex) { $this->scan(); if (is_int($parameterNameOrInfoIndex)) { $info = $this->infos[$parameterNameOrInfoIndex]; if ($info['type'] != 'parameter') { throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter'); } } elseif (is_string($parameterNameOrInfoIndex)) { foreach ($this->infos as $info) { if ($info['type'] === 'parameter' && $info['name'] === $parameterNameOrInfoIndex) { break; } unset($info); } if (! isset($info)) { throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter'); } } $p = new ParameterScanner( array_slice($this->tokens, $info['tokenStart'], $info['tokenEnd'] - $info['tokenStart']), $this->nameInformation ); $p->setDeclaringFunction($this->name); $p->setDeclaringScannerFunction($this); $p->setDeclaringClass($this->class); $p->setDeclaringScannerClass($this->scannerClass); $p->setPosition($info['position']); return $p; } /** * @return string */ public function getBody() { $this->scan(); return $this->body; } public static function export() { // @todo } public function __toString() { $this->scan(); return var_export($this, true); } protected function scan() { if ($this->isScanned) { return; } if (! $this->tokens) { throw new Exception\RuntimeException('No tokens were provided'); } /** * Variables & Setup */ $tokens = &$this->tokens; // localize $infos = &$this->infos; // localize $tokenIndex = null; $token = null; $tokenType = null; $tokenContent = null; $tokenLine = null; $infoIndex = 0; $parentCount = 0; /* * MACRO creation */ $MACRO_TOKEN_ADVANCE = function () use ( &$tokens, &$tokenIndex, &$token, &$tokenType, &$tokenContent, &$tokenLine ) { static $lastTokenArray = null; $tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1; if (! isset($tokens[$tokenIndex])) { $token = false; $tokenContent = false; $tokenType = false; $tokenLine = false; return false; } $token = $tokens[$tokenIndex]; if (is_string($token)) { $tokenType = null; $tokenContent = $token; $tokenLine += substr_count( $lastTokenArray[1] ?? '', "\n" ); // adjust token line by last known newline count } else { $lastTokenArray = $token; [$tokenType, $tokenContent, $tokenLine] = $token; } return $tokenIndex; }; $MACRO_INFO_START = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) { $infos[$infoIndex] = [ 'type' => 'parameter', 'tokenStart' => $tokenIndex, 'tokenEnd' => null, 'lineStart' => $tokenLine, 'lineEnd' => $tokenLine, 'name' => null, 'position' => $infoIndex + 1, // position is +1 of infoIndex ]; }; $MACRO_INFO_ADVANCE = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) { $infos[$infoIndex]['tokenEnd'] = $tokenIndex; $infos[$infoIndex]['lineEnd'] = $tokenLine; $infoIndex++; return $infoIndex; }; /** * START FINITE STATE MACHINE FOR SCANNING TOKENS */ // Initialize token $MACRO_TOKEN_ADVANCE(); SCANNER_TOP: $this->lineStart = $this->lineStart ? : $tokenLine; switch ($tokenType) { case T_DOC_COMMENT: $this->lineStart = null; if ($this->docComment === null && $this->name === null) { $this->docComment = $tokenContent; } goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_FINAL: $this->isFinal = true; goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_ABSTRACT: $this->isAbstract = true; goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_PUBLIC: // use defaults goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_PROTECTED: $this->setVisibility(T_PROTECTED); goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_PRIVATE: $this->setVisibility(T_PRIVATE); goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_STATIC: $this->isStatic = true; goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_NS_SEPARATOR: if (! isset($infos[$infoIndex])) { $MACRO_INFO_START(); } goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case T_VARIABLE: case T_STRING: if ($tokenType === T_STRING && $parentCount === 0) { $this->name = $tokenContent; } if ($parentCount === 1) { if (! isset($infos[$infoIndex])) { $MACRO_INFO_START(); } if ($tokenType === T_VARIABLE) { $infos[$infoIndex]['name'] = ltrim($tokenContent, '$'); } } goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case null: switch ($tokenContent) { case '&': if (! isset($infos[$infoIndex])) { $MACRO_INFO_START(); } goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case '(': $parentCount++; goto SCANNER_CONTINUE_SIGNATURE; // goto (no break needed); case ')': $parentCount--; if ($parentCount > 0) { goto SCANNER_CONTINUE_SIGNATURE; } if ($parentCount === 0) { if ($infos) { $MACRO_INFO_ADVANCE(); } $context = 'body'; } goto SCANNER_CONTINUE_BODY; // goto (no break needed); case ',': if ($parentCount === 1) { $MACRO_INFO_ADVANCE(); } goto SCANNER_CONTINUE_SIGNATURE; } } SCANNER_CONTINUE_SIGNATURE: if ($MACRO_TOKEN_ADVANCE() === false) { goto SCANNER_END; } goto SCANNER_TOP; SCANNER_CONTINUE_BODY: $braceCount = 0; while ($MACRO_TOKEN_ADVANCE() !== false) { if ($tokenContent == '}') { $braceCount--; } if ($braceCount > 0) { $this->body .= $tokenContent; } if ($tokenContent == '{') { $braceCount++; } $this->lineEnd = $tokenLine; } SCANNER_END: $this->isScanned = true; } }
Java
<?php /** * Copyright © OXID eSales AG. All rights reserved. * See LICENSE file for license details. */ declare(strict_types=1); namespace OxidEsales\EshopCommunity\Internal\Framework\Module\Configuration\Exception; class ProjectConfigurationIsEmptyException extends \Exception { }
Java
% This is part of Exercices et corrigés de CdI-1 % Copyright (c) 2011 % Laurent Claessens % See the file fdl-1.3.txt for copying conditions. \begin{exercice}\label{exoEqsDiff0005} Soit $p(t)$ le nombre d'individus d'une population à l'instant $t$. Un modèle de population classique et très simple est celui régi par $p' = K p$ où $K \in \eR$ est le taux de croissance de la population (taux de natalité moins le taux de mortalité). La résolution de cette équation différentielle montre que la croissance de la population est exponentielle, ce qui est généralement satisfaisant tant qu'il n'y a pas de problèmes de surpopulation (territoire et ressource illimités). Pour tenir compte de tels problèmes, on suppose plutôt que $p$ est régie par l'équation différentielle $p' = Kp(M-p)$ où $M \in \eR_0^+$ est le seuil de surpopulation. \begin{enumerate} \item Sachant que $p(0) = p_0$ déterminez $p(t)$. \item Déterminez le comportement de $p(t)$ lorsque $t$ tend vers $+\infty $. \item Dessiner le champ de pentes correspondant à cette équation et en déduire l'allure des solutions sans utiliser la résolution de l'équation différentielle. Remarquez que $p=M$ est une solution stable, alors que $p=0$ est instable. \end{enumerate} \end{exercice}
Java
#ifndef __AGENT_H #define __AGENT_H #include "libssh/libssh.h" /* Messages for the authentication agent connection. */ #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 #define SSH_AGENTC_RSA_CHALLENGE 3 #define SSH_AGENT_RSA_RESPONSE 4 #define SSH_AGENT_FAILURE 5 #define SSH_AGENT_SUCCESS 6 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 #define SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES 9 /* private OpenSSH extensions for SSH2 */ #define SSH2_AGENTC_REQUEST_IDENTITIES 11 #define SSH2_AGENT_IDENTITIES_ANSWER 12 #define SSH2_AGENTC_SIGN_REQUEST 13 #define SSH2_AGENT_SIGN_RESPONSE 14 #define SSH2_AGENTC_ADD_IDENTITY 17 #define SSH2_AGENTC_REMOVE_IDENTITY 18 #define SSH2_AGENTC_REMOVE_ALL_IDENTITIES 19 /* smartcard */ #define SSH_AGENTC_ADD_SMARTCARD_KEY 20 #define SSH_AGENTC_REMOVE_SMARTCARD_KEY 21 /* lock/unlock the agent */ #define SSH_AGENTC_LOCK 22 #define SSH_AGENTC_UNLOCK 23 /* add key with constraints */ #define SSH_AGENTC_ADD_RSA_ID_CONSTRAINED 24 #define SSH2_AGENTC_ADD_ID_CONSTRAINED 25 #define SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED 26 #define SSH_AGENT_CONSTRAIN_LIFETIME 1 #define SSH_AGENT_CONSTRAIN_CONFIRM 2 /* extended failure messages */ #define SSH2_AGENT_FAILURE 30 /* additional error code for ssh.com's ssh-agent2 */ #define SSH_COM_AGENT2_FAILURE 102 #define SSH_AGENT_OLD_SIGNATURE 0x01 struct ssh_agent_struct { struct socket *sock; ssh_buffer ident; unsigned int count; }; #ifndef _WIN32 /* agent.c */ /** * @brief Create a new ssh agent structure. * * @return An allocated ssh agent structure or NULL on error. */ struct ssh_agent_struct *agent_new(struct ssh_session_struct *session); void agent_close(struct ssh_agent_struct *agent); /** * @brief Free an allocated ssh agent structure. * * @param agent The ssh agent structure to free. */ void agent_free(struct ssh_agent_struct *agent); /** * @brief Check if the ssh agent is running. * * @param session The ssh session to check for the agent. * * @return 1 if it is running, 0 if not. */ int agent_is_running(struct ssh_session_struct *session); int agent_get_ident_count(struct ssh_session_struct *session); struct ssh_public_key_struct *agent_get_next_ident(struct ssh_session_struct *session, char **comment); struct ssh_public_key_struct *agent_get_first_ident(struct ssh_session_struct *session, char **comment); ssh_string agent_sign_data(struct ssh_session_struct *session, struct ssh_buffer_struct *data, struct ssh_public_key_struct *pubkey); #endif #endif /* __AGENT_H */ /* vim: set ts=2 sw=2 et cindent: */
Java
/* Copyright 2013 Red Hat, Inc. and/or its affiliates. This file is part of lightblue. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.redhat.lightblue.config; import org.junit.Assert; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.redhat.lightblue.Request; import com.redhat.lightblue.crud.DeleteRequest; import com.redhat.lightblue.util.test.FileUtil; import static com.redhat.lightblue.util.JsonUtils.json; public class CrudValidationTest { @Test public void testValidInputWithNonValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, false); String jsonString = FileUtil.readFile("valid-deletion-req.json"); JsonNode node = json(jsonString); DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.assertNotNull(req); } @Test public void testInvalidInputWithNonValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, false); String jsonString = FileUtil.readFile("invalid-deletion-req.json"); JsonNode node = json(jsonString); DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.assertNotNull(req); } @Test public void testValidInputWithValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, true); String jsonString = FileUtil.readFile("valid-deletion-req.json"); JsonNode node = json(jsonString); DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.assertNotNull(req); } @Test public void testInvalidInputWithValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, true); String jsonString = FileUtil.readFile("invalid-deletion-req.json"); JsonNode node = json(jsonString); try { lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.fail(); } catch (Exception e) { System.out.println(e); } } }
Java
#pragma once #include <WeaselIPC.h> struct KeyInfo { UINT repeatCount: 16; UINT scanCode: 8; UINT isExtended: 1; UINT reserved: 4; UINT contextCode: 1; UINT prevKeyState: 1; UINT isKeyUp: 1; KeyInfo(LPARAM lparam) { *this = *reinterpret_cast<KeyInfo*>(&lparam); } operator UINT32() { return *reinterpret_cast<UINT32*>(this); } }; bool ConvertKeyEvent(UINT vkey, KeyInfo kinfo, const LPBYTE keyState, weasel::KeyEvent& result); namespace ibus { // keycodes enum Keycode { VoidSymbol = 0xFFFFFF, space = 0x020, grave = 0x060, BackSpace = 0xFF08, Tab = 0xFF09, Linefeed = 0xFF0A, Clear = 0xFF0B, Return = 0xFF0D, Pause = 0xFF13, Scroll_Lock = 0xFF14, Sys_Req = 0xFF15, Escape = 0xFF1B, Delete = 0xFFFF, Multi_key = 0xFF20, Codeinput = 0xFF37, SingleCandidate = 0xFF3C, MultipleCandidate = 0xFF3D, PreviousCandidate = 0xFF3E, Kanji = 0xFF21, Muhenkan = 0xFF22, Henkan_Mode = 0xFF23, Henkan = 0xFF23, Romaji = 0xFF24, Hiragana = 0xFF25, Katakana = 0xFF26, Hiragana_Katakana = 0xFF27, Zenkaku = 0xFF28, Hankaku = 0xFF29, Zenkaku_Hankaku = 0xFF2A, Touroku = 0xFF2B, Massyo = 0xFF2C, Kana_Lock = 0xFF2D, Kana_Shift = 0xFF2E, Eisu_Shift = 0xFF2F, Eisu_toggle = 0xFF30, Kanji_Bangou = 0xFF37, Zen_Koho = 0xFF3D, Mae_Koho = 0xFF3E, Home = 0xFF50, Left = 0xFF51, Up = 0xFF52, Right = 0xFF53, Down = 0xFF54, Prior = 0xFF55, Page_Up = 0xFF55, Next = 0xFF56, Page_Down = 0xFF56, End = 0xFF57, Begin = 0xFF58, Select = 0xFF60, Print = 0xFF61, Execute = 0xFF62, Insert = 0xFF63, Undo = 0xFF65, Redo = 0xFF66, Menu = 0xFF67, Find = 0xFF68, Cancel = 0xFF69, Help = 0xFF6A, Break = 0xFF6B, Mode_switch = 0xFF7E, script_switch = 0xFF7E, Num_Lock = 0xFF7F, KP_Space = 0xFF80, KP_Tab = 0xFF89, KP_Enter = 0xFF8D, KP_F1 = 0xFF91, KP_F2 = 0xFF92, KP_F3 = 0xFF93, KP_F4 = 0xFF94, KP_Home = 0xFF95, KP_Left = 0xFF96, KP_Up = 0xFF97, KP_Right = 0xFF98, KP_Down = 0xFF99, KP_Prior = 0xFF9A, KP_Page_Up = 0xFF9A, KP_Next = 0xFF9B, KP_Page_Down = 0xFF9B, KP_End = 0xFF9C, KP_Begin = 0xFF9D, KP_Insert = 0xFF9E, KP_Delete = 0xFF9F, KP_Equal = 0xFFBD, KP_Multiply = 0xFFAA, KP_Add = 0xFFAB, KP_Separator = 0xFFAC, KP_Subtract = 0xFFAD, KP_Decimal = 0xFFAE, KP_Divide = 0xFFAF, KP_0 = 0xFFB0, KP_1 = 0xFFB1, KP_2 = 0xFFB2, KP_3 = 0xFFB3, KP_4 = 0xFFB4, KP_5 = 0xFFB5, KP_6 = 0xFFB6, KP_7 = 0xFFB7, KP_8 = 0xFFB8, KP_9 = 0xFFB9, F1 = 0xFFBE, F2 = 0xFFBF, F3 = 0xFFC0, F4 = 0xFFC1, F5 = 0xFFC2, F6 = 0xFFC3, F7 = 0xFFC4, F8 = 0xFFC5, F9 = 0xFFC6, F10 = 0xFFC7, F11 = 0xFFC8, L1 = 0xFFC8, F12 = 0xFFC9, L2 = 0xFFC9, F13 = 0xFFCA, L3 = 0xFFCA, F14 = 0xFFCB, L4 = 0xFFCB, F15 = 0xFFCC, L5 = 0xFFCC, F16 = 0xFFCD, L6 = 0xFFCD, F17 = 0xFFCE, L7 = 0xFFCE, F18 = 0xFFCF, L8 = 0xFFCF, F19 = 0xFFD0, L9 = 0xFFD0, F20 = 0xFFD1, L10 = 0xFFD1, F21 = 0xFFD2, R1 = 0xFFD2, F22 = 0xFFD3, R2 = 0xFFD3, F23 = 0xFFD4, R3 = 0xFFD4, F24 = 0xFFD5, R4 = 0xFFD5, F25 = 0xFFD6, R5 = 0xFFD6, F26 = 0xFFD7, R6 = 0xFFD7, F27 = 0xFFD8, R7 = 0xFFD8, F28 = 0xFFD9, R8 = 0xFFD9, F29 = 0xFFDA, R9 = 0xFFDA, F30 = 0xFFDB, R10 = 0xFFDB, F31 = 0xFFDC, R11 = 0xFFDC, F32 = 0xFFDD, R12 = 0xFFDD, F33 = 0xFFDE, R13 = 0xFFDE, F34 = 0xFFDF, R14 = 0xFFDF, F35 = 0xFFE0, R15 = 0xFFE0, Shift_L = 0xFFE1, Shift_R = 0xFFE2, Control_L = 0xFFE3, Control_R = 0xFFE4, Caps_Lock = 0xFFE5, Shift_Lock = 0xFFE6, Meta_L = 0xFFE7, Meta_R = 0xFFE8, Alt_L = 0xFFE9, Alt_R = 0xFFEA, Super_L = 0xFFEB, Super_R = 0xFFEC, Hyper_L = 0xFFED, Hyper_R = 0xFFEE, Null = 0 }; // modifiers, modified to fit a UINT16 enum Modifier { NULL_MASK = 0, SHIFT_MASK = 1 << 0, LOCK_MASK = 1 << 1, CONTROL_MASK = 1 << 2, ALT_MASK = 1 << 3, MOD1_MASK = 1 << 3, MOD2_MASK = 1 << 4, MOD3_MASK = 1 << 5, MOD4_MASK = 1 << 6, MOD5_MASK = 1 << 7, HANDLED_MASK = 1 << 8, // 24 IGNORED_MASK = 1 << 9, // 25 FORWARD_MASK = 1 << 9, // 25 SUPER_MASK = 1 << 10, // 26 HYPER_MASK = 1 << 11, // 27 META_MASK = 1 << 12, // 28 RELEASE_MASK = 1 << 14, // 30 MODIFIER_MASK = 0x2fff }; }
Java
/* * Copyright (c) 2018 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.mica.micaConfig.service; import org.obiba.mica.micaConfig.domain.PopulationConfig; import org.obiba.mica.micaConfig.repository.PopulationConfigRepository; import org.springframework.stereotype.Component; import javax.inject.Inject; @Component public class PopulationConfigService extends EntityConfigService<PopulationConfig> { @Inject PopulationConfigRepository populationConfigRepository; @Override protected PopulationConfigRepository getRepository() { return populationConfigRepository; } @Override protected String getDefaultId() { return "default"; } @Override protected PopulationConfig createEmptyForm() { return new PopulationConfig(); } @Override protected String getDefaultDefinitionResourcePath() { return "classpath:config/population-form/definition.json"; } @Override protected String getMandatoryDefinitionResourcePath() { return "classpath:config/population-form/definition-mandatory.json"; } @Override protected String getDefaultSchemaResourcePath() { return "classpath:config/population-form/schema.json"; } @Override protected String getMandatorySchemaResourcePath() { return "classpath:config/population-form/schema-mandatory.json"; } }
Java
/* * This file is part of the libsigrok project. * * Copyright (C) 2010 Uwe Hermann <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ /* Needed for POSIX.1-2008 locale functions */ /** @cond PRIVATE */ #define _XOPEN_SOURCE 700 /** @endcond */ #include <config.h> #include <ctype.h> #include <locale.h> #if defined(__FreeBSD__) || defined(__APPLE__) #include <xlocale.h> #endif #if defined(__FreeBSD__) #include <sys/param.h> #endif #include <stdint.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <errno.h> #include <libsigrok/libsigrok.h> #include "libsigrok-internal.h" /** @cond PRIVATE */ #define LOG_PREFIX "strutil" /** @endcond */ /** * @file * * Helper functions for handling or converting libsigrok-related strings. */ /** * @defgroup grp_strutil String utilities * * Helper functions for handling or converting libsigrok-related strings. * * @{ */ /** * Convert a string representation of a numeric value (base 10) to a long integer. The * conversion is strict and will fail if the complete string does not represent * a valid long integer. The function sets errno according to the details of the * failure. * * @param str The string representation to convert. * @param ret Pointer to long where the result of the conversion will be stored. * * @retval SR_OK Conversion successful. * @retval SR_ERR Failure. * * @private */ SR_PRIV int sr_atol(const char *str, long *ret) { long tmp; char *endptr = NULL; errno = 0; tmp = strtol(str, &endptr, 10); while (endptr && isspace(*endptr)) endptr++; if (!endptr || *endptr || errno) { if (!errno) errno = EINVAL; return SR_ERR; } *ret = tmp; return SR_OK; } /** * Convert a text to a number including support for non-decimal bases. * Also optionally returns the position after the number, where callers * can either error out, or support application specific suffixes. * * @param[in] str The input text to convert. * @param[out] ret The conversion result. * @param[out] end The position after the number. * @param[in] base The number format's base, can be 0. * * @retval SR_OK Conversion successful. * @retval SR_ERR Conversion failed. * * @private * * This routine is more general than @ref sr_atol(), which strictly * expects the input text to contain just a decimal number, and nothing * else in addition. The @ref sr_atol_base() routine accepts trailing * text after the number, and supports non-decimal numbers (bin, hex), * including automatic detection from prefix text. */ SR_PRIV int sr_atol_base(const char *str, long *ret, char **end, int base) { long num; char *endptr; /* Add "0b" prefix support which strtol(3) may be missing. */ while (str && isspace(*str)) str++; if (!base && strncmp(str, "0b", strlen("0b")) == 0) { str += strlen("0b"); base = 2; } /* Run the number conversion. Quick bail out if that fails. */ errno = 0; endptr = NULL; num = strtol(str, &endptr, base); if (!endptr || errno) { if (!errno) errno = EINVAL; return SR_ERR; } *ret = num; /* Advance to optional non-space trailing suffix. */ while (endptr && isspace(*endptr)) endptr++; if (end) *end = endptr; return SR_OK; } /** * Convert a string representation of a numeric value (base 10) to an integer. The * conversion is strict and will fail if the complete string does not represent * a valid integer. The function sets errno according to the details of the * failure. * * @param str The string representation to convert. * @param ret Pointer to int where the result of the conversion will be stored. * * @retval SR_OK Conversion successful. * @retval SR_ERR Failure. * * @private */ SR_PRIV int sr_atoi(const char *str, int *ret) { long tmp; if (sr_atol(str, &tmp) != SR_OK) return SR_ERR; if ((int) tmp != tmp) { errno = ERANGE; return SR_ERR; } *ret = (int) tmp; return SR_OK; } /** * Convert a string representation of a numeric value to a double. The * conversion is strict and will fail if the complete string does not represent * a valid double. The function sets errno according to the details of the * failure. * * @param str The string representation to convert. * @param ret Pointer to double where the result of the conversion will be stored. * * @retval SR_OK Conversion successful. * @retval SR_ERR Failure. * * @private */ SR_PRIV int sr_atod(const char *str, double *ret) { double tmp; char *endptr = NULL; errno = 0; tmp = strtof(str, &endptr); while (endptr && isspace(*endptr)) endptr++; if (!endptr || *endptr || errno) { if (!errno) errno = EINVAL; return SR_ERR; } *ret = tmp; return SR_OK; } /** * Convert a string representation of a numeric value to a float. The * conversion is strict and will fail if the complete string does not represent * a valid float. The function sets errno according to the details of the * failure. * * @param str The string representation to convert. * @param ret Pointer to float where the result of the conversion will be stored. * * @retval SR_OK Conversion successful. * @retval SR_ERR Failure. * * @private */ SR_PRIV int sr_atof(const char *str, float *ret) { double tmp; if (sr_atod(str, &tmp) != SR_OK) return SR_ERR; if ((float) tmp != tmp) { errno = ERANGE; return SR_ERR; } *ret = (float) tmp; return SR_OK; } /** * Convert a string representation of a numeric value to a double. The * conversion is strict and will fail if the complete string does not represent * a valid double. The function sets errno according to the details of the * failure. This version ignores the locale. * * @param str The string representation to convert. * @param ret Pointer to double where the result of the conversion will be stored. * * @retval SR_OK Conversion successful. * @retval SR_ERR Failure. * * @private */ SR_PRIV int sr_atod_ascii(const char *str, double *ret) { double tmp; char *endptr = NULL; errno = 0; tmp = g_ascii_strtod(str, &endptr); if (!endptr || *endptr || errno) { if (!errno) errno = EINVAL; return SR_ERR; } *ret = tmp; return SR_OK; } /** * Convert a string representation of a numeric value to a float. The * conversion is strict and will fail if the complete string does not represent * a valid float. The function sets errno according to the details of the * failure. This version ignores the locale. * * @param str The string representation to convert. * @param ret Pointer to float where the result of the conversion will be stored. * * @retval SR_OK Conversion successful. * @retval SR_ERR Failure. * * @private */ SR_PRIV int sr_atof_ascii(const char *str, float *ret) { double tmp; char *endptr = NULL; errno = 0; tmp = g_ascii_strtod(str, &endptr); if (!endptr || *endptr || errno) { if (!errno) errno = EINVAL; return SR_ERR; } /* FIXME This fails unexpectedly. Some other method to safel downcast * needs to be found. Checking against FLT_MAX doesn't work as well. */ /* if ((float) tmp != tmp) { errno = ERANGE; sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp); return SR_ERR; } */ *ret = (float) tmp; return SR_OK; } /** * Compose a string with a format string in the buffer pointed to by buf. * * It is up to the caller to ensure that the allocated buffer is large enough * to hold the formatted result. * * A terminating NUL character is automatically appended after the content * written. * * After the format parameter, the function expects at least as many additional * arguments as needed for format. * * This version ignores the current locale and uses the locale "C" for Linux, * FreeBSD, OSX and Android. * * @param buf Pointer to a buffer where the resulting C string is stored. * @param format C string that contains a format string (see printf). * @param ... A sequence of additional arguments, each containing a value to be * used to replace a format specifier in the format string. * * @return On success, the number of characters that would have been written, * not counting the terminating NUL character. * * @since 0.6.0 */ SR_API int sr_sprintf_ascii(char *buf, const char *format, ...) { int ret; va_list args; va_start(args, format); ret = sr_vsprintf_ascii(buf, format, args); va_end(args); return ret; } /** * Compose a string with a format string in the buffer pointed to by buf. * * It is up to the caller to ensure that the allocated buffer is large enough * to hold the formatted result. * * Internally, the function retrieves arguments from the list identified by * args as if va_arg was used on it, and thus the state of args is likely to * be altered by the call. * * In any case, args should have been initialized by va_start at some point * before the call, and it is expected to be released by va_end at some point * after the call. * * This version ignores the current locale and uses the locale "C" for Linux, * FreeBSD, OSX and Android. * * @param buf Pointer to a buffer where the resulting C string is stored. * @param format C string that contains a format string (see printf). * @param args A value identifying a variable arguments list initialized with * va_start. * * @return On success, the number of characters that would have been written, * not counting the terminating NUL character. * * @since 0.6.0 */ SR_API int sr_vsprintf_ascii(char *buf, const char *format, va_list args) { #if defined(_WIN32) int ret; #if 0 /* * TODO: This part compiles with mingw-w64 but doesn't run with Win7. * Doesn't start because of "Procedure entry point _create_locale * not found in msvcrt.dll". * mingw-w64 should link to msvcr100.dll not msvcrt.dll! * See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx */ _locale_t locale; locale = _create_locale(LC_NUMERIC, "C"); ret = _vsprintf_l(buf, format, locale, args); _free_locale(locale); #endif /* vsprintf() uses the current locale, may not work correctly for floats. */ ret = vsprintf(buf, format, args); return ret; #elif defined(__APPLE__) /* * See: * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html */ int ret; locale_t locale; locale = newlocale(LC_NUMERIC_MASK, "C", NULL); ret = vsprintf_l(buf, locale, format, args); freelocale(locale); return ret; #elif defined(__FreeBSD__) && __FreeBSD_version >= 901000 /* * See: * https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE * https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE */ int ret; locale_t locale; locale = newlocale(LC_NUMERIC_MASK, "C", NULL); ret = vsprintf_l(buf, locale, format, args); freelocale(locale); return ret; #elif defined(__ANDROID__) /* * The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8" * aka "en_US.UTF-8"). The decimal point is hard coded as "." * See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp */ int ret; ret = vsprintf(buf, format, args); return ret; #elif defined(__linux__) int ret; locale_t old_locale, temp_locale; /* Switch to C locale for proper float/double conversion. */ temp_locale = newlocale(LC_NUMERIC, "C", NULL); old_locale = uselocale(temp_locale); ret = vsprintf(buf, format, args); /* Switch back to original locale. */ uselocale(old_locale); freelocale(temp_locale); return ret; #elif defined(__unix__) || defined(__unix) /* * This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by * using the current locale for snprintf(). This may not work correctly * for floats! */ int ret; ret = vsprintf(buf, format, args); return ret; #else /* No implementation for unknown systems! */ return -1; #endif } /** * Composes a string with a format string (like printf) in the buffer pointed * by buf (taking buf_size as the maximum buffer capacity to fill). * If the resulting string would be longer than n - 1 characters, the remaining * characters are discarded and not stored, but counted for the value returned * by the function. * A terminating NUL character is automatically appended after the content * written. * After the format parameter, the function expects at least as many additional * arguments as needed for format. * * This version ignores the current locale and uses the locale "C" for Linux, * FreeBSD, OSX and Android. * * @param buf Pointer to a buffer where the resulting C string is stored. * @param buf_size Maximum number of bytes to be used in the buffer. The * generated string has a length of at most buf_size - 1, leaving space * for the additional terminating NUL character. * @param format C string that contains a format string (see printf). * @param ... A sequence of additional arguments, each containing a value to be * used to replace a format specifier in the format string. * * @return On success, the number of characters that would have been written if * buf_size had been sufficiently large, not counting the terminating * NUL character. On failure, a negative number is returned. * Notice that only when this returned value is non-negative and less * than buf_size, the string has been completely written. * * @since 0.6.0 */ SR_API int sr_snprintf_ascii(char *buf, size_t buf_size, const char *format, ...) { int ret; va_list args; va_start(args, format); ret = sr_vsnprintf_ascii(buf, buf_size, format, args); va_end(args); return ret; } /** * Composes a string with a format string (like printf) in the buffer pointed * by buf (taking buf_size as the maximum buffer capacity to fill). * If the resulting string would be longer than n - 1 characters, the remaining * characters are discarded and not stored, but counted for the value returned * by the function. * A terminating NUL character is automatically appended after the content * written. * Internally, the function retrieves arguments from the list identified by * args as if va_arg was used on it, and thus the state of args is likely to * be altered by the call. * In any case, arg should have been initialized by va_start at some point * before the call, and it is expected to be released by va_end at some point * after the call. * * This version ignores the current locale and uses the locale "C" for Linux, * FreeBSD, OSX and Android. * * @param buf Pointer to a buffer where the resulting C string is stored. * @param buf_size Maximum number of bytes to be used in the buffer. The * generated string has a length of at most buf_size - 1, leaving space * for the additional terminating NUL character. * @param format C string that contains a format string (see printf). * @param args A value identifying a variable arguments list initialized with * va_start. * * @return On success, the number of characters that would have been written if * buf_size had been sufficiently large, not counting the terminating * NUL character. On failure, a negative number is returned. * Notice that only when this returned value is non-negative and less * than buf_size, the string has been completely written. * * @since 0.6.0 */ SR_API int sr_vsnprintf_ascii(char *buf, size_t buf_size, const char *format, va_list args) { #if defined(_WIN32) int ret; #if 0 /* * TODO: This part compiles with mingw-w64 but doesn't run with Win7. * Doesn't start because of "Procedure entry point _create_locale * not found in msvcrt.dll". * mingw-w64 should link to msvcr100.dll not msvcrt.dll!. * See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx */ _locale_t locale; locale = _create_locale(LC_NUMERIC, "C"); ret = _vsnprintf_l(buf, buf_size, format, locale, args); _free_locale(locale); #endif /* vsprintf uses the current locale, may cause issues for floats. */ ret = vsnprintf(buf, buf_size, format, args); return ret; #elif defined(__APPLE__) /* * See: * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html */ int ret; locale_t locale; locale = newlocale(LC_NUMERIC_MASK, "C", NULL); ret = vsnprintf_l(buf, buf_size, locale, format, args); freelocale(locale); return ret; #elif defined(__FreeBSD__) && __FreeBSD_version >= 901000 /* * See: * https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE * https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE */ int ret; locale_t locale; locale = newlocale(LC_NUMERIC_MASK, "C", NULL); ret = vsnprintf_l(buf, buf_size, locale, format, args); freelocale(locale); return ret; #elif defined(__ANDROID__) /* * The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8" * aka "en_US.UTF-8"). The decimal point is hard coded as ".". * See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp */ int ret; ret = vsnprintf(buf, buf_size, format, args); return ret; #elif defined(__linux__) int ret; locale_t old_locale, temp_locale; /* Switch to C locale for proper float/double conversion. */ temp_locale = newlocale(LC_NUMERIC, "C", NULL); old_locale = uselocale(temp_locale); ret = vsnprintf(buf, buf_size, format, args); /* Switch back to original locale. */ uselocale(old_locale); freelocale(temp_locale); return ret; #elif defined(__unix__) || defined(__unix) /* * This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by * using the current locale for snprintf(). This may not work correctly * for floats! */ int ret; ret = vsnprintf(buf, buf_size, format, args); return ret; #else /* No implementation for unknown systems! */ return -1; #endif } /** * Convert a sequence of bytes to its textual representation ("hex dump"). * * Callers should free the allocated GString. See sr_hexdump_free(). * * @param[in] data Pointer to the byte sequence to print. * @param[in] len Number of bytes to print. * * @return NULL upon error, newly allocated GString pointer otherwise. * * @private */ SR_PRIV GString *sr_hexdump_new(const uint8_t *data, const size_t len) { GString *s; size_t i; s = g_string_sized_new(3 * len); for (i = 0; i < len; i++) { if (i) g_string_append_c(s, ' '); g_string_append_printf(s, "%02x", data[i]); } return s; } /** * Free a hex dump text that was created by sr_hexdump_new(). * * @param[in] s Pointer to the GString to release. * * @private */ SR_PRIV void sr_hexdump_free(GString *s) { if (s) g_string_free(s, TRUE); } /** * Convert a string representation of a numeric value to a sr_rational. * * The conversion is strict and will fail if the complete string does not * represent a valid number. The function sets errno according to the details * of the failure. This version ignores the locale. * * @param str The string representation to convert. * @param ret Pointer to sr_rational where the result of the conversion will be stored. * * @retval SR_OK Conversion successful. * @retval SR_ERR Failure. * * @since 0.5.0 */ SR_API int sr_parse_rational(const char *str, struct sr_rational *ret) { char *endptr = NULL; int64_t integral; int64_t fractional = 0; int64_t denominator = 1; int32_t fractional_len = 0; int32_t exponent = 0; gboolean is_negative = FALSE; gboolean no_integer, no_fractional; while (isspace(*str)) str++; errno = 0; integral = g_ascii_strtoll(str, &endptr, 10); if (str == endptr && (str[0] == '-' || str[0] == '+') && str[1] == '.') { endptr += 1; no_integer = TRUE; } else if (str == endptr && str[0] == '.') { no_integer = TRUE; } else if (errno) { return SR_ERR; } else { no_integer = FALSE; } if (integral < 0 || str[0] == '-') is_negative = TRUE; errno = 0; if (*endptr == '.') { gboolean is_exp, is_eos; const char *start = endptr + 1; fractional = g_ascii_strtoll(start, &endptr, 10); is_exp = *endptr == 'E' || *endptr == 'e'; is_eos = *endptr == '\0'; if (endptr == start && (is_exp || is_eos)) { fractional = 0; errno = 0; } if (errno) return SR_ERR; no_fractional = endptr == start; if (no_integer && no_fractional) return SR_ERR; fractional_len = endptr - start; } errno = 0; if ((*endptr == 'E') || (*endptr == 'e')) { exponent = g_ascii_strtoll(endptr + 1, &endptr, 10); if (errno) return SR_ERR; } if (*endptr != '\0') return SR_ERR; for (int i = 0; i < fractional_len; i++) integral *= 10; exponent -= fractional_len; if (!is_negative) integral += fractional; else integral -= fractional; while (exponent > 0) { integral *= 10; exponent--; } while (exponent < 0) { denominator *= 10; exponent++; } ret->p = integral; ret->q = denominator; return SR_OK; } /** * Convert a numeric value value to its "natural" string representation * in SI units. * * E.g. a value of 3000000, with units set to "W", would be converted * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW". * * @param x The value to convert. * @param unit The unit to append to the string, or NULL if the string * has no units. * * @return A newly allocated string representation of the samplerate value, * or NULL upon errors. The caller is responsible to g_free() the * memory. * * @since 0.2.0 */ SR_API char *sr_si_string_u64(uint64_t x, const char *unit) { uint8_t i; uint64_t quot, divisor[] = { SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1), SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000), }; const char *p, prefix[] = "\0kMGTPE"; char fmt[16], fract[20] = "", *f; if (!unit) unit = ""; for (i = 0; (quot = x / divisor[i]) >= 1000; i++); if (i) { sprintf(fmt, ".%%0%d"PRIu64, i * 3); f = fract + sprintf(fract, fmt, x % divisor[i]) - 1; while (f >= fract && strchr("0.", *f)) *f-- = 0; } p = prefix + i; return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit); } /** * Convert a numeric samplerate value to its "natural" string representation. * * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz", * 31500 would become "31.5 kHz". * * @param samplerate The samplerate in Hz. * * @return A newly allocated string representation of the samplerate value, * or NULL upon errors. The caller is responsible to g_free() the * memory. * * @since 0.1.0 */ SR_API char *sr_samplerate_string(uint64_t samplerate) { return sr_si_string_u64(samplerate, "Hz"); } /** * Convert a numeric period value to the "natural" string representation * of its period value. * * The period is specified as a rational number's numerator and denominator. * * E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms". * * @param v_p The period numerator. * @param v_q The period denominator. * * @return A newly allocated string representation of the period value, * or NULL upon errors. The caller is responsible to g_free() the * memory. * * @since 0.5.0 */ SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q) { double freq, v; int prec; freq = 1 / ((double)v_p / v_q); if (freq > SR_GHZ(1)) { v = (double)v_p / v_q * 1000000000000.0; prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3; return g_strdup_printf("%.*f ps", prec, v); } else if (freq > SR_MHZ(1)) { v = (double)v_p / v_q * 1000000000.0; prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3; return g_strdup_printf("%.*f ns", prec, v); } else if (freq > SR_KHZ(1)) { v = (double)v_p / v_q * 1000000.0; prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3; return g_strdup_printf("%.*f us", prec, v); } else if (freq > 1) { v = (double)v_p / v_q * 1000.0; prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3; return g_strdup_printf("%.*f ms", prec, v); } else { v = (double)v_p / v_q; prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3; return g_strdup_printf("%.*f s", prec, v); } } /** * Convert a numeric voltage value to the "natural" string representation * of its voltage value. The voltage is specified as a rational number's * numerator and denominator. * * E.g. a value of 300000 would be converted to "300mV", 2 to "2V". * * @param v_p The voltage numerator. * @param v_q The voltage denominator. * * @return A newly allocated string representation of the voltage value, * or NULL upon errors. The caller is responsible to g_free() the * memory. * * @since 0.2.0 */ SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q) { if (v_q == 1000) return g_strdup_printf("%" PRIu64 " mV", v_p); else if (v_q == 1) return g_strdup_printf("%" PRIu64 " V", v_p); else return g_strdup_printf("%g V", (float)v_p / (float)v_q); } /** * Convert a "natural" string representation of a size value to uint64_t. * * E.g. a value of "3k" or "3 K" would be converted to 3000, a value * of "15M" would be converted to 15000000. * * Value representations other than decimal (such as hex or octal) are not * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported. * Spaces (but not other whitespace) between value and suffix are allowed. * * @param sizestring A string containing a (decimal) size value. * @param size Pointer to uint64_t which will contain the string's size value. * * @return SR_OK upon success, SR_ERR upon errors. * * @since 0.1.0 */ SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size) { uint64_t multiplier; int done; double frac_part; char *s; *size = strtoull(sizestring, &s, 10); multiplier = 0; frac_part = 0; done = FALSE; while (s && *s && multiplier == 0 && !done) { switch (*s) { case ' ': break; case '.': frac_part = g_ascii_strtod(s, &s); break; case 'k': case 'K': multiplier = SR_KHZ(1); break; case 'm': case 'M': multiplier = SR_MHZ(1); break; case 'g': case 'G': multiplier = SR_GHZ(1); break; case 't': case 'T': multiplier = SR_GHZ(1000); break; case 'p': case 'P': multiplier = SR_GHZ(1000 * 1000); break; case 'e': case 'E': multiplier = SR_GHZ(1000 * 1000 * 1000); break; default: done = TRUE; s--; } s++; } if (multiplier > 0) { *size *= multiplier; *size += frac_part * multiplier; } else { *size += frac_part; } if (s && *s && g_ascii_strcasecmp(s, "Hz")) return SR_ERR; return SR_OK; } /** * Convert a "natural" string representation of a time value to an * uint64_t value in milliseconds. * * E.g. a value of "3s" or "3 s" would be converted to 3000, a value * of "15ms" would be converted to 15. * * Value representations other than decimal (such as hex or octal) are not * supported. Only lower-case "s" and "ms" time suffixes are supported. * Spaces (but not other whitespace) between value and suffix are allowed. * * @param timestring A string containing a (decimal) time value. * @return The string's time value as uint64_t, in milliseconds. * * @todo Add support for "m" (minutes) and others. * @todo Add support for picoseconds? * @todo Allow both lower-case and upper-case? If no, document it. * * @since 0.1.0 */ SR_API uint64_t sr_parse_timestring(const char *timestring) { uint64_t time_msec; char *s; /* TODO: Error handling, logging. */ time_msec = strtoull(timestring, &s, 10); if (time_msec == 0 && s == timestring) return 0; if (s && *s) { while (*s == ' ') s++; if (!strcmp(s, "s")) time_msec *= 1000; else if (!strcmp(s, "ms")) ; /* redundant */ else return 0; } return time_msec; } /** @since 0.1.0 */ SR_API gboolean sr_parse_boolstring(const char *boolstr) { /* * Complete absence of an input spec is assumed to mean TRUE, * as in command line option strings like this: * ...:samplerate=100k:header:numchannels=4:... */ if (!boolstr || !*boolstr) return TRUE; if (!g_ascii_strncasecmp(boolstr, "true", 4) || !g_ascii_strncasecmp(boolstr, "yes", 3) || !g_ascii_strncasecmp(boolstr, "on", 2) || !g_ascii_strncasecmp(boolstr, "1", 1)) return TRUE; return FALSE; } /** @since 0.2.0 */ SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q) { char *s; *p = strtoull(periodstr, &s, 10); if (*p == 0 && s == periodstr) /* No digits found. */ return SR_ERR_ARG; if (s && *s) { while (*s == ' ') s++; if (!strcmp(s, "fs")) *q = UINT64_C(1000000000000000); else if (!strcmp(s, "ps")) *q = UINT64_C(1000000000000); else if (!strcmp(s, "ns")) *q = UINT64_C(1000000000); else if (!strcmp(s, "us")) *q = 1000000; else if (!strcmp(s, "ms")) *q = 1000; else if (!strcmp(s, "s")) *q = 1; else /* Must have a time suffix. */ return SR_ERR_ARG; } return SR_OK; } /** @since 0.2.0 */ SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q) { char *s; *p = strtoull(voltstr, &s, 10); if (*p == 0 && s == voltstr) /* No digits found. */ return SR_ERR_ARG; if (s && *s) { while (*s == ' ') s++; if (!g_ascii_strcasecmp(s, "mv")) *q = 1000L; else if (!g_ascii_strcasecmp(s, "v")) *q = 1; else /* Must have a base suffix. */ return SR_ERR_ARG; } return SR_OK; } /** @} */
Java
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* control code for tailsitters. Enabled by setting Q_FRAME_CLASS=10 */ #include "Plane.h" /* return true when flying a tailsitter */ bool QuadPlane::is_tailsitter(void) { return available() && frame_class == AP_Motors::MOTOR_FRAME_TAILSITTER; } /* check if we are flying as a tailsitter */ bool QuadPlane::tailsitter_active(void) { return is_tailsitter() && in_vtol_mode(); } /* run output for tailsitters */ void QuadPlane::tailsitter_output(void) { if (!is_tailsitter()) { return; } if (!tailsitter_active()) { if (tailsitter.vectored_forward_gain > 0) { // thrust vectoring in fixed wing flight float aileron = SRV_Channels::get_output_scaled(SRV_Channel::k_aileron); float elevator = SRV_Channels::get_output_scaled(SRV_Channel::k_elevator); float tilt_left = (elevator + aileron) * tailsitter.vectored_forward_gain; float tilt_right = (elevator - aileron) * tailsitter.vectored_forward_gain; SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, tilt_left); SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, tilt_right); } else { SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, 0); SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, 0); } return; } motors_output(); plane.pitchController.reset_I(); plane.rollController.reset_I(); if (tailsitter.vectored_hover_gain > 0) { // thrust vectoring VTOL modes float aileron = SRV_Channels::get_output_scaled(SRV_Channel::k_aileron); float elevator = SRV_Channels::get_output_scaled(SRV_Channel::k_elevator); float tilt_left = (elevator + aileron) * tailsitter.vectored_hover_gain; float tilt_right = (elevator - aileron) * tailsitter.vectored_hover_gain; SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, tilt_left); SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, tilt_right); } if (tailsitter.input_mask_chan > 0 && tailsitter.input_mask > 0 && hal.rcin->read(tailsitter.input_mask_chan-1) > 1700) { // the user is learning to prop-hang if (tailsitter.input_mask & TAILSITTER_MASK_AILERON) { SRV_Channels::set_output_scaled(SRV_Channel::k_aileron, plane.channel_roll->get_control_in_zero_dz()); } if (tailsitter.input_mask & TAILSITTER_MASK_ELEVATOR) { SRV_Channels::set_output_scaled(SRV_Channel::k_elevator, plane.channel_pitch->get_control_in_zero_dz()); } if (tailsitter.input_mask & TAILSITTER_MASK_THROTTLE) { SRV_Channels::set_output_scaled(SRV_Channel::k_throttle, plane.channel_throttle->get_control_in_zero_dz()); } if (tailsitter.input_mask & TAILSITTER_MASK_RUDDER) { SRV_Channels::set_output_scaled(SRV_Channel::k_rudder, plane.channel_rudder->get_control_in_zero_dz()); } } } /* return true when we have completed enough of a transition to switch to fixed wing control */ bool QuadPlane::tailsitter_transition_complete(void) { if (plane.fly_inverted()) { // transition immediately return true; } if (labs(ahrs_view->pitch_sensor) > tailsitter.transition_angle*100 || labs(ahrs_view->roll_sensor) > tailsitter.transition_angle*100 || AP_HAL::millis() - transition_start_ms > 2000) { return true; } // still waiting return false; } // handle different tailsitter input types void QuadPlane::tailsitter_check_input(void) { if (tailsitter_active() && tailsitter.input_type == TAILSITTER_INPUT_PLANE) { // the user has asked for body frame controls when tailsitter // is active. We switch around the control_in value for the // channels to do this, as that ensures the value is // consistent throughout the code int16_t roll_in = plane.channel_roll->get_control_in(); int16_t yaw_in = plane.channel_rudder->get_control_in(); plane.channel_roll->set_control_in(yaw_in); plane.channel_rudder->set_control_in(-roll_in); } }
Java
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email [email protected] or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #include "HeadSpin.h" #include "plComponent.h" #include "plComponentReg.h" #include "plMiscComponents.h" #include "MaxMain/plMaxNode.h" #include "resource.h" #include <iparamm2.h> #pragma hdrstop #include "MaxMain/plPlasmaRefMsgs.h" #include "pnSceneObject/plSceneObject.h" #include "pnSceneObject/plCoordinateInterface.h" #include "pnSceneObject/plDrawInterface.h" #include "plMessage/plSimStateMsg.h" #include "pnMessage/plEnableMsg.h" #include "MaxMain/plPluginResManager.h" void DummyCodeIncludeFuncIgnore() {} ///////////////////////////////////////////////////////////////////////////////////////////////// // // Ignore Component // // //Class that accesses the paramblock below. class plIgnoreComponent : public plComponent { public: plIgnoreComponent(); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg); bool Convert(plMaxNode *node, plErrorMsg *pErrMsg); virtual void CollectNonDrawables(INodeTab& nonDrawables); }; //Max desc stuff necessary below. CLASS_DESC(plIgnoreComponent, gIgnoreDesc, "Ignore", "Ignore", COMP_TYPE_IGNORE, Class_ID(0x48326288, 0x528a3dea)) enum { kIgnoreMeCheckBx }; ParamBlockDesc2 gIgnoreBk ( plComponent::kBlkComp, _T("Ignore"), 0, &gIgnoreDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_IGNORE, IDS_COMP_IGNORES, 0, 0, NULL, kIgnoreMeCheckBx, _T("Ignore"), TYPE_BOOL, 0, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORE_CKBX, end, end ); plIgnoreComponent::plIgnoreComponent() { fClassDesc = &gIgnoreDesc; fClassDesc->MakeAutoParamBlocks(this); } void plIgnoreComponent::CollectNonDrawables(INodeTab& nonDrawables) { if (fCompPB->GetInt(kIgnoreMeCheckBx)) { AddTargetsToList(nonDrawables); } } // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool plIgnoreComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { if (fCompPB->GetInt(kIgnoreMeCheckBx)) pNode->SetCanConvert(false); return true; } bool plIgnoreComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; } ///////////////////////////////////////////////////////////////////////////////////////////////// // // IgnoreLite Component // // //Class that accesses the paramblock below. class plIgnoreLiteComponent : public plComponent { public: enum { kSelectedOnly }; enum LightState { kTurnOn, kTurnOff, kToggle }; public: plIgnoreLiteComponent(); void SetState(LightState s); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; } bool PreConvert(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; } bool Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; } }; class plIgnoreLiteProc : public ParamMap2UserDlgProc { public: BOOL DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_COMMAND: if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_ON) ) { plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner(); ilc->SetState(plIgnoreLiteComponent::kTurnOn); return TRUE; } if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_OFF) ) { plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner(); ilc->SetState(plIgnoreLiteComponent::kTurnOff); return TRUE; } if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_TOGGLE) ) { plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner(); ilc->SetState(plIgnoreLiteComponent::kToggle); return TRUE; } break; } return false; } void DeleteThis() {} }; static plIgnoreLiteProc gIgnoreLiteProc; //Max desc stuff necessary below. CLASS_DESC(plIgnoreLiteComponent, gIgnoreLiteDesc, "Control Max Light", "ControlLite", COMP_TYPE_IGNORE, IGNORELITE_CID) ParamBlockDesc2 gIgnoreLiteBk ( plComponent::kBlkComp, _T("IgnoreLite"), 0, &gIgnoreLiteDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_IGNORELITE, IDS_COMP_IGNORELITES, 0, 0, &gIgnoreLiteProc, plIgnoreLiteComponent::kSelectedOnly, _T("SelectedOnly"), TYPE_BOOL, 0, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORELITE_SELECTED, end, end ); plIgnoreLiteComponent::plIgnoreLiteComponent() { fClassDesc = &gIgnoreLiteDesc; fClassDesc->MakeAutoParamBlocks(this); } void plIgnoreLiteComponent::SetState(LightState s) { BOOL selectedOnly = fCompPB->GetInt(kSelectedOnly); int numTarg = NumTargets(); int i; for( i = 0; i < numTarg; i++ ) { plMaxNodeBase* targ = GetTarget(i); if( targ ) { if( selectedOnly && !targ->Selected() ) continue; Object *obj = targ->EvalWorldState(TimeValue(0)).obj; if (obj && (obj->SuperClassID() == SClass_ID(LIGHT_CLASS_ID))) { LightObject* liObj = (LightObject*)obj; switch( s ) { case kTurnOn: liObj->SetUseLight(true); break; case kTurnOff: liObj->SetUseLight(false); break; case kToggle: liObj->SetUseLight(!liObj->GetUseLight()); break; } } } } } ///////////////////////////////////////////////////////////////////////////////////////////////// // // Barney Component // // //Class that accesses the paramblock below. class plBarneyComponent : public plComponent { public: plBarneyComponent(); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg); bool Convert(plMaxNode *node, plErrorMsg *pErrMsg); }; //Max desc stuff necessary below. CLASS_DESC(plBarneyComponent, gBarneyDesc, "Barney", "Barney", COMP_TYPE_IGNORE, Class_ID(0x376955dc, 0x2fec50ae)) ParamBlockDesc2 gBarneyBk ( plComponent::kBlkComp, _T("Barney"), 0, &gBarneyDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_BARNEY, IDS_COMP_BARNEYS, 0, 0, NULL, end ); plBarneyComponent::plBarneyComponent() { fClassDesc = &gBarneyDesc; fClassDesc->MakeAutoParamBlocks(this); } // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool plBarneyComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { pNode->SetCanConvert(false); pNode->SetIsBarney(true); return true; } bool plBarneyComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; } ///////////////////////////////////////////////////////////////////////////////////////////////// // // NoShow Component // // //Class that accesses the paramblock below. class plNoShowComponent : public plComponent { public: enum { kShowable, kAffectDraw, kAffectPhys }; public: plNoShowComponent(); virtual void CollectNonDrawables(INodeTab& nonDrawables); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg); bool Convert(plMaxNode *node, plErrorMsg *pErrMsg); }; const Class_ID COMP_NOSHOW_CID(0x41cb2b85, 0x615932c6); //Max desc stuff necessary below. CLASS_DESC(plNoShowComponent, gNoShowDesc, "NoShow", "NoShow", COMP_TYPE_IGNORE, COMP_NOSHOW_CID) ParamBlockDesc2 gNoShowBk ( plComponent::kBlkComp, _T("NoShow"), 0, &gNoShowDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_NOSHOW, IDS_COMP_NOSHOW, 0, 0, NULL, plNoShowComponent::kShowable, _T("Showable"), TYPE_BOOL, 0, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_SHOWABLE, end, plNoShowComponent::kAffectDraw, _T("AffectDraw"), TYPE_BOOL, 0, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTDRAW, end, plNoShowComponent::kAffectPhys, _T("AffectPhys"), TYPE_BOOL, 0, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTPHYS, end, end ); plNoShowComponent::plNoShowComponent() { fClassDesc = &gNoShowDesc; fClassDesc->MakeAutoParamBlocks(this); } // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool plNoShowComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { if( !fCompPB->GetInt(kShowable) ) { if( fCompPB->GetInt(kAffectDraw) ) pNode->SetDrawable(false); if( fCompPB->GetInt(kAffectPhys) ) pNode->SetPhysical(false); } return true; } bool plNoShowComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg) { plSceneObject* obj = node->GetSceneObject(); if( !obj ) return true; if( fCompPB->GetInt(kShowable) ) { if( fCompPB->GetInt(kAffectDraw) ) { plEnableMsg* eMsg = new plEnableMsg(nil, plEnableMsg::kDisable, plEnableMsg::kDrawable); eMsg->AddReceiver(obj->GetKey()); eMsg->Send(); } if( fCompPB->GetInt(kAffectPhys) ) { hsAssert(0, "Who uses this?"); // plEventGroupEnableMsg* pMsg = new plEventGroupEnableMsg; // pMsg->SetFlags(plEventGroupEnableMsg::kCollideOff | plEventGroupEnableMsg::kReportOff); // pMsg->AddReceiver(obj->GetKey()); // pMsg->Send(); } #if 0 plDrawInterface* di = node->GetDrawInterface(); if( di && { di->SetProperty(plDrawInterface::kDisable, true); } #endif } return true; } void plNoShowComponent::CollectNonDrawables(INodeTab& nonDrawables) { if( fCompPB->GetInt(kAffectDraw) ) AddTargetsToList(nonDrawables); }
Java
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "branchmodel.h" #include "gitclient.h" #include <utils/qtcassert.h> #include <vcsbase/vcsoutputwindow.h> #include <vcsbase/vcscommand.h> #include <QFont> using namespace VcsBase; namespace Git { namespace Internal { enum RootNodes { LocalBranches = 0, RemoteBranches = 1, Tags = 2 }; // -------------------------------------------------------------------------- // BranchNode: // -------------------------------------------------------------------------- class BranchNode { public: BranchNode() : parent(0), name(QLatin1String("<ROOT>")) { } BranchNode(const QString &n, const QString &s = QString(), const QString &t = QString()) : parent(0), name(n), sha(s), tracking(t) { } ~BranchNode() { while (!children.isEmpty()) delete children.first(); if (parent) parent->children.removeAll(this); } BranchNode *rootNode() const { return parent ? parent->rootNode() : const_cast<BranchNode *>(this); } int count() const { return children.count(); } bool isLeaf() const { return children.isEmpty() && parent && parent->parent; } bool childOf(BranchNode *node) const { if (this == node) return true; return parent ? parent->childOf(node) : false; } bool childOfRoot(RootNodes root) const { BranchNode *rn = rootNode(); if (rn->isLeaf()) return false; if (root >= rn->children.count()) return false; return childOf(rn->children.at(root)); } bool isTag() const { return childOfRoot(Tags); } bool isLocal() const { return childOfRoot(LocalBranches); } BranchNode *childOfName(const QString &name) const { for (int i = 0; i < children.count(); ++i) { if (children.at(i)->name == name) return children.at(i); } return 0; } QStringList fullName(bool includePrefix = false) const { QTC_ASSERT(isLeaf(), return QStringList()); QStringList fn; QList<const BranchNode *> nodes; const BranchNode *current = this; while (current->parent) { nodes.prepend(current); current = current->parent; } if (includePrefix) fn.append(nodes.first()->sha); nodes.removeFirst(); foreach (const BranchNode *n, nodes) fn.append(n->name); return fn; } void insert(const QStringList &path, BranchNode *n) { BranchNode *current = this; for (int i = 0; i < path.count(); ++i) { BranchNode *c = current->childOfName(path.at(i)); if (c) current = c; else current = current->append(new BranchNode(path.at(i))); } current->append(n); } BranchNode *append(BranchNode *n) { n->parent = this; children.append(n); return n; } QStringList childrenNames() const { if (children.count() > 0) { QStringList names; foreach (BranchNode *n, children) { names.append(n->childrenNames()); } return names; } return QStringList(fullName().join(QLatin1Char('/'))); } int rowOf(BranchNode *node) { return children.indexOf(node); } BranchNode *parent; QList<BranchNode *> children; QString name; QString sha; QString tracking; mutable QString toolTip; }; // -------------------------------------------------------------------------- // BranchModel: // -------------------------------------------------------------------------- BranchModel::BranchModel(GitClient *client, QObject *parent) : QAbstractItemModel(parent), m_client(client), m_rootNode(new BranchNode), m_currentBranch(0) { QTC_CHECK(m_client); // Abuse the sha field for ref prefix m_rootNode->append(new BranchNode(tr("Local Branches"), QLatin1String("refs/heads"))); m_rootNode->append(new BranchNode(tr("Remote Branches"), QLatin1String("refs/remotes"))); } BranchModel::~BranchModel() { delete m_rootNode; } QModelIndex BranchModel::index(int row, int column, const QModelIndex &parentIdx) const { if (column != 0) return QModelIndex(); BranchNode *parentNode = indexToNode(parentIdx); if (row >= parentNode->count()) return QModelIndex(); return nodeToIndex(parentNode->children.at(row)); } QModelIndex BranchModel::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); BranchNode *node = indexToNode(index); if (node->parent == m_rootNode) return QModelIndex(); return nodeToIndex(node->parent); } int BranchModel::rowCount(const QModelIndex &parentIdx) const { if (parentIdx.column() > 0) return 0; return indexToNode(parentIdx)->count(); } int BranchModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 1; } QVariant BranchModel::data(const QModelIndex &index, int role) const { BranchNode *node = indexToNode(index); if (!node) return QVariant(); switch (role) { case Qt::DisplayRole: { QString res = node->name; if (!node->tracking.isEmpty()) res += QLatin1String(" [") + node->tracking + QLatin1Char(']'); return res; } case Qt::EditRole: return node->name; case Qt::ToolTipRole: if (!node->isLeaf()) return QVariant(); if (node->toolTip.isEmpty()) node->toolTip = toolTip(node->sha); return node->toolTip; case Qt::FontRole: { QFont font; if (!node->isLeaf()) { font.setBold(true); } else if (node == m_currentBranch) { font.setBold(true); font.setUnderline(true); } return font; } default: return QVariant(); } } bool BranchModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::EditRole) return false; BranchNode *node = indexToNode(index); if (!node) return false; const QString newName = value.toString(); if (newName.isEmpty()) return false; if (node->name == newName) return true; QStringList oldFullName = node->fullName(); node->name = newName; QStringList newFullName = node->fullName(); QString output; QString errorMessage; if (!m_client->synchronousBranchCmd(m_workingDirectory, QStringList() << QLatin1String("-m") << oldFullName.last() << newFullName.last(), &output, &errorMessage)) { node->name = oldFullName.last(); VcsOutputWindow::appendError(errorMessage); return false; } emit dataChanged(index, index); return true; } Qt::ItemFlags BranchModel::flags(const QModelIndex &index) const { BranchNode *node = indexToNode(index); if (!node) return Qt::NoItemFlags; if (node->isLeaf() && node->isLocal()) return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled; else return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } void BranchModel::clear() { foreach (BranchNode *root, m_rootNode->children) while (root->count()) delete root->children.takeLast(); if (hasTags()) m_rootNode->children.takeLast(); m_currentBranch = 0; } bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage) { beginResetModel(); clear(); if (workingDirectory.isEmpty()) { endResetModel(); return false; } m_currentSha = m_client->synchronousTopRevision(workingDirectory); QStringList args; args << QLatin1String("--format=%(objectname)\t%(refname)\t%(upstream:short)\t%(*objectname)"); QString output; if (!m_client->synchronousForEachRefCmd(workingDirectory, args, &output, errorMessage)) VcsOutputWindow::appendError(*errorMessage); m_workingDirectory = workingDirectory; const QStringList lines = output.split(QLatin1Char('\n')); foreach (const QString &l, lines) parseOutputLine(l); if (m_currentBranch) { if (m_currentBranch->parent == m_rootNode->children.at(LocalBranches)) m_currentBranch = 0; setCurrentBranch(); } endResetModel(); return true; } void BranchModel::setCurrentBranch() { QString currentBranch = m_client->synchronousCurrentLocalBranch(m_workingDirectory); if (currentBranch.isEmpty()) return; BranchNode *local = m_rootNode->children.at(LocalBranches); int pos = 0; for (pos = 0; pos < local->count(); ++pos) { if (local->children.at(pos)->name == currentBranch) m_currentBranch = local->children[pos]; } } void BranchModel::renameBranch(const QString &oldName, const QString &newName) { QString errorMessage; QString output; if (!m_client->synchronousBranchCmd(m_workingDirectory, QStringList() << QLatin1String("-m") << oldName << newName, &output, &errorMessage)) VcsOutputWindow::appendError(errorMessage); else refresh(m_workingDirectory, &errorMessage); } void BranchModel::renameTag(const QString &oldName, const QString &newName) { QString errorMessage; QString output; if (!m_client->synchronousTagCmd(m_workingDirectory, QStringList() << newName << oldName, &output, &errorMessage) || !m_client->synchronousTagCmd(m_workingDirectory, QStringList() << QLatin1String("-d") << oldName, &output, &errorMessage)) { VcsOutputWindow::appendError(errorMessage); } else { refresh(m_workingDirectory, &errorMessage); } } QString BranchModel::workingDirectory() const { return m_workingDirectory; } GitClient *BranchModel::client() const { return m_client; } QModelIndex BranchModel::currentBranch() const { if (!m_currentBranch) return QModelIndex(); return nodeToIndex(m_currentBranch); } QString BranchModel::fullName(const QModelIndex &idx, bool includePrefix) const { if (!idx.isValid()) return QString(); BranchNode *node = indexToNode(idx); if (!node || !node->isLeaf()) return QString(); QStringList path = node->fullName(includePrefix); return path.join(QLatin1Char('/')); } QStringList BranchModel::localBranchNames() const { if (!m_rootNode || !m_rootNode->count()) return QStringList(); return m_rootNode->children.at(LocalBranches)->childrenNames(); } QString BranchModel::sha(const QModelIndex &idx) const { if (!idx.isValid()) return QString(); BranchNode *node = indexToNode(idx); return node->sha; } bool BranchModel::hasTags() const { return m_rootNode->children.count() > Tags; } bool BranchModel::isLocal(const QModelIndex &idx) const { if (!idx.isValid()) return false; BranchNode *node = indexToNode(idx); return node->isLocal(); } bool BranchModel::isLeaf(const QModelIndex &idx) const { if (!idx.isValid()) return false; BranchNode *node = indexToNode(idx); return node->isLeaf(); } bool BranchModel::isTag(const QModelIndex &idx) const { if (!idx.isValid() || !hasTags()) return false; return indexToNode(idx)->isTag(); } void BranchModel::removeBranch(const QModelIndex &idx) { QString branch = fullName(idx); if (branch.isEmpty()) return; QString errorMessage; QString output; QStringList args; args << QLatin1String("-D") << branch; if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) { VcsOutputWindow::appendError(errorMessage); return; } removeNode(idx); } void BranchModel::removeTag(const QModelIndex &idx) { QString tag = fullName(idx); if (tag.isEmpty()) return; QString errorMessage; QString output; QStringList args; args << QLatin1String("-d") << tag; if (!m_client->synchronousTagCmd(m_workingDirectory, args, &output, &errorMessage)) { VcsOutputWindow::appendError(errorMessage); return; } removeNode(idx); } void BranchModel::checkoutBranch(const QModelIndex &idx) { QString branch = fullName(idx, !isLocal(idx)); if (branch.isEmpty()) return; // No StashGuard since this function for now is only used with clean working dir. // If it is ever used from another place, please add StashGuard here m_client->synchronousCheckout(m_workingDirectory, branch); } bool BranchModel::branchIsMerged(const QModelIndex &idx) { QString branch = fullName(idx); if (branch.isEmpty()) return false; QString errorMessage; QString output; QStringList args; args << QLatin1String("-a") << QLatin1String("--contains") << sha(idx); if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) VcsOutputWindow::appendError(errorMessage); QStringList lines = output.split(QLatin1Char('\n'), QString::SkipEmptyParts); foreach (const QString &l, lines) { QString currentBranch = l.mid(2); // remove first letters (those are either // " " or "* " depending on whether it is // the currently checked out branch or not) if (currentBranch != branch) return true; } return false; } static int positionForName(BranchNode *node, const QString &name) { int pos = 0; for (pos = 0; pos < node->count(); ++pos) { if (node->children.at(pos)->name >= name) break; } return pos; } QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModelIndex &startPoint) { if (!m_rootNode || !m_rootNode->count()) return QModelIndex(); const QString trackedBranch = fullName(startPoint); const QString fullTrackedBranch = fullName(startPoint, true); QString startSha; QString output; QString errorMessage; QStringList args; args << (track ? QLatin1String("--track") : QLatin1String("--no-track")); args << name; if (!fullTrackedBranch.isEmpty()) { args << fullTrackedBranch; startSha = sha(startPoint); } else { startSha = m_client->synchronousTopRevision(m_workingDirectory); } if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) { VcsOutputWindow::appendError(errorMessage); return QModelIndex(); } BranchNode *local = m_rootNode->children.at(LocalBranches); const int slash = name.indexOf(QLatin1Char('/')); const QString leafName = slash == -1 ? name : name.mid(slash + 1); bool added = false; if (slash != -1) { const QString nodeName = name.left(slash); int pos = positionForName(local, nodeName); BranchNode *child = (pos == local->count()) ? 0 : local->children.at(pos); if (!child || child->name != nodeName) { child = new BranchNode(nodeName); beginInsertRows(nodeToIndex(local), pos, pos); added = true; child->parent = local; local->children.insert(pos, child); } local = child; } int pos = positionForName(local, leafName); auto newNode = new BranchNode(leafName, startSha, track ? trackedBranch : QString()); if (!added) beginInsertRows(nodeToIndex(local), pos, pos); newNode->parent = local; local->children.insert(pos, newNode); endInsertRows(); return nodeToIndex(newNode); } void BranchModel::setRemoteTracking(const QModelIndex &trackingIndex) { QModelIndex current = currentBranch(); QTC_ASSERT(current.isValid(), return); const QString currentName = fullName(current); const QString shortTracking = fullName(trackingIndex); const QString tracking = fullName(trackingIndex, true); m_client->synchronousSetTrackingBranch(m_workingDirectory, currentName, tracking); m_currentBranch->tracking = shortTracking; emit dataChanged(current, current); } void BranchModel::parseOutputLine(const QString &line) { if (line.size() < 3) return; QStringList lineParts = line.split(QLatin1Char('\t')); const QString shaDeref = lineParts.at(3); const QString sha = shaDeref.isEmpty() ? lineParts.at(0) : shaDeref; const QString fullName = lineParts.at(1); bool current = (sha == m_currentSha); bool showTags = m_client->settings().boolValue(GitSettings::showTagsKey); // insert node into tree: QStringList nameParts = fullName.split(QLatin1Char('/')); nameParts.removeFirst(); // remove refs... BranchNode *root = 0; if (nameParts.first() == QLatin1String("heads")) { root = m_rootNode->children.at(LocalBranches); } else if (nameParts.first() == QLatin1String("remotes")) { root = m_rootNode->children.at(RemoteBranches); } else if (showTags && nameParts.first() == QLatin1String("tags")) { if (!hasTags()) // Tags is missing, add it m_rootNode->append(new BranchNode(tr("Tags"), QLatin1String("refs/tags"))); root = m_rootNode->children.at(Tags); } else { return; } nameParts.removeFirst(); // limit depth of list. Git basically only ever wants one / and considers the rest as part of // the name. while (nameParts.count() > 3) { nameParts[2] = nameParts.at(2) + QLatin1Char('/') + nameParts.at(3); nameParts.removeAt(3); } const QString name = nameParts.last(); nameParts.removeLast(); auto newNode = new BranchNode(name, sha, lineParts.at(2)); root->insert(nameParts, newNode); if (current) m_currentBranch = newNode; } BranchNode *BranchModel::indexToNode(const QModelIndex &index) const { if (index.column() > 0) return 0; if (!index.isValid()) return m_rootNode; return static_cast<BranchNode *>(index.internalPointer()); } QModelIndex BranchModel::nodeToIndex(BranchNode *node) const { if (node == m_rootNode) return QModelIndex(); return createIndex(node->parent->rowOf(node), 0, static_cast<void *>(node)); } void BranchModel::removeNode(const QModelIndex &idx) { QModelIndex nodeIndex = idx; // idx is a leaf, so count must be 0. BranchNode *node = indexToNode(nodeIndex); while (node->count() == 0 && node->parent != m_rootNode) { BranchNode *parentNode = node->parent; const QModelIndex parentIndex = nodeToIndex(parentNode); const int nodeRow = nodeIndex.row(); beginRemoveRows(parentIndex, nodeRow, nodeRow); parentNode->children.removeAt(nodeRow); delete node; endRemoveRows(); node = parentNode; nodeIndex = parentIndex; } } QString BranchModel::toolTip(const QString &sha) const { // Show the sha description excluding diff as toolTip QString output; QString errorMessage; QStringList arguments(QLatin1String("-n1")); arguments << sha; if (!m_client->synchronousLog(m_workingDirectory, arguments, &output, &errorMessage, VcsCommand::SuppressCommandLogging)) { return errorMessage; } return output; } } // namespace Internal } // namespace Git
Java
/* This file is part of the FreeRTOS.org distribution. FreeRTOS.org is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation and modified by the FreeRTOS exception. FreeRTOS.org is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FreeRTOS.org; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. A special exception to the GPL is included to allow you to distribute a combined work that includes FreeRTOS.org without being obliged to provide the source code for any proprietary components. See the licensing section of http://www.FreeRTOS.org for full details. *************************************************************************** * * * Get the FreeRTOS eBook! See http://www.FreeRTOS.org/Documentation * * * * This is a concise, step by step, 'hands on' guide that describes both * * general multitasking concepts and FreeRTOS specifics. It presents and * * explains numerous examples that are written using the FreeRTOS API. * * Full source code for all the examples is provided in an accompanying * * .zip file. * * * *************************************************************************** 1 tab == 4 spaces! Please ensure to read the configuration and relevant port sections of the online documentation. *************************************************************************** * * * Having a problem? Start by reading the FAQ "My application does * * not run, what could be wrong? * * * * http://www.FreeRTOS.org/FAQHelp.html * * * *************************************************************************** http://www.FreeRTOS.org - Documentation, training, latest information, license and contact details. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool. Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell the code with commercial support, indemnification, and middleware, under the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also provide a safety engineered and independently SIL3 certified version under the SafeRTOS brand: http://www.SafeRTOS.com. */ /* Kernel includes. */ #include "FreeRTOS.h" #include "semphr.h" #include "task.h" /* Demo includes. */ #include "FEC.h" #include "fecbd.h" #include "mii.h" #include "eth_phy.h" #include "eth.h" /* uIP includes. */ #include "uip.h" #include "uip_arp.h" /*-----------------------------------------------------------*/ /* FEC hardware specifics. */ #define MCF_FEC_MSCR_MII_SPEED(x) (((x)&0x3F)<<0x1) #define MCF_FEC_RDAR_R_DES_ACTIVE ( 0x1000000 ) #define MCF_FEC_TDAR_X_DES_ACTIVE ( 0x1000000 ) /* PHY hardware specifics. */ #define PHY_STATUS ( 16 ) #define PHY_DUPLEX_STATUS ( 4 ) /* Delay between polling the PHY to see if a link has been established. */ #define fecLINK_DELAY ( 500 / portTICK_PERIOD_MS ) /* Very short delay to use when waiting for the Tx to finish with a buffer if we run out of Rx buffers. */ #define fecMINIMAL_DELAY ( 3 / portTICK_PERIOD_MS ) /* Don't block to wait for a buffer more than this many times. */ #define uipBUFFER_WAIT_ATTEMPTS ( 30 ) /* The Tx re-uses the Rx buffers and only has one descriptor. */ #define fecNUM_TX_DESCRIPTORS ( 1 ) /* The total number of buffers available, which should be greater than the number of Rx descriptors. */ #define fecNUM_BUFFERS ( configNUM_FEC_RX_DESCRIPTORS + 2 ) /*-----------------------------------------------------------*/ /* * Return an unused buffer to the pool of free buffers. */ static void prvReturnBuffer( unsigned char *pucBuffer ); /* * Find and return the next buffer that is not in use by anything else. */ static unsigned char *prvGetFreeBuffer( void ); /*-----------------------------------------------------------*/ /* The semaphore used to wake the uIP task when data arrives. */ SemaphoreHandle_t xFECSemaphore = NULL; /* The buffer used by the uIP stack. In this case the pointer is used to point to one of the Rx buffers to avoid having to copy the Rx buffer into the uIP buffer. */ unsigned char *uip_buf; /* The DMA descriptors. These are char arrays to allow us to align them correctly. */ static unsigned char xFECTxDescriptors_unaligned[ ( fecNUM_TX_DESCRIPTORS * sizeof( FECBD ) ) + 16 ]; static unsigned char xFECRxDescriptors_unaligned[ ( configNUM_FEC_RX_DESCRIPTORS * sizeof( FECBD ) ) + 16 ]; static FECBD *pxFECTxDescriptor; static FECBD *xFECRxDescriptors; /* The DMA buffer. This is a char arrays to allow it to be aligned correctly. */ static unsigned char ucFECRxBuffers[ ( fecNUM_BUFFERS * configFEC_BUFFER_SIZE ) + 16 ]; /* Index to the next descriptor to be inspected for received data. */ static unsigned long ulNextRxDescriptor = 0; /* Contains the start address of each Rx buffer, after it has been correctly aligned. */ static unsigned char *pucAlignedBufferStartAddresses[ fecNUM_BUFFERS ] = { 0 }; /* Each ucBufferInUse index corresponds to a position in the same index in the pucAlignedBufferStartAddresses array. If the index contains a 1 then the buffer within pucAlignedBufferStartAddresses is in use, if it contains a 0 then the buffer is free. */ static unsigned char ucBufferInUse[ fecNUM_BUFFERS ] = { 0 }; /*-----------------------------------------------------------*/ /********************************************************************/ /* * Write a value to a PHY's MII register. * * Parameters: * ch FEC channel * phy_addr Address of the PHY. * reg_addr Address of the register in the PHY. * data Data to be written to the PHY register. * * Return Values: * 0 on failure * 1 on success. * * Please refer to your PHY manual for registers and their meanings. * mii_write() polls for the FEC's MII interrupt event and clears it. * If after a suitable amount of time the event isn't triggered, a * value of 0 is returned. */ static int fec_mii_write( int phy_addr, int reg_addr, int data ) { int timeout; unsigned long eimr; /* Clear the MII interrupt bit */ EIR = EIR_MII; /* Mask the MII interrupt */ eimr = EIMR; EIMR &= ~EIMR_MII; /* Write to the MII Management Frame Register to kick-off the MII write */ MMFR = ( unsigned long ) ( FEC_MMFR_ST_01 | FEC_MMFR_OP_WRITE | FEC_MMFR_PA(phy_addr) | FEC_MMFR_RA(reg_addr) | FEC_MMFR_TA_10 | FEC_MMFR_DATA( data ) ); /* Poll for the MII interrupt (interrupt should be masked) */ for (timeout = 0; timeout < FEC_MII_TIMEOUT; timeout++) { if( EIR & EIR_MII) { break; } } if( timeout == FEC_MII_TIMEOUT ) { return 0; } /* Clear the MII interrupt bit */ EIR = EIR_MII; /* Restore the EIMR */ EIMR = eimr; return 1; } /********************************************************************/ /* * Read a value from a PHY's MII register. * * Parameters: * ch FEC channel * phy_addr Address of the PHY. * reg_addr Address of the register in the PHY. * data Pointer to storage for the Data to be read * from the PHY register (passed by reference) * * Return Values: * 0 on failure * 1 on success. * * Please refer to your PHY manual for registers and their meanings. * mii_read() polls for the FEC's MII interrupt event and clears it. * If after a suitable amount of time the event isn't triggered, a * value of 0 is returned. */ static int fec_mii_read( int phy_addr, int reg_addr, unsigned short* data ) { int timeout; unsigned long eimr; /* Clear the MII interrupt bit */ EIR = 0xffffffff; /* Mask the MII interrupt */ eimr = EIMR; EIMR &= ~EIMR_MII; /* Write to the MII Management Frame Register to kick-off the MII read */ MMFR = ( unsigned long ) ( FEC_MMFR_ST_01 | FEC_MMFR_OP_READ | FEC_MMFR_PA(phy_addr) | FEC_MMFR_RA(reg_addr) | FEC_MMFR_TA_10 ); /* Poll for the MII interrupt (interrupt should be masked) */ for (timeout = 0; timeout < FEC_MII_TIMEOUT; timeout++) { if (EIR) { break; } } if(timeout == FEC_MII_TIMEOUT) { return 0; } /* Clear the MII interrupt bit */ EIR = EIR_MII; /* Restore the EIMR */ EIMR = eimr; *data = (unsigned short)(MMFR & 0x0000FFFF); return 1; } /********************************************************************/ /* * Generate the hash table settings for the given address * * Parameters: * addr 48-bit (6 byte) Address to generate the hash for * * Return Value: * The 6 most significant bits of the 32-bit CRC result */ static unsigned char fec_hash_address( const unsigned char* addr ) { unsigned long crc; unsigned char byte; int i, j; crc = 0xFFFFFFFF; for(i=0; i<6; ++i) { byte = addr[i]; for(j=0; j<8; ++j) { if((byte & 0x01)^(crc & 0x01)) { crc >>= 1; crc = crc ^ 0xEDB88320; } else { crc >>= 1; } byte >>= 1; } } return (unsigned char)(crc >> 26); } /********************************************************************/ /* * Set the Physical (Hardware) Address and the Individual Address * Hash in the selected FEC * * Parameters: * ch FEC channel * pa Physical (Hardware) Address for the selected FEC */ static void fec_set_address( const unsigned char *pa ) { unsigned char crc; /* * Set the Physical Address */ PALR = (unsigned long)((pa[0]<<24) | (pa[1]<<16) | (pa[2]<<8) | pa[3]); PAUR = (unsigned long)((pa[4]<<24) | (pa[5]<<16)); /* * Calculate and set the hash for given Physical Address * in the Individual Address Hash registers */ crc = fec_hash_address(pa); if(crc >= 32) { IAUR |= (unsigned long)(1 << (crc - 32)); } else { IALR |= (unsigned long)(1 << crc); } } /*-----------------------------------------------------------*/ static void prvInitialiseFECBuffers( void ) { unsigned portBASE_TYPE ux; unsigned char *pcBufPointer; /* Set the pointer to a correctly aligned address. */ pcBufPointer = &( xFECTxDescriptors_unaligned[ 0 ] ); while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 ) { pcBufPointer++; } pxFECTxDescriptor = ( FECBD * ) pcBufPointer; /* Likewise the pointer to the Rx descriptor. */ pcBufPointer = &( xFECRxDescriptors_unaligned[ 0 ] ); while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 ) { pcBufPointer++; } xFECRxDescriptors = ( FECBD * ) pcBufPointer; /* There is no Tx buffer as the Rx buffer is reused. */ pxFECTxDescriptor->length = 0; pxFECTxDescriptor->status = 0; /* Align the Rx buffers. */ pcBufPointer = &( ucFECRxBuffers[ 0 ] ); while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 ) { pcBufPointer++; } /* Then fill in the Rx descriptors. */ for( ux = 0; ux < configNUM_FEC_RX_DESCRIPTORS; ux++ ) { xFECRxDescriptors[ ux ].status = RX_BD_E; xFECRxDescriptors[ ux ].length = configFEC_BUFFER_SIZE; xFECRxDescriptors[ ux ].data = pcBufPointer; /* Note the start address of the buffer now that it is correctly aligned. */ pucAlignedBufferStartAddresses[ ux ] = pcBufPointer; /* The buffer is in use by the descriptor. */ ucBufferInUse[ ux ] = pdTRUE; pcBufPointer += configFEC_BUFFER_SIZE; } /* Note the start address of the last buffer as one more buffer is allocated than there are Rx descriptors. */ pucAlignedBufferStartAddresses[ ux ] = pcBufPointer; /* Set uip_buf to point to the last buffer. */ uip_buf = pcBufPointer; ucBufferInUse[ ux ] = pdTRUE; /* Set the wrap bit in the last descriptors to form a ring. */ xFECRxDescriptors[ configNUM_FEC_RX_DESCRIPTORS - 1 ].status |= RX_BD_W; /* We start with descriptor 0. */ ulNextRxDescriptor = 0; } /*-----------------------------------------------------------*/ void vInitFEC( void ) { unsigned short usData; struct uip_eth_addr xAddr; const unsigned char ucMACAddress[6] = { configMAC_0, configMAC_1,configMAC_2,configMAC_3,configMAC_4,configMAC_5 }; prvInitialiseFECBuffers(); /* Create the semaphore used to wake the uIP task when data arrives. */ vSemaphoreCreateBinary( xFECSemaphore ); /* Set the MAC address within the stack. */ for( usData = 0; usData < 6; usData++ ) { xAddr.addr[ usData ] = ucMACAddress[ usData ]; } uip_setethaddr( xAddr ); /* Set the Reset bit and clear the Enable bit */ ECR_RESET = 1; /* Enable the clock. */ SCGC4 |= SCGC4_FEC_MASK; /* Wait at least 8 clock cycles */ for( usData = 0; usData < 10; usData++ ) { asm( "NOP" ); } /* Set MII speed to 2.5MHz. */ MSCR = MCF_FEC_MSCR_MII_SPEED( ( ( configCPU_CLOCK_HZ / 1000000 ) / 5 ) + 1 ); /* * Make sure the external interface signals are enabled */ PTCPF2_C0 = 1; PTCPF2_C1 = 1; PTCPF2_C2 = 1; PTAPF1 = 0x55; PTAPF2 = 0x55; PTBPF1 = 0x55; PTBPF2 = 0x55; /* Set all pins to full drive with no filter. */ PTADS = 0x06; PTAIFE = 0x06; PTBDS = 0xf4; PTBIFE = 0xf4; PTCDS = 0; PTCIFE = 0; /* Can we talk to the PHY? */ do { vTaskDelay( fecLINK_DELAY ); usData = 0xffff; fec_mii_read( configPHY_ADDRESS, PHY_PHYIDR1, &usData ); } while( usData == 0xffff ); /* Start auto negotiate. */ fec_mii_write( configPHY_ADDRESS, PHY_BMCR, ( PHY_BMCR_AN_RESTART | PHY_BMCR_AN_ENABLE ) ); /* Wait for auto negotiate to complete. */ do { vTaskDelay( fecLINK_DELAY ); fec_mii_read( configPHY_ADDRESS, PHY_BMSR, &usData ); } while( !( usData & PHY_BMSR_AN_COMPLETE ) ); /* When we get here we have a link - find out what has been negotiated. */ usData = 0; fec_mii_read( configPHY_ADDRESS, PHY_STATUS, &usData ); /* Setup half or full duplex. */ if( usData & PHY_DUPLEX_STATUS ) { RCR &= (unsigned long)~RCR_DRT; TCR |= TCR_FDEN; } else { RCR |= RCR_DRT; TCR &= (unsigned long)~TCR_FDEN; } /* Clear the Individual and Group Address Hash registers */ IALR = 0; IAUR = 0; GALR = 0; GAUR = 0; /* Set the Physical Address for the selected FEC */ fec_set_address( ucMACAddress ); /* Set Rx Buffer Size */ EMRBR = (unsigned short) configFEC_BUFFER_SIZE; /* Point to the start of the circular Rx buffer descriptor queue */ ERDSR = ( volatile unsigned long ) &( xFECRxDescriptors[ 0 ] ); /* Point to the start of the circular Tx buffer descriptor queue */ ETSDR = ( volatile unsigned long ) pxFECTxDescriptor; /* Clear all FEC interrupt events */ EIR = ( unsigned long ) -1; /* Various mode/status setup. */ RCR = 0; RCR_MAX_FL = configFEC_BUFFER_SIZE; RCR_MII_MODE = 1; #if( configUSE_PROMISCUOUS_MODE == 1 ) { RCR |= RCR_PROM; } #endif /* Enable interrupts. */ EIMR = EIR_TXF_MASK | EIMR_RXF_MASK | EIMR_RXB_MASK | EIMR_UN_MASK | EIMR_RL_MASK | EIMR_LC_MASK | EIMR_BABT_MASK | EIMR_BABR_MASK | EIMR_HBERR_MASK; /* Enable the MAC itself. */ ECR = ECR_ETHER_EN_MASK; /* Indicate that there have been empty receive buffers produced */ RDAR = MCF_FEC_RDAR_R_DES_ACTIVE; } /*-----------------------------------------------------------*/ unsigned long ulFECRx( void ) { unsigned long ulLen = 0UL; /* Is a buffer ready? */ if( ( xFECRxDescriptors[ ulNextRxDescriptor ].status & RX_BD_E ) == 0 ) { /* uip_buf is about to be set to a new buffer, so return the buffer it is already pointing to. */ prvReturnBuffer( uip_buf ); /* Obtain the size of the packet and put it into the "len" variable. */ ulLen = xFECRxDescriptors[ ulNextRxDescriptor ].length; uip_buf = xFECRxDescriptors[ ulNextRxDescriptor ].data; /* The buffer that this descriptor was using is now in use by the TCP/IP stack, so allocate it a new buffer. */ xFECRxDescriptors[ ulNextRxDescriptor ].data = prvGetFreeBuffer(); /* Doing this here could cause corruption! */ xFECRxDescriptors[ ulNextRxDescriptor ].status |= RX_BD_E; portENTER_CRITICAL(); { ulNextRxDescriptor++; if( ulNextRxDescriptor >= configNUM_FEC_RX_DESCRIPTORS ) { ulNextRxDescriptor = 0; } } portEXIT_CRITICAL(); /* Tell the DMA a new buffer is available. */ RDAR = MCF_FEC_RDAR_R_DES_ACTIVE; } return ulLen; } /*-----------------------------------------------------------*/ void vFECTx( void ) { /* When we get here the Tx descriptor should show as having completed. */ while( pxFECTxDescriptor->status & TX_BD_R ) { vTaskDelay( fecMINIMAL_DELAY ); } portENTER_CRITICAL(); { /* To maintain the zero copy implementation, point the Tx descriptor to the data from the Rx buffer. */ pxFECTxDescriptor->data = uip_buf; /* Setup the buffer descriptor for transmission */ pxFECTxDescriptor->length = uip_len; /* NB this assumes only one Tx descriptor! */ pxFECTxDescriptor->status = ( TX_BD_R | TX_BD_L | TX_BD_TC | TX_BD_W ); } portEXIT_CRITICAL(); /* Continue the Tx DMA task (in case it was waiting for a new TxBD) */ TDAR = MCF_FEC_TDAR_X_DES_ACTIVE; /* uip_buf is being used by the Tx descriptor. Allocate a new buffer to uip_buf. */ uip_buf = prvGetFreeBuffer(); } /*-----------------------------------------------------------*/ static void prvReturnBuffer( unsigned char *pucBuffer ) { unsigned long ul; /* Mark a buffer as free for use. */ for( ul = 0; ul < fecNUM_BUFFERS; ul++ ) { if( pucAlignedBufferStartAddresses[ ul ] == pucBuffer ) { ucBufferInUse[ ul ] = pdFALSE; break; } } } /*-----------------------------------------------------------*/ static unsigned char *prvGetFreeBuffer( void ) { portBASE_TYPE x; unsigned char *pucReturn = NULL; unsigned long ulAttempts = 0; while( pucReturn == NULL ) { /* Look through the buffers to find one that is not in use by anything else. */ for( x = 0; x < fecNUM_BUFFERS; x++ ) { if( ucBufferInUse[ x ] == pdFALSE ) { ucBufferInUse[ x ] = pdTRUE; pucReturn = pucAlignedBufferStartAddresses[ x ]; break; } } /* Was a buffer found? */ if( pucReturn == NULL ) { ulAttempts++; if( ulAttempts >= uipBUFFER_WAIT_ATTEMPTS ) { break; } /* Wait then look again. */ vTaskDelay( fecMINIMAL_DELAY ); } } return pucReturn; } /*-----------------------------------------------------------*/ void interrupt 86 vFECISRHandler( void ) { unsigned long ulEvent; portBASE_TYPE xHighPriorityTaskWoken = pdFALSE; /* Determine the cause of the interrupt. */ ulEvent = EIR & EIMR; EIR = ulEvent; if( ulEvent & EIR_RXF_MASK ) { /* A packet has been received. Wake the handler task in case it is blocked. */ xSemaphoreGiveFromISR( xFECSemaphore, &xHighPriorityTaskWoken ); } if( ulEvent & EIR_TXF_MASK ) { /* The Tx has completed. Mark the buffer it was using as free again. */ prvReturnBuffer( pxFECTxDescriptor->data ); pxFECTxDescriptor->data = NULL; } if (ulEvent & ( EIR_UN_MASK | EIR_RL_MASK | EIR_LC_MASK | EIR_EBERR_MASK | EIR_BABT_MASK | EIR_BABR_MASK | EIR_HBERR_MASK ) ) { /* Sledge hammer error handling. */ prvInitialiseFECBuffers(); RDAR = MCF_FEC_RDAR_R_DES_ACTIVE; } portEND_SWITCHING_ISR( xHighPriorityTaskWoken ); }
Java
-- Account initialisation script for Oracle Trust Service tablespace -- <![CDATA[Usage: sqlplus / as sysdba @oracle-create-account.sql ]]> drop user trust cascade; create user trust identified by trust default tablespace TRUST_SERVICE temporary tablespace temp quota unlimited on TRUST_SERVICE ; grant connect to trust; grant create sequence to trust; grant create view to trust; grant alter session to trust; grant create table to trust; -- XA DataSource support GRANT SELECT ON sys.dba_pending_transactions TO trust; GRANT SELECT ON sys.pending_trans$ TO trust; GRANT SELECT ON sys.dba_2pc_pending TO trust; -- for Oracle 10g R2 with patch for bug 5945463 applied and higher: -- GRANT EXECUTE ON sys.dbms_xa TO trust; -- else GRANT EXECUTE ON sys.dbms_system TO trust;
Java
/**CFile**************************************************************** FileName [ioReadBaf.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Command processing package.] Synopsis [Procedures to read AIG in the binary format.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: ioReadBaf.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #include "ioAbc.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Reads the AIG in the binary format.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Io_ReadBaf( char * pFileName, int fCheck ) { ProgressBar * pProgress; FILE * pFile; Vec_Ptr_t * vNodes; Abc_Obj_t * pObj, * pNode0, * pNode1; Abc_Ntk_t * pNtkNew; int nInputs, nOutputs, nLatches, nAnds, nFileSize, Num, i; char * pContents, * pName, * pCur; unsigned * pBufferNode; int RetValue; // read the file into the buffer nFileSize = Extra_FileSize( pFileName ); pFile = fopen( pFileName, "rb" ); pContents = ABC_ALLOC( char, nFileSize ); RetValue = fread( pContents, nFileSize, 1, pFile ); fclose( pFile ); // skip the comments (comment lines begin with '#' and end with '\n') for ( pCur = pContents; *pCur == '#'; ) while ( *pCur++ != '\n' ); // read the name pName = pCur; while ( *pCur++ ); // read the number of inputs nInputs = atoi( pCur ); while ( *pCur++ ); // read the number of outputs nOutputs = atoi( pCur ); while ( *pCur++ ); // read the number of latches nLatches = atoi( pCur ); while ( *pCur++ ); // read the number of nodes nAnds = atoi( pCur ); while ( *pCur++ ); // allocate the empty AIG pNtkNew = Abc_NtkAlloc( ABC_NTK_STRASH, ABC_FUNC_AIG, 1 ); pNtkNew->pName = Extra_UtilStrsav( pName ); pNtkNew->pSpec = Extra_UtilStrsav( pFileName ); // prepare the array of nodes vNodes = Vec_PtrAlloc( 1 + nInputs + nLatches + nAnds ); Vec_PtrPush( vNodes, Abc_AigConst1(pNtkNew) ); // create the PIs for ( i = 0; i < nInputs; i++ ) { pObj = Abc_NtkCreatePi(pNtkNew); Abc_ObjAssignName( pObj, pCur, NULL ); while ( *pCur++ ); Vec_PtrPush( vNodes, pObj ); } // create the POs for ( i = 0; i < nOutputs; i++ ) { pObj = Abc_NtkCreatePo(pNtkNew); Abc_ObjAssignName( pObj, pCur, NULL ); while ( *pCur++ ); } // create the latches for ( i = 0; i < nLatches; i++ ) { pObj = Abc_NtkCreateLatch(pNtkNew); Abc_ObjAssignName( pObj, pCur, NULL ); while ( *pCur++ ); pNode0 = Abc_NtkCreateBi(pNtkNew); Abc_ObjAssignName( pNode0, pCur, NULL ); while ( *pCur++ ); pNode1 = Abc_NtkCreateBo(pNtkNew); Abc_ObjAssignName( pNode1, pCur, NULL ); while ( *pCur++ ); Vec_PtrPush( vNodes, pNode1 ); Abc_ObjAddFanin( pObj, pNode0 ); Abc_ObjAddFanin( pNode1, pObj ); } // get the pointer to the beginning of the node array pBufferNode = (unsigned *)(pContents + (nFileSize - (2 * nAnds + nOutputs + nLatches) * sizeof(int)) ); // make sure we are at the place where the nodes begin if ( pBufferNode != (unsigned *)pCur ) { ABC_FREE( pContents ); Vec_PtrFree( vNodes ); Abc_NtkDelete( pNtkNew ); printf( "Warning: Internal reader error.\n" ); return NULL; } // create the AND gates pProgress = Extra_ProgressBarStart( stdout, nAnds ); for ( i = 0; i < nAnds; i++ ) { Extra_ProgressBarUpdate( pProgress, i, NULL ); pNode0 = Abc_ObjNotCond( (Abc_Obj_t *)Vec_PtrEntry(vNodes, pBufferNode[2*i+0] >> 1), pBufferNode[2*i+0] & 1 ); pNode1 = Abc_ObjNotCond( (Abc_Obj_t *)Vec_PtrEntry(vNodes, pBufferNode[2*i+1] >> 1), pBufferNode[2*i+1] & 1 ); Vec_PtrPush( vNodes, Abc_AigAnd((Abc_Aig_t *)pNtkNew->pManFunc, pNode0, pNode1) ); } Extra_ProgressBarStop( pProgress ); // read the POs Abc_NtkForEachCo( pNtkNew, pObj, i ) { Num = pBufferNode[2*nAnds+i]; if ( Abc_ObjFanoutNum(pObj) > 0 && Abc_ObjIsLatch(Abc_ObjFanout0(pObj)) ) { Abc_ObjSetData( Abc_ObjFanout0(pObj), (void *)(ABC_PTRINT_T)(Num & 3) ); Num >>= 2; } pNode0 = Abc_ObjNotCond( (Abc_Obj_t *)Vec_PtrEntry(vNodes, Num >> 1), Num & 1 ); Abc_ObjAddFanin( pObj, pNode0 ); } ABC_FREE( pContents ); Vec_PtrFree( vNodes ); // remove the extra nodes // Abc_AigCleanup( (Abc_Aig_t *)pNtkNew->pManFunc ); // check the result if ( fCheck && !Abc_NtkCheckRead( pNtkNew ) ) { printf( "Io_ReadBaf: The network check has failed.\n" ); Abc_NtkDelete( pNtkNew ); return NULL; } return pNtkNew; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
Java
package com.github.bordertech.wcomponents.examples; import com.github.bordertech.wcomponents.RadioButtonGroup; import com.github.bordertech.wcomponents.Size; import com.github.bordertech.wcomponents.WLabel; import com.github.bordertech.wcomponents.WPanel; import com.github.bordertech.wcomponents.WRadioButton; import com.github.bordertech.wcomponents.layout.FlowLayout; import com.github.bordertech.wcomponents.layout.FlowLayout.Alignment; /** * {@link WRadioButton} example. * * @author Yiannis Paschalidis * @since 1.0.0 */ public class RadioButtonExample extends WPanel { /** * Creates a RadioButtonExample. */ public RadioButtonExample() { this.setLayout(new FlowLayout(Alignment.VERTICAL)); WPanel panel = new WPanel(); RadioButtonGroup group1 = new RadioButtonGroup(); panel.add(group1); WRadioButton rb1 = group1.addRadioButton(1); panel.add(new WLabel("Default", rb1)); panel.add(rb1); this.add(panel); panel = new WPanel(); RadioButtonGroup group2 = new RadioButtonGroup(); panel.add(group2); WRadioButton rb2 = group2.addRadioButton(1); rb2.setSelected(true); panel.add(new WLabel("Initially selected", rb2)); panel.add(rb2); this.add(panel); panel = new WPanel(); RadioButtonGroup group3 = new RadioButtonGroup(); panel.add(group3); WRadioButton rb3 = group3.addRadioButton(1); rb3.setDisabled(true); rb3.setToolTip("This is disabled."); panel.add(new WLabel("Disabled", rb3)); panel.add(rb3); this.add(panel); RadioButtonGroup group = new RadioButtonGroup(); WRadioButton rb4 = group.addRadioButton("A"); WRadioButton rb5 = group.addRadioButton("B"); WRadioButton rb6 = group.addRadioButton("C"); panel = new WPanel(); panel.setLayout(new FlowLayout(Alignment.LEFT, Size.MEDIUM)); add(new WLabel("Group")); panel.add(new WLabel("A", rb4)); panel.add(rb4); panel.add(new WLabel("B", rb5)); panel.add(rb5); panel.add(new WLabel("C", rb6)); panel.add(rb6); panel.add(group); this.add(panel); } }
Java
/* * Crafter Studio Web-content authoring solution * Copyright (C) 2007-2016 Crafter Software Corporation. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.studio.impl.v1.service.activity; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.*; import net.sf.json.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.craftercms.commons.validation.annotations.param.ValidateIntegerParam; import org.craftercms.commons.validation.annotations.param.ValidateParams; import org.craftercms.commons.validation.annotations.param.ValidateSecurePathParam; import org.craftercms.commons.validation.annotations.param.ValidateStringParam; import org.craftercms.studio.api.v1.constant.StudioConstants; import org.craftercms.studio.api.v1.constant.DmConstants; import org.craftercms.studio.api.v1.dal.AuditFeed; import org.craftercms.studio.api.v1.dal.AuditFeedMapper; import org.craftercms.studio.api.v1.exception.ServiceException; import org.craftercms.studio.api.v1.exception.SiteNotFoundException; import org.craftercms.studio.api.v1.log.Logger; import org.craftercms.studio.api.v1.log.LoggerFactory; import org.craftercms.studio.api.v1.service.AbstractRegistrableService; import org.craftercms.studio.api.v1.service.activity.ActivityService; import org.craftercms.studio.api.v1.service.content.ContentService; import org.craftercms.studio.api.v1.service.deployment.DeploymentService; import org.craftercms.studio.api.v1.service.objectstate.State; import org.craftercms.studio.api.v1.service.site.SiteService; import org.craftercms.studio.api.v1.to.ContentItemTO; import org.craftercms.studio.api.v1.util.DebugUtils; import org.craftercms.studio.api.v1.util.StudioConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.craftercms.studio.api.v1.service.security.SecurityService; import static org.craftercms.studio.api.v1.constant.StudioConstants.CONTENT_TYPE_PAGE; import static org.craftercms.studio.api.v1.util.StudioConfiguration.ACTIVITY_USERNAME_CASE_SENSITIVE; public class ActivityServiceImpl extends AbstractRegistrableService implements ActivityService { private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class); protected static final int MAX_LEN_USER_ID = 255; // needs to match schema: // feed_user_id, // post_user_id protected static final int MAX_LEN_SITE_ID = 255; // needs to match schema: // site_network protected static final int MAX_LEN_ACTIVITY_TYPE = 255; // needs to match // schema: // activity_type protected static final int MAX_LEN_ACTIVITY_DATA = 4000; // needs to match // schema: // activity_data protected static final int MAX_LEN_APP_TOOL_ID = 36; // needs to match // schema: app_tool /** activity post properties **/ protected static final String ACTIVITY_PROP_ACTIVITY_SUMMARY = "activitySummary"; protected static final String ACTIVITY_PROP_ID = "id"; protected static final String ACTIVITY_PROP_POST_DATE = "postDate"; protected static final String ACTIVITY_PROP_USER = "user"; protected static final String ACTIVITY_PROP_FEEDUSER = "feedUserId"; protected static final String ACTIVITY_PROP_CONTENTID = "contentId"; /** activity feed format **/ protected static final String ACTIVITY_FEED_FORMAT = "json"; @Autowired protected AuditFeedMapper auditFeedMapper; protected SiteService siteService; protected ContentService contentService; protected SecurityService securityService; protected StudioConfiguration studioConfiguration; protected DeploymentService deploymentService; @Override public void register() { getServicesManager().registerService(ActivityService.class, this); } @Override @ValidateParams public void postActivity(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateSecurePathParam(name = "contentId") String contentId, ActivityType activity, ActivitySource source, Map<String,String> extraInfo) { JSONObject activityPost = new JSONObject(); activityPost.put(ACTIVITY_PROP_USER, user); activityPost.put(ACTIVITY_PROP_ID, contentId); if (extraInfo != null) { activityPost.putAll(extraInfo); } String contentType = null; if (extraInfo != null) { contentType = extraInfo.get(DmConstants.KEY_CONTENT_TYPE); } postActivity(activity.toString(), source.toString(), site, null, activityPost.toString(),contentId,contentType, user); } private void postActivity(String activityType, String activitySource, String siteNetwork, String appTool, String activityData, String contentId, String contentType, String approver) { String currentUser = (StringUtils.isEmpty(approver)) ? securityService.getCurrentUser() : approver; try { // optional - default to empty string if (siteNetwork == null) { siteNetwork = ""; } else if (siteNetwork.length() > MAX_LEN_SITE_ID) { throw new ServiceException("Invalid site network - exceeds " + MAX_LEN_SITE_ID + " chars: " + siteNetwork); } // optional - default to empty string if (appTool == null) { appTool = ""; } else if (appTool.length() > MAX_LEN_APP_TOOL_ID) { throw new ServiceException("Invalid app tool - exceeds " + MAX_LEN_APP_TOOL_ID + " chars: " + appTool); } // required if (StringUtils.isEmpty(activityType)) { throw new ServiceException("Invalid activity type - activity type is empty"); } else if (activityType.length() > MAX_LEN_ACTIVITY_TYPE) { throw new ServiceException("Invalid activity type - exceeds " + MAX_LEN_ACTIVITY_TYPE + " chars: " + activityType); } // optional - default to empty string if (activityData == null) { activityData = ""; } else if (activityType.length() > MAX_LEN_ACTIVITY_DATA) { throw new ServiceException("Invalid activity data - exceeds " + MAX_LEN_ACTIVITY_DATA + " chars: " + activityData); } // required if (StringUtils.isEmpty(currentUser)) { throw new ServiceException("Invalid user - user is empty"); } else if (currentUser.length() > MAX_LEN_USER_ID) { throw new ServiceException("Invalid user - exceeds " + MAX_LEN_USER_ID + " chars: " + currentUser); } else { // user names are not case-sensitive currentUser = currentUser.toLowerCase(); } if (contentType == null) { contentType = CONTENT_TYPE_PAGE; } } catch (ServiceException e) { // log error and throw exception logger.error("Error in getting feeds", e); } try { ZonedDateTime postDate = ZonedDateTime.now(ZoneOffset.UTC); AuditFeed activityPost = new AuditFeed(); activityPost.setUserId(currentUser); activityPost.setSiteNetwork(siteNetwork); activityPost.setSummary(activityData); activityPost.setType(activityType); activityPost.setCreationDate(postDate); activityPost.setModifiedDate(postDate); activityPost.setSummaryFormat("json"); activityPost.setContentId(contentId); activityPost.setContentType(contentType); activityPost.setSource(activitySource); try { activityPost.setCreationDate(ZonedDateTime.now(ZoneOffset.UTC)); long postId = insertFeedEntry(activityPost); activityPost.setId(postId); logger.debug("Posted: " + activityPost); } catch (Exception e) { throw new ServiceException("Failed to post activity: " + e, e); } } catch (ServiceException e) { // log error, subsume exception (for post activity) logger.error("Error in posting feed", e); } } private long insertFeedEntry(AuditFeed activityFeed) { DebugUtils.addDebugStack(logger); logger.debug("Insert activity " + activityFeed.getContentId()); Long id = auditFeedMapper.insertActivityFeed(activityFeed); return (id != null ? id : -1); } @Override @ValidateParams public void renameContentId(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "oldUrl") String oldUrl, @ValidateSecurePathParam(name = "newUrl") String newUrl) { DebugUtils.addDebugStack(logger); logger.debug("Rename " + oldUrl + " to " + newUrl); Map<String, String> params = new HashMap<String, String>(); params.put("newPath", newUrl); params.put("site", site); params.put("oldPath", oldUrl); auditFeedMapper.renameContent(params); } @Override @ValidateParams public List<ContentItemTO> getActivities(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateIntegerParam(name = "num") int num, @ValidateStringParam(name = "sort") String sort, boolean ascending, boolean excludeLive, @ValidateStringParam(name = "filterType") String filterType) throws ServiceException { int startPos = 0; List<ContentItemTO> contentItems = new ArrayList<ContentItemTO>(); boolean hasMoreItems = true; while(contentItems.size() < num && hasMoreItems){ int remainingItems = num - contentItems.size(); hasMoreItems = getActivityFeeds(user, site, startPos, num , filterType, excludeLive,contentItems,remainingItems); startPos = startPos+num; } if(contentItems.size() > num){ return contentItems.subList(0, num); } return contentItems; } /** * * Returns all non-live items if hideLiveItems is true, else should return all feeds back * */ protected boolean getActivityFeeds(String user, String site,int startPos, int size, String filterType,boolean hideLiveItems,List<ContentItemTO> contentItems,int remainingItem){ List<String> activityFeedEntries = new ArrayList<String>(); if (!getUserNamesAreCaseSensitive()) { user = user.toLowerCase(); } List<AuditFeed> activityFeeds = null; activityFeeds = selectUserFeedEntries(user, ACTIVITY_FEED_FORMAT, site, startPos, size, filterType, hideLiveItems); for (AuditFeed activityFeed : activityFeeds) { activityFeedEntries.add(activityFeed.getJSONString()); } boolean hasMoreItems=true; //if number of items returned is less than size it means that table has no more records if(activityFeedEntries.size()<size){ hasMoreItems=false; } if (activityFeedEntries != null && activityFeedEntries.size() > 0) { for (int index = 0; index < activityFeedEntries.size() && remainingItem!=0; index++) { JSONObject feedObject = JSONObject.fromObject(activityFeedEntries.get(index)); String id = (feedObject.containsKey(ACTIVITY_PROP_CONTENTID)) ? feedObject.getString(ACTIVITY_PROP_CONTENTID) : ""; ContentItemTO item = createActivityItem(site, feedObject, id); item.published = true; item.setPublished(true); ZonedDateTime pubDate = deploymentService.getLastDeploymentDate(site, id); item.publishedDate = pubDate; item.setPublishedDate(pubDate); contentItems.add(item); remainingItem--; } } logger.debug("Total Item post live filter : " + contentItems.size() + " hasMoreItems : "+hasMoreItems); return hasMoreItems; } /** * create an activity from the given feed * * @param site * @param feedObject * @return activity */ protected ContentItemTO createActivityItem(String site, JSONObject feedObject, String id) { try { ContentItemTO item = contentService.getContentItem(site, id, 0); if(item == null || item.isDeleted()) { item = contentService.createDummyDmContentItemForDeletedNode(site, id); String modifier = (feedObject.containsKey(ACTIVITY_PROP_FEEDUSER)) ? feedObject.getString(ACTIVITY_PROP_FEEDUSER) : ""; if(modifier != null && !modifier.isEmpty()) { item.user = modifier; } String activitySummary = (feedObject.containsKey(ACTIVITY_PROP_ACTIVITY_SUMMARY)) ? feedObject.getString(ACTIVITY_PROP_ACTIVITY_SUMMARY) : ""; JSONObject summaryObject = JSONObject.fromObject(activitySummary); if (summaryObject.containsKey(DmConstants.KEY_CONTENT_TYPE)) { String contentType = (String)summaryObject.get(DmConstants.KEY_CONTENT_TYPE); item.contentType = contentType; } if(summaryObject.containsKey(StudioConstants.INTERNAL_NAME)) { String internalName = (String)summaryObject.get(StudioConstants.INTERNAL_NAME); item.internalName = internalName; } if(summaryObject.containsKey(StudioConstants.BROWSER_URI)) { String browserUri = (String)summaryObject.get(StudioConstants.BROWSER_URI); item.browserUri = browserUri; } item.setLockOwner(""); } String postDate = (feedObject.containsKey(ACTIVITY_PROP_POST_DATE)) ? feedObject.getString(ACTIVITY_PROP_POST_DATE) : ""; ZonedDateTime editedDate = ZonedDateTime.parse(postDate); if (editedDate != null) { item.eventDate = editedDate.withZoneSameInstant(ZoneOffset.UTC); } else { item.eventDate = editedDate; } return item; } catch (Exception e) { logger.error("Error fetching content item for [" + id + "]", e.getMessage()); return null; } } private List<AuditFeed> selectUserFeedEntries(String feedUserId, String format, String siteId, int startPos, int feedSize, String contentType, boolean hideLiveItems) { HashMap<String,Object> params = new HashMap<String,Object>(); params.put("userId",feedUserId); params.put("summaryFormat",format); params.put("siteNetwork",siteId); params.put("startPos", startPos); params.put("feedSize", feedSize); params.put("activities", Arrays.asList(ActivityType.CREATED, ActivityType.DELETED, ActivityType.UPDATED, ActivityType.MOVED)); if(StringUtils.isNotEmpty(contentType) && !contentType.toLowerCase().equals("all")){ params.put("contentType",contentType.toLowerCase()); } if (hideLiveItems) { List<String> statesValues = new ArrayList<String>(); for (State state : State.LIVE_STATES) { statesValues.add(state.name()); } params.put("states", statesValues); return auditFeedMapper.selectUserFeedEntriesHideLive(params); } else { return auditFeedMapper.selectUserFeedEntries(params); } } @Override @ValidateParams public AuditFeed getDeletedActivity(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "path") String path) { HashMap<String,String> params = new HashMap<String,String>(); params.put("contentId", path); params.put("siteNetwork", site); String activityType = ActivityType.DELETED.toString(); params.put("activityType", activityType); return auditFeedMapper.getDeletedActivity(params); } @Override @ValidateParams public void deleteActivitiesForSite(@ValidateStringParam(name = "site") String site) { Map<String, String> params = new HashMap<String, String>(); params.put("site", site); auditFeedMapper.deleteActivitiesForSite(params); } @Override @ValidateParams public List<AuditFeed> getAuditLogForSite(@ValidateStringParam(name = "site") String site, @ValidateIntegerParam(name = "start") int start, @ValidateIntegerParam(name = "number") int number, @ValidateStringParam(name = "user") String user, List<String> actions) throws SiteNotFoundException { if (!siteService.exists(site)) { throw new SiteNotFoundException(); } else { Map<String, Object> params = new HashMap<String, Object>(); params.put("site", site); params.put("start", start); params.put("number", number); if (StringUtils.isNotEmpty(user)) { params.put("user", user); } if (CollectionUtils.isNotEmpty(actions)) { params.put("actions", actions); } return auditFeedMapper.getAuditLogForSite(params); } } @Override @ValidateParams public long getAuditLogForSiteTotal(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, List<String> actions) throws SiteNotFoundException { if (!siteService.exists(site)) { throw new SiteNotFoundException(); } else { Map<String, Object> params = new HashMap<String, Object>(); params.put("site", site); if (StringUtils.isNotEmpty(user)) { params.put("user", user); } if (CollectionUtils.isNotEmpty(actions)) { params.put("actions", actions); } return auditFeedMapper.getAuditLogForSiteTotal(params); } } public boolean getUserNamesAreCaseSensitive() { boolean toReturn = Boolean.parseBoolean(studioConfiguration.getProperty(ACTIVITY_USERNAME_CASE_SENSITIVE)); return toReturn; } public SiteService getSiteService() { return siteService; } public void setSiteService(final SiteService siteService) { this.siteService = siteService; } public void setContentService(ContentService contentService) { this.contentService = contentService; } public SecurityService getSecurityService() {return securityService; } public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } public StudioConfiguration getStudioConfiguration() { return studioConfiguration; } public void setStudioConfiguration(StudioConfiguration studioConfiguration) { this.studioConfiguration = studioConfiguration; } public DeploymentService getDeploymentService() { return deploymentService; } public void setDeploymentService(DeploymentService deploymentService) { this.deploymentService = deploymentService; } }
Java
package org.thoughtcrime.securesms.testutil; import org.signal.core.util.logging.Log; public final class SystemOutLogger extends Log.Logger { @Override public void v(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('v', tag, message, t); } @Override public void d(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('d', tag, message, t); } @Override public void i(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('i', tag, message, t); } @Override public void w(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('w', tag, message, t); } @Override public void e(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('e', tag, message, t); } @Override public void flush() { } private void printlnFormatted(char level, String tag, String message, Throwable t) { System.out.println(format(level, tag, message, t)); } private String format(char level, String tag, String message, Throwable t) { if (t != null) { return String.format("%c[%s] %s %s:%s", level, tag, message, t.getClass().getSimpleName(), t.getMessage()); } else { return String.format("%c[%s] %s", level, tag, message); } } }
Java
// Openbravo POS is a point of sales application designed for touch screens. // Copyright (C) 2007-2009 Openbravo, S.L. // http://www.openbravo.com/product/pos // // This file is part of Openbravo POS. // // Openbravo POS is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Openbravo POS is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Openbravo POS. If not, see <http://www.gnu.org/licenses/>. package com.openbravo.pos.printer.escpos; public class CodesIthaca extends Codes { private static final byte[] INITSEQUENCE = {}; private static final byte[] CHAR_SIZE_0 = {0x1D, 0x21, 0x00}; private static final byte[] CHAR_SIZE_1 = {0x1D, 0x21, 0x01}; private static final byte[] CHAR_SIZE_2 = {0x1D, 0x21, 0x30}; private static final byte[] CHAR_SIZE_3 = {0x1D, 0x21, 0x31}; public static final byte[] BOLD_SET = {0x1B, 0x45, 0x01}; public static final byte[] BOLD_RESET = {0x1B, 0x45, 0x00}; public static final byte[] UNDERLINE_SET = {0x1B, 0x2D, 0x01}; public static final byte[] UNDERLINE_RESET = {0x1B, 0x2D, 0x00}; private static final byte[] OPEN_DRAWER = {0x1B, 0x78, 0x01}; private static final byte[] PARTIAL_CUT = {0x1B, 0x50, 0x00}; private static final byte[] IMAGE_HEADER = {0x1D, 0x76, 0x30, 0x03}; private static final byte[] NEW_LINE = {0x0D, 0x0A}; // Print and carriage return /** Creates a new instance of CodesIthaca */ public CodesIthaca() { } public byte[] getInitSequence() { return INITSEQUENCE; } public byte[] getSize0() { return CHAR_SIZE_0; } public byte[] getSize1() { return CHAR_SIZE_1; } public byte[] getSize2() { return CHAR_SIZE_2; } public byte[] getSize3() { return CHAR_SIZE_3; } public byte[] getBoldSet() { return BOLD_SET; } public byte[] getBoldReset() { return BOLD_RESET; } public byte[] getUnderlineSet() { return UNDERLINE_SET; } public byte[] getUnderlineReset() { return UNDERLINE_RESET; } public byte[] getOpenDrawer() { return OPEN_DRAWER; } public byte[] getCutReceipt() { return PARTIAL_CUT; } public byte[] getNewLine() { return NEW_LINE; } public byte[] getImageHeader() { return IMAGE_HEADER; } public int getImageWidth() { return 256; } }
Java
----------------------------------- -- Area: Nashmau -- NPC: Yuyuroon -- Standard Info NPC ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0109); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
Java
#ifndef UTIL_BIT_PACKING__ #define UTIL_BIT_PACKING__ /* Bit-level packing routines */ #include <assert.h> #ifdef __APPLE__ #include <architecture/byte_order.h> #elif __linux__ #include <endian.h> #else #include <arpa/nameser_compat.h> #endif #include <inttypes.h> namespace util { /* WARNING WARNING WARNING: * The write functions assume that memory is zero initially. This makes them * faster and is the appropriate case for mmapped language model construction. * These routines assume that unaligned access to uint64_t is fast and that * storage is little endian. This is the case on x86_64. I'm not sure how * fast unaligned 64-bit access is on x86 but my target audience is large * language models for which 64-bit is necessary. * * Call the BitPackingSanity function to sanity check. Calling once suffices, * but it may be called multiple times when that's inconvenient. */ // Fun fact: __BYTE_ORDER is wrong on Solaris Sparc, but the version without __ is correct. #if BYTE_ORDER == LITTLE_ENDIAN inline uint8_t BitPackShift(uint8_t bit, uint8_t /*length*/) { return bit; } #elif BYTE_ORDER == BIG_ENDIAN inline uint8_t BitPackShift(uint8_t bit, uint8_t length) { return 64 - length - bit; } #else #error "Bit packing code isn't written for your byte order." #endif inline uint64_t ReadOff(const void *base, uint64_t bit_off) { return *reinterpret_cast<const uint64_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3)); } /* Pack integers up to 57 bits using their least significant digits. * The length is specified using mask: * Assumes mask == (1 << length) - 1 where length <= 57. */ inline uint64_t ReadInt57(const void *base, uint64_t bit_off, uint8_t length, uint64_t mask) { return (ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, length)) & mask; } /* Assumes value < (1 << length) and length <= 57. * Assumes the memory is zero initially. */ inline void WriteInt57(void *base, uint64_t bit_off, uint8_t length, uint64_t value) { *reinterpret_cast<uint64_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |= (value << BitPackShift(bit_off & 7, length)); } /* Same caveats as above, but for a 25 bit limit. */ inline uint32_t ReadInt25(const void *base, uint64_t bit_off, uint8_t length, uint32_t mask) { return (*reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3)) >> BitPackShift(bit_off & 7, length)) & mask; } inline void WriteInt25(void *base, uint64_t bit_off, uint8_t length, uint32_t value) { *reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |= (value << BitPackShift(bit_off & 7, length)); } typedef union { float f; uint32_t i; } FloatEnc; inline float ReadFloat32(const void *base, uint64_t bit_off) { FloatEnc encoded; encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 32); return encoded.f; } inline void WriteFloat32(void *base, uint64_t bit_off, float value) { FloatEnc encoded; encoded.f = value; WriteInt57(base, bit_off, 32, encoded.i); } const uint32_t kSignBit = 0x80000000; inline void SetSign(float &to) { FloatEnc enc; enc.f = to; enc.i |= kSignBit; to = enc.f; } inline void UnsetSign(float &to) { FloatEnc enc; enc.f = to; enc.i &= ~kSignBit; to = enc.f; } inline float ReadNonPositiveFloat31(const void *base, uint64_t bit_off) { FloatEnc encoded; encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 31); // Sign bit set means negative. encoded.i |= kSignBit; return encoded.f; } inline void WriteNonPositiveFloat31(void *base, uint64_t bit_off, float value) { FloatEnc encoded; encoded.f = value; encoded.i &= ~kSignBit; WriteInt57(base, bit_off, 31, encoded.i); } void BitPackingSanity(); // Return bits required to store integers upto max_value. Not the most // efficient implementation, but this is only called a few times to size tries. uint8_t RequiredBits(uint64_t max_value); struct BitsMask { static BitsMask ByMax(uint64_t max_value) { BitsMask ret; ret.FromMax(max_value); return ret; } static BitsMask ByBits(uint8_t bits) { BitsMask ret; ret.bits = bits; ret.mask = (1ULL << bits) - 1; return ret; } void FromMax(uint64_t max_value) { bits = RequiredBits(max_value); mask = (1ULL << bits) - 1; } uint8_t bits; uint64_t mask; }; } // namespace util #endif // UTIL_BIT_PACKING__
Java
#region Copyright & License Information /* * Copyright 2007-2011 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System.Collections.Generic; using OpenRA.FileFormats; using OpenRA.Traits; namespace OpenRA.Mods.RA { [Desc("Used to waypoint units after production or repair is finished.")] public class RallyPointInfo : ITraitInfo { public readonly int[] RallyPoint = { 1, 3 }; public readonly string IndicatorPalettePrefix = "player"; public object Create(ActorInitializer init) { return new RallyPoint(init.self, this); } } public class RallyPoint : IIssueOrder, IResolveOrder, ISync { [Sync] public CPos rallyPoint; public int nearEnough = 1; public RallyPoint(Actor self, RallyPointInfo info) { rallyPoint = self.Location + new CVec(info.RallyPoint[0], info.RallyPoint[1]); self.World.AddFrameEndTask(w => w.Add(new Effects.RallyPoint(self, info.IndicatorPalettePrefix))); } public IEnumerable<IOrderTargeter> Orders { get { yield return new RallyPointOrderTargeter(); } } public Order IssueOrder( Actor self, IOrderTargeter order, Target target, bool queued ) { if( order.OrderID == "SetRallyPoint" ) return new Order(order.OrderID, self, false) { TargetLocation = target.CenterPosition.ToCPos() }; return null; } public void ResolveOrder( Actor self, Order order ) { if( order.OrderString == "SetRallyPoint" ) rallyPoint = order.TargetLocation; } class RallyPointOrderTargeter : IOrderTargeter { public string OrderID { get { return "SetRallyPoint"; } } public int OrderPriority { get { return 0; } } public bool CanTarget(Actor self, Target target, List<Actor> othersAtTarget, TargetModifiers modifiers, ref string cursor) { if (target.Type != TargetType.Terrain) return false; var location = target.CenterPosition.ToCPos(); if (self.World.Map.IsInMap(location)) { cursor = "ability"; return true; } return false; } public bool IsQueued { get { return false; } } // unused } } }
Java
<!-- Data Source: http://www.htmlhelp.com/reference/html40/entities/symbols.html HTML To Convert JSON http://convertjson.com/html-table-to-json.htm Creator : ARGE|LOG [email protected] --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>summernote</title> <!-- include jquery --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <!-- include libs stylesheets --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.css" /> <script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.js"></script> <!-- include summernote --> <link rel="stylesheet" href="../dist/summernote-bs4.css"> <script type="text/javascript" src="../dist/summernote-bs4.js"></script> <script src="https://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> $(function() { $('.summernote').summernote({ height: 200, hint: { match: /=(\w{0,})$/, search: function(keyword, callback) { $.ajax({ url: 'symbols_mathematical-symbols_Greek-letters.json?v=1' }).then(function (data) { callback(data.filter(function(item){return item.Character.indexOf(keyword)>-1 || item.FIELD6.indexOf(keyword)>-1;})); }); }, content: function(item) { return item.FIELD6; }, template: function(item) { return '[<strong>' + item.FIELD6 + '</strong>] ' + item.Character; } } }); }); </script> </head> <body> <textarea class="summernote">type #su</textarea> </body> </html>
Java
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * The "namespaces" collection of methods. * Typical usage is: * <code> * $runService = new Google_Service_CloudRun(...); * $namespaces = $runService->namespaces; * </code> */ class Google_Service_CloudRun_Resource_ProjectsLocationsNamespaces extends Google_Service_Resource { /** * Rpc to get information about a namespace. (namespaces.get) * * @param string $name Required. The name of the namespace being retrieved. If * needed, replace {namespace_id} with the project ID. * @param array $optParams Optional parameters. * @return Google_Service_CloudRun_RunNamespace */ public function get($name, $optParams = array()) { $params = array('name' => $name); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_CloudRun_RunNamespace"); } /** * Rpc to update a namespace. (namespaces.patch) * * @param string $name Required. The name of the namespace being retrieved. If * needed, replace {namespace_id} with the project ID. * @param Google_Service_CloudRun_RunNamespace $postBody * @param array $optParams Optional parameters. * * @opt_param string updateMask Required. Indicates which fields in the provided * namespace to update. This field is currently unused. * @return Google_Service_CloudRun_RunNamespace */ public function patch($name, Google_Service_CloudRun_RunNamespace $postBody, $optParams = array()) { $params = array('name' => $name, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('patch', array($params), "Google_Service_CloudRun_RunNamespace"); } }
Java
<?php /** * Mahara: Electronic portfolio, weblog, resume builder and social networking * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see: * http://wiki.mahara.org/Contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package mahara * @subpackage lang * @author Catalyst IT Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU GPL * @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz * */ defined('INTERNAL') || die(); $string['pluginname'] = 'Profile'; $string['profile'] = 'Profile'; $string['mandatory'] = 'Mandatory'; $string['public'] = 'Public'; $string['aboutdescription'] = 'Enter your real first and last name here. If you want to show a different name to people in the system, put that name in as your display name.'; $string['infoisprivate'] = 'This information is private until you include it in a page that is shared with others.'; $string['viewmyprofile'] = 'View my profile'; // profile categories $string['aboutme'] = 'About me'; $string['contact'] = 'Contact information'; $string['messaging'] = 'Messaging'; $string['general'] = 'General'; // profile fields $string['firstname'] = 'First Name'; $string['lastname'] = 'Last Name'; $string['fullname'] = 'Full Name'; $string['institution'] = 'Institution'; $string['studentid'] = 'Student ID'; $string['preferredname'] = 'Display Name'; $string['introduction'] = 'Introduction'; $string['email'] = 'Email Address'; $string['maildisabled'] = 'Email Disabled'; $string['officialwebsite'] = 'Official Website Address'; $string['personalwebsite'] = 'Personal Website Address'; $string['blogaddress'] = 'Blog Address'; $string['address'] = 'Postal Address'; $string['town'] = 'Town'; $string['city'] = 'City/Region'; $string['country'] = 'Country'; $string['homenumber'] = 'Home Phone'; $string['businessnumber'] = 'Business Phone'; $string['mobilenumber'] = 'Mobile Phone'; $string['faxnumber'] = 'Fax Number'; $string['icqnumber'] = 'ICQ Number'; $string['msnnumber'] = 'MSN Chat'; $string['aimscreenname'] = 'AIM Screen Name'; $string['yahoochat'] = 'Yahoo Chat'; $string['skypeusername'] = 'Skype Username'; $string['jabberusername'] = 'Jabber Username'; $string['occupation'] = 'Occupation'; $string['industry'] = 'Industry'; // Field names for view user and search user display $string['name'] = 'Name'; $string['principalemailaddress'] = 'Primary email'; $string['emailaddress'] = 'Alternative email'; $string['saveprofile'] = 'Save Profile'; $string['profilesaved'] = 'Profile saved successfully'; $string['profilefailedsaved'] = 'Profile saving failed'; $string['emailvalidation_subject'] = 'Email validation'; $string['emailvalidation_body'] = <<<EOF Hello %s, You have added email address %s to your user account in Mahara. Please visit the link below to activate this address. %s If this email belongs to you but you have not requested adding it to your Mahara account, follow the link below to decline email activation. %s EOF; $string['validationemailwillbesent'] = 'a validation email will be sent when you save your profile'; $string['validationemailsent'] = 'a validation email has been sent'; $string['emailactivation'] = 'Email Activation'; $string['emailactivationsucceeded'] = 'Email Activation Successful'; $string['emailalreadyactivated'] = 'Email already activiated'; $string['emailactivationfailed'] = 'Email Activation Failed'; $string['emailactivationdeclined'] = 'Email Activation Declined Successfully'; $string['verificationlinkexpired'] = 'Verification link expired'; $string['invalidemailaddress'] = 'Invalid email address'; $string['unvalidatedemailalreadytaken'] = 'The e-mail address you are trying to validate is already taken'; $string['addbutton'] = 'Add'; $string['emailingfailed'] = 'Profile saved, but emails were not sent to: %s'; $string['loseyourchanges'] = 'Lose your changes?'; $string['Title'] = 'Title'; $string['Created'] = 'Created'; $string['Description'] = 'Description'; $string['Download'] = 'Download'; $string['lastmodified'] = 'Last Modified'; $string['Owner'] = 'Owner'; $string['Preview'] = 'Preview'; $string['Size'] = 'Size'; $string['Type'] = 'Type'; $string['profileinformation'] = 'Profile Information'; $string['profilepage'] = 'Profile Page'; $string['viewprofilepage'] = 'View profile page'; $string['viewallprofileinformation'] = 'View all profile information';
Java
#include <parmetislib.h> /* Byte-wise swap two items of size SIZE. */ #define QSSWAP(a, b, stmp) do { stmp = (a); (a) = (b); (b) = stmp; } while (0) /* Discontinue quicksort algorithm when partition gets below this size. This particular magic number was chosen to work best on a Sun 4/260. */ #define MAX_THRESH 20 /* Stack node declarations used to store unfulfilled partition obligations. */ typedef struct { KeyValueType *lo; KeyValueType *hi; } stack_node; /* The next 4 #defines implement a very fast in-line stack abstraction. */ #define STACK_SIZE (8 * sizeof(unsigned long int)) #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top)) #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi))) #define STACK_NOT_EMPTY (stack < top) void ikeyvalsort(int total_elems, KeyValueType *pbase) { KeyValueType pivot, stmp; if (total_elems == 0) /* Avoid lossage with unsigned arithmetic below. */ return; if (total_elems > MAX_THRESH) { KeyValueType *lo = pbase; KeyValueType *hi = &lo[total_elems - 1]; stack_node stack[STACK_SIZE]; /* Largest size needed for 32-bit int!!! */ stack_node *top = stack + 1; while (STACK_NOT_EMPTY) { KeyValueType *left_ptr; KeyValueType *right_ptr; KeyValueType *mid = lo + ((hi - lo) >> 1); if (mid->key < lo->key || (mid->key == lo->key && mid->val < lo->val)) QSSWAP(*mid, *lo, stmp); if (hi->key < mid->key || (hi->key == mid->key && hi->val < mid->val)) QSSWAP(*mid, *hi, stmp); else goto jump_over; if (mid->key < lo->key || (mid->key == lo->key && mid->val < lo->val)) QSSWAP(*mid, *lo, stmp); jump_over:; pivot = *mid; left_ptr = lo + 1; right_ptr = hi - 1; /* Here's the famous ``collapse the walls'' section of quicksort. Gotta like those tight inner loops! They are the main reason that this algorithm runs much faster than others. */ do { while (left_ptr->key < pivot.key || (left_ptr->key == pivot.key && left_ptr->val < pivot.val)) left_ptr++; while (pivot.key < right_ptr->key || (pivot.key == right_ptr->key && pivot.val < right_ptr->val)) right_ptr--; if (left_ptr < right_ptr) { QSSWAP (*left_ptr, *right_ptr, stmp); left_ptr++; right_ptr--; } else if (left_ptr == right_ptr) { left_ptr++; right_ptr--; break; } } while (left_ptr <= right_ptr); /* Set up pointers for next iteration. First determine whether left and right partitions are below the threshold size. If so, ignore one or both. Otherwise, push the larger partition's bounds on the stack and continue sorting the smaller one. */ if ((size_t) (right_ptr - lo) <= MAX_THRESH) { if ((size_t) (hi - left_ptr) <= MAX_THRESH) /* Ignore both small partitions. */ POP (lo, hi); else /* Ignore small left partition. */ lo = left_ptr; } else if ((size_t) (hi - left_ptr) <= MAX_THRESH) /* Ignore small right partition. */ hi = right_ptr; else if ((right_ptr - lo) > (hi - left_ptr)) { /* Push larger left partition indices. */ PUSH (lo, right_ptr); lo = left_ptr; } else { /* Push larger right partition indices. */ PUSH (left_ptr, hi); hi = right_ptr; } } } /* Once the BASE_PTR array is partially sorted by quicksort the rest is completely sorted using insertion sort, since this is efficient for partitions below MAX_THRESH size. BASE_PTR points to the beginning of the array to sort, and END_PTR points at the very last element in the array (*not* one beyond it!). */ { KeyValueType *end_ptr = &pbase[total_elems - 1]; KeyValueType *tmp_ptr = pbase; KeyValueType *thresh = (end_ptr < pbase + MAX_THRESH ? end_ptr : pbase + MAX_THRESH); register KeyValueType *run_ptr; /* Find smallest element in first threshold and place it at the array's beginning. This is the smallest array element, and the operation speeds up insertion sort's inner loop. */ for (run_ptr = tmp_ptr + 1; run_ptr <= thresh; run_ptr++) if (run_ptr->key < tmp_ptr->key || (run_ptr->key == tmp_ptr->key && run_ptr->val < tmp_ptr->val)) tmp_ptr = run_ptr; if (tmp_ptr != pbase) QSSWAP(*tmp_ptr, *pbase, stmp); /* Insertion sort, running from left-hand-side up to right-hand-side. */ run_ptr = pbase + 1; while (++run_ptr <= end_ptr) { tmp_ptr = run_ptr - 1; while (run_ptr->key < tmp_ptr->key || (run_ptr->key == tmp_ptr->key && run_ptr->val < tmp_ptr->val)) tmp_ptr--; tmp_ptr++; if (tmp_ptr != run_ptr) { KeyValueType elmnt = *run_ptr; KeyValueType *mptr; for (mptr=run_ptr; mptr>tmp_ptr; mptr--) *mptr = *(mptr-1); *mptr = elmnt; } } } }
Java
/* This file is part of HSPlasma. * * HSPlasma is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HSPlasma is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HSPlasma. If not, see <http://www.gnu.org/licenses/>. */ #include "plSDL.h" unsigned int plSDL::VariableLengthRead(hsStream* S, size_t size) { if (size < 0x100) return S->readByte(); else if (size < 0x10000) return S->readShort(); else return S->readInt(); } void plSDL::VariableLengthWrite(hsStream* S, size_t size, unsigned int value) { if (size < 0x100) S->writeByte(value); else if (size < 0x10000) S->writeShort(value); else S->writeInt(value); }
Java
#Region "Microsoft.VisualBasic::593db87795bffd7fe72a1c6b208d9e4b, ..\sciBASIC#\mime\text%yaml\yaml\Syntax\Tag.vb" ' Author: ' ' asuka ([email protected]) ' xieguigang ([email protected]) ' xie ([email protected]) ' ' Copyright (c) 2016 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program. If not, see <http://www.gnu.org/licenses/>. #End Region Imports System.Collections.Generic Imports System.Text Namespace Syntax Public Class Tag End Class End Namespace
Java
package com.redhat.jcliff; import java.io.StringBufferInputStream; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.jboss.dmr.ModelNode; public class DeploymentTest { @Test public void replace() throws Exception { ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"} }")); ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}")); Deployment d=new Deployment(new Ctx(),true); Map<String,Set<String>> map=d.findDeploymentsToReplace(newDeployments,existingDeployments); Assert.assertEquals("app2",map.get("app2").iterator().next()); Assert.assertNull(map.get("app1")); Assert.assertEquals(1,map.size()); } @Test public void newdeployments() throws Exception { ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"} }")); ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}")); Deployment d=new Deployment(new Ctx(),true); String[] news=d.getNewDeployments(newDeployments,existingDeployments.keys()); Assert.assertEquals(1,news.length); Assert.assertEquals("app3",news[0]); } @Test public void undeployments() throws Exception { ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"}, \"app4\"=>\"deleted\" }")); ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}")); Deployment d=new Deployment(new Ctx(),true); String[] und=d.getUndeployments(newDeployments,existingDeployments); Assert.assertEquals(1,und.length); Assert.assertEquals("app1",und[0]); } }
Java
# Contextual Identities ## What it does Lists existing identities, lets you create new tabs with an identity and remove all tabs from an identity. For more information on contextual identities: https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers ## What it shows How to use the contextualIdentities API. Please note: you must have contextualIdentities enabled. You can do that by going to about:config and setting the `privacy.userContext.enabled` preference to true. If you are using web-ext you can do this by running: web-ext run --pref privacy.userContext.enabled=true Icon from: https://www.iconfinder.com/icons/290119/card_id_identification_identity_profile_icon#size=128, License: "Free for commercial use".
Java
<!DOCTYPE html> <!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using common/security-features/tools/template/test.release.html.template. --> <html> <head> <title>Referrer-Policy: Referrer Policy is set to 'strict-origin-when-cross-origin'</title> <meta charset='utf-8'> <meta name="description" content="Check that a priori insecure subresource gets no referrer information. Otherwise, cross-origin subresources get the origin portion of the referrer URL and same-origin get the stripped referrer URL."> <link rel="author" title="Kristijan Burnik" href="[email protected]"> <link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin-when-cross-origin"> <meta name="assert" content="Referrer Policy: Expects stripped-referrer for fetch to same-http origin and no-redirect redirection from http context."> <meta name="referrer" content="no-referrer"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/security-features/resources/common.sub.js"></script> <script src="/referrer-policy/generic/test-case.sub.js"></script> </head> <body> <script> TestCase( { "expectation": "stripped-referrer", "origin": "same-http", "redirection": "no-redirect", "source_context_list": [ { "policyDeliveries": [ { "deliveryType": "http-rp", "key": "referrerPolicy", "value": "strict-origin-when-cross-origin" } ], "sourceContextType": "worker-classic" } ], "source_scheme": "http", "subresource": "fetch", "subresource_policy_deliveries": [] }, document.querySelector("meta[name=assert]").content, new SanityChecker() ).start(); </script> <div id="log"></div> </body> </html>
Java
package raft import ( "bytes" crand "crypto/rand" "fmt" "math" "math/big" "math/rand" "time" "github.com/hashicorp/go-msgpack/codec" ) func init() { // Ensure we use a high-entropy seed for the pseudo-random generator rand.Seed(newSeed()) } // returns an int64 from a crypto random source // can be used to seed a source for a math/rand. func newSeed() int64 { r, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)) if err != nil { panic(fmt.Errorf("failed to read random bytes: %v", err)) } return r.Int64() } // randomTimeout returns a value that is between the minVal and 2x minVal. func randomTimeout(minVal time.Duration) <-chan time.Time { if minVal == 0 { return nil } extra := (time.Duration(rand.Int63()) % minVal) return time.After(minVal + extra) } // min returns the minimum. func min(a, b uint64) uint64 { if a <= b { return a } return b } // max returns the maximum. func max(a, b uint64) uint64 { if a >= b { return a } return b } // generateUUID is used to generate a random UUID. func generateUUID() string { buf := make([]byte, 16) if _, err := crand.Read(buf); err != nil { panic(fmt.Errorf("failed to read random bytes: %v", err)) } return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x", buf[0:4], buf[4:6], buf[6:8], buf[8:10], buf[10:16]) } // asyncNotifyCh is used to do an async channel send // to a single channel without blocking. func asyncNotifyCh(ch chan struct{}) { select { case ch <- struct{}{}: default: } } // drainNotifyCh empties out a single-item notification channel without // blocking, and returns whether it received anything. func drainNotifyCh(ch chan struct{}) bool { select { case <-ch: return true default: return false } } // asyncNotifyBool is used to do an async notification // on a bool channel. func asyncNotifyBool(ch chan bool, v bool) { select { case ch <- v: default: } } // overrideNotifyBool is used to notify on a bool channel // but override existing value if value is present. // ch must be 1-item buffered channel. // // This method does not support multiple concurrent calls. func overrideNotifyBool(ch chan bool, v bool) { select { case ch <- v: // value sent, all done case <-ch: // channel had an old value select { case ch <- v: default: panic("race: channel was sent concurrently") } } } // Decode reverses the encode operation on a byte slice input. func decodeMsgPack(buf []byte, out interface{}) error { r := bytes.NewBuffer(buf) hd := codec.MsgpackHandle{} dec := codec.NewDecoder(r, &hd) return dec.Decode(out) } // Encode writes an encoded object to a new bytes buffer. func encodeMsgPack(in interface{}) (*bytes.Buffer, error) { buf := bytes.NewBuffer(nil) hd := codec.MsgpackHandle{} enc := codec.NewEncoder(buf, &hd) err := enc.Encode(in) return buf, err } // backoff is used to compute an exponential backoff // duration. Base time is scaled by the current round, // up to some maximum scale factor. func backoff(base time.Duration, round, limit uint64) time.Duration { power := min(round, limit) for power > 2 { base *= 2 power-- } return base } // Needed for sorting []uint64, used to determine commitment type uint64Slice []uint64 func (p uint64Slice) Len() int { return len(p) } func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] } func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
Java
<!DOCTYPE html> <!-- DO NOT EDIT! Generated by upgrade-insecure-requests/generic/tools/generate.py using common/security-features/tools/template/test.release.html.template. --> <html> <head> <title>Upgrade-Insecure-Requests: With upgrade-insecure-request</title> <meta charset='utf-8'> <meta name="description" content="With upgrade-insecure-request"> <link rel="author" title="Kristijan Burnik" href="[email protected]"> <link rel="help" href="https://w3c.github.io/webappsec-upgrade-insecure-requests/"> <meta name="assert" content="Upgrade-Insecure-Requests: Expects allowed for xhr to same-http-downgrade origin and no-redirect redirection from https context."> <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/security-features/resources/common.sub.js"></script> <script src="/upgrade-insecure-requests/generic/test-case.sub.js"></script> </head> <body> <script> TestCase( { "expectation": "allowed", "origin": "same-http-downgrade", "redirection": "no-redirect", "source_context_list": [ { "policyDeliveries": [], "sourceContextType": "worker-classic-data" } ], "source_scheme": "https", "subresource": "xhr", "subresource_policy_deliveries": [] }, document.querySelector("meta[name=assert]").content, new SanityChecker() ).start(); </script> <div id="log"></div> </body> </html>
Java
package net.tropicraft.world.genlayer; import net.minecraft.world.gen.layer.IntCache; public class GenLayerTropiVoronoiZoom extends GenLayerTropicraft { public enum Mode { CARTESIAN, MANHATTAN; } public Mode zoomMode; public GenLayerTropiVoronoiZoom(long seed, GenLayerTropicraft parent, Mode zoomMode) { super(seed); super.parent = parent; this.zoomMode = zoomMode; this.setZoom(1); } /** * Returns a list of integer values generated by this layer. These may be interpreted as temperatures, rainfall * amounts, or biomeList[] indices based on the particular GenLayer subclass. */ public int[] getInts(int x, int y, int width, int length) { final int randomResolution = 1024; final double half = 0.5D; final double almostTileSize = 3.6D; final double tileSize = 4D; x -= 2; y -= 2; int scaledX = x >> 2; int scaledY = y >> 2; int scaledWidth = (width >> 2) + 2; int scaledLength = (length >> 2) + 2; int[] parentValues = this.parent.getInts(scaledX, scaledY, scaledWidth, scaledLength); int bitshiftedWidth = scaledWidth - 1 << 2; int bitshiftedLength = scaledLength - 1 << 2; int[] aint1 = IntCache.getIntCache(bitshiftedWidth * bitshiftedLength); int i; for(int j = 0; j < scaledLength - 1; ++j) { i = 0; int baseValue = parentValues[i + 0 + (j + 0) * scaledWidth]; for(int advancedValueJ = parentValues[i + 0 + (j + 1) * scaledWidth]; i < scaledWidth - 1; ++i) { this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY << 2)); double offsetY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; double offsetX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY << 2)); double offsetYY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; double offsetXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY + 1 << 2)); double offsetYX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; double offsetXX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY + 1 << 2)); double offsetYXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; double offsetXXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; int advancedValueI = parentValues[i + 1 + (j + 0) * scaledWidth] & 255; int advancedValueIJ = parentValues[i + 1 + (j + 1) * scaledWidth] & 255; for(int innerX = 0; innerX < 4; ++innerX) { int index = ((j << 2) + innerX) * bitshiftedWidth + (i << 2); for(int innerY = 0; innerY < 4; ++innerY) { double baseDistance; double distanceY; double distanceX; double distanceXY; switch(zoomMode) { case CARTESIAN: baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY); distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY); distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX); distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY); break; case MANHATTAN: baseDistance = Math.abs(innerX - offsetX) + Math.abs(innerY - offsetY); distanceY = Math.abs(innerX - offsetXY) + Math.abs(innerY - offsetYY); distanceX = Math.abs(innerX - offsetXX) + Math.abs(innerY - offsetYX); distanceXY = Math.abs(innerX - offsetXXY) + Math.abs(innerY - offsetYXY); break; default: baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY); distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY); distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX); distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY); } if(baseDistance < distanceY && baseDistance < distanceX && baseDistance < distanceXY) { aint1[index++] = baseValue; } else if(distanceY < baseDistance && distanceY < distanceX && distanceY < distanceXY) { aint1[index++] = advancedValueI; } else if(distanceX < baseDistance && distanceX < distanceY && distanceX < distanceXY) { aint1[index++] = advancedValueJ; } else { aint1[index++] = advancedValueIJ; } } } baseValue = advancedValueI; advancedValueJ = advancedValueIJ; } } int[] aint2 = IntCache.getIntCache(width * length); for(i = 0; i < length; ++i) { System.arraycopy(aint1, (i + (y & 3)) * bitshiftedWidth + (x & 3), aint2, i * width, width); } return aint2; } @Override public void setZoom(int zoom) { this.zoom = zoom; parent.setZoom(zoom * 4); } }
Java
initSidebarItems({"mod":[["color",""],["geometry",""],["layers",""],["platform",""],["rendergl",""],["scene",""],["texturegl","OpenGL-specific implementation of texturing."],["tiling",""],["util",""]]});
Java
initSidebarItems({"struct":[["DefaultState","A structure which is a factory for instances of `Hasher` which implement the default trait."]],"trait":[["HashState","A trait representing stateful hashes which can be used to hash keys in a `HashMap`."]]});
Java
#form { top: 70%; left: 50%; width: 60%; } #main-login-form { top: 70%; left: 50%; width: 60%; background-color: #FFFFFF; border-radius: 10px; padding: 12px 20px; } .fixed-form { position: fixed; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .form-partial-container { margin: 0 auto; } .centered { text-align: center; } .error-message { color: red; margin-bottom: 10px; }
Java
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey="H" changePositionKey="Q" > <LogMonitor /> </DockMonitor> )
Java
/* * The contents of this file are subject to the OpenMRS Public License * Version 1.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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ var ExitHandlers = { // a widget can dynamically set "do-not-exit" or "do-not-exit-once" classes on the field to indicate we should not // exit the field. "do-not-exit-once" will be cleared after a single exit attempt. 'manual-exit': { handleExit: function(fieldModel) { var doNotExit = fieldModel.element.hasClass('do-not-exit') || fieldModel.element.hasClass('do-not-exit-once'); fieldModel.element.removeClass('do-not-exit-once'); return !doNotExit; } }, 'leading-zeros': { handleExit: function(fieldModel) { var val = fieldModel.element.val(); if (val) { // if the field is blank, leave it alone var maxLength = parseInt(fieldModel.element.attr('maxlength')); if (maxLength > 0) { while (val.length < maxLength) { val = "0" + val; } fieldModel.element.val(val); } } return true; } } };
Java
import { Model, belongsTo } from 'ember-cli-mirage'; export default Model.extend({ parent: belongsTo('alloc-file'), });
Java
<?php use Faker\Generator; class IssueModuleCest { /** * @var string $lastView helps the test skip some repeated tests in order to make the test framework run faster at the * potential cost of being accurate and reliable */ protected $lastView; /** * @var Generator $fakeData */ protected $fakeData; /** * @var integer $fakeDataSeed */ protected $fakeDataSeed; /** * @param AcceptanceTester $I */ public function _before(AcceptanceTester $I) { if (!$this->fakeData) { $this->fakeData = Faker\Factory::create(); $this->fakeDataSeed = rand(0, 2048); } $this->fakeData->seed($this->fakeDataSeed); } /** * @param AcceptanceTester $I */ public function _after(AcceptanceTester $I) { } // Tests /** * @param \AcceptanceTester $I * @param \Step\Acceptance\ModuleBuilder $moduleBuilder * @param \Helper\WebDriverHelper $webDriverHelper * * As an administrator I want to create and deploy a issue module so that I can test * that the issue functionality is working. Given that I have already created a module I expect to deploy * the module before testing. */ public function testScenarioCreateIssueModule( \AcceptanceTester $I, \Step\Acceptance\ModuleBuilder $moduleBuilder, \Helper\WebDriverHelper $webDriverHelper ) { $I->wantTo('Create a issue module for testing'); $I->amOnUrl( $webDriverHelper->getInstanceURL() ); $I->loginAsAdmin(); $moduleBuilder->createModule( \Page\IssueModule::$PACKAGE_NAME, \Page\IssueModule::$NAME, \SuiteCRM\Enumerator\SugarObjectType::issue ); $this->lastView = 'ModuleBuilder'; } /** * @param \AcceptanceTester $I * @param \Step\Acceptance\NavigationBarTester $navigationBar * @param \Step\Acceptance\ListView $listView * @param \Helper\WebDriverHelper $webDriverHelper * * As administrative user I want to view my issue test module so that I can see if it has been * deployed correctly. */ public function testScenarioViewIssueTestModule( \AcceptanceTester $I, \Step\Acceptance\NavigationBarTester $navigationBar, \Step\Acceptance\ListView $listView, \Helper\WebDriverHelper $webDriverHelper ) { $I->wantTo('View Issue Test Module'); $I->amOnUrl( $webDriverHelper->getInstanceURL() ); $I->loginAsAdmin(); // Navigate to module $navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME); $listView->waitForListViewVisible(); $this->lastView = 'ListView'; } /** * @param \AcceptanceTester $I * @param \Step\Acceptance\NavigationBarTester $navigationBar * @param \Step\Acceptance\ListView $listView * @param \Step\Acceptance\EditView $editView * @param \Step\Acceptance\DetailView $detailView * @param \Helper\WebDriverHelper $webDriverHelper * * As administrative user I want to create a record with my issue test module so that I can test * the standard fields. */ public function testScenarioCreateRecord( \AcceptanceTester $I, \Step\Acceptance\NavigationBarTester $navigationBar, \Step\Acceptance\ListView $listView, \Step\Acceptance\EditView $editView, \Step\Acceptance\DetailView $detailView, \Helper\WebDriverHelper $webDriverHelper ) { $I->wantTo('Create Issue Test Module Record'); $I->amOnUrl( $webDriverHelper->getInstanceURL() ); $I->loginAsAdmin(); // Go to Issue Test Module $navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME); $listView->waitForListViewVisible(); // Select create Issue Test Module form the current menu $navigationBar->clickCurrentMenuItem('Create ' . \Page\IssueModule::$NAME); // Create a record $this->fakeData->seed($this->fakeDataSeed); $editView->waitForEditViewVisible(); $editView->fillField('#name', $this->fakeData->name); $editView->fillField('#description', $this->fakeData->paragraph); $editView->clickSaveButton(); $detailView->waitForDetailViewVisible(); $this->lastView = 'DetailView'; } /** * @param \AcceptanceTester $I * @param \Step\Acceptance\NavigationBarTester $navigationBar * @param \Step\Acceptance\ListView $listView * @param \Step\Acceptance\DetailView $detailView * @param \Helper\WebDriverHelper $webDriverHelper * * As administrative user I want to view the record by selecting it in the list view */ public function testScenarioViewRecordFromListView( \AcceptanceTester $I, \Step\Acceptance\NavigationBarTester $navigationBar, \Step\Acceptance\ListView $listView, \Step\Acceptance\DetailView $detailView, \Helper\WebDriverHelper $webDriverHelper ) { $I->wantTo('Select Record from list view'); $I->amOnUrl( $webDriverHelper->getInstanceURL() ); $I->loginAsAdmin(); // Go to Issue Test Module $navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME); $listView->waitForListViewVisible(); $this->fakeData->seed($this->fakeDataSeed); $listView->clickFilterButton(); $listView->click('Quick Filter'); $this->fakeData->seed($this->fakeDataSeed); $listView->fillField('#name_basic', $this->fakeData->name); $listView->click('Search', '.submitButtons'); $listView->wait(1); $this->fakeData->seed($this->fakeDataSeed); $listView->clickNameLink($this->fakeData->name); $detailView->waitForDetailViewVisible(); $this->lastView = 'DetailView'; } /** * @param \AcceptanceTester $I * @param \Step\Acceptance\NavigationBarTester $navigationBar * @param \Step\Acceptance\ListView $listView * @param \Step\Acceptance\DetailView $detailView * @param \Step\Acceptance\EditView $editView * @param \Helper\WebDriverHelper $webDriverHelper * * As administrative user I want to edit the record by selecting it in the detail view */ public function testScenarioEditRecordFromDetailView( \AcceptanceTester$I, \Step\Acceptance\NavigationBarTester $navigationBar, \Step\Acceptance\ListView $listView, \Step\Acceptance\DetailView $detailView, \Step\Acceptance\EditView $editView, \Helper\WebDriverHelper $webDriverHelper ) { $I->wantTo('Edit Issue Test Module Record from detail view'); if ($this->lastView !== 'DetailView') { $I->amOnUrl( $webDriverHelper->getInstanceURL() ); $I->loginAsAdmin(); // Go to Issue Test Module $navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME); $listView->waitForListViewVisible(); // Select record from list view $listView->clickFilterButton(); $listView->click('Quick Filter'); $this->fakeData->seed($this->fakeDataSeed); $listView->fillField('#name_basic', $this->fakeData->name); $listView->click('Search', '.submitButtons'); $listView->wait(1); $this->fakeData->seed($this->fakeDataSeed); $listView->clickNameLink($this->fakeData->name); } // Edit Record $detailView->clickActionMenuItem('Edit'); // Save record $editView->click('Save'); $detailView->waitForDetailViewVisible(); $this->lastView = 'DetailView'; } /** * @param \AcceptanceTester $I * @param \Step\Acceptance\NavigationBarTester $navigationBar * @param \Step\Acceptance\ListView $listView * @param \Step\Acceptance\DetailView $detailView * @param \Step\Acceptance\EditView $editView * @param \Helper\WebDriverHelper $webDriverHelper * * As administrative user I want to duplicate the record */ public function testScenarioDuplicateRecordFromDetailView( \AcceptanceTester $I, \Step\Acceptance\NavigationBarTester $navigationBar, \Step\Acceptance\ListView $listView, \Step\Acceptance\DetailView $detailView, \Step\Acceptance\EditView $editView, \Helper\WebDriverHelper $webDriverHelper ) { $I->wantTo('Duplicate Issue Test Module Record from detail view'); if ($this->lastView !== 'DetailView') { $I->amOnUrl( $webDriverHelper->getInstanceURL() ); $I->loginAsAdmin(); // Go to Issue Test Module $navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME); $listView->waitForListViewVisible(); // Select record from list view $listView->clickFilterButton(); $listView->click('Quick Filter'); $this->fakeData->seed($this->fakeDataSeed); $listView->fillField('#name_basic', $this->fakeData->name); $listView->click('Search', '.submitButtons'); $listView->wait(1); $this->fakeData->seed($this->fakeDataSeed); $listView->clickNameLink($this->fakeData->name); } // Edit Record $detailView->clickActionMenuItem('Duplicate'); $this->fakeData->seed($this->fakeDataSeed); $editView->fillField('#name', $this->fakeData->name . '1'); // Save record $editView->click('Save'); $detailView->waitForDetailViewVisible(); $detailView->clickActionMenuItem('Delete'); $detailView->acceptPopup(); $listView->waitForListViewVisible(); $this->lastView = 'ListView'; } /** * @param \AcceptanceTester $I * @param \Step\Acceptance\NavigationBarTester $navigationBar * @param \Step\Acceptance\ListView $listView * @param \Step\Acceptance\DetailView $detailView * @param \Helper\WebDriverHelper $webDriverHelper * * As administrative user I want to delete the record by selecting it in the detail view */ public function testScenarioDeleteRecordFromDetailView( \AcceptanceTester $I, \Step\Acceptance\NavigationBarTester $navigationBar, \Step\Acceptance\ListView $listView, \Step\Acceptance\DetailView $detailView, \Helper\WebDriverHelper $webDriverHelper ) { $I->wantTo('Delete Issue Test Module Record from detail view'); if ($this->lastView !== 'DetailView') { $I->amOnUrl( $webDriverHelper->getInstanceURL() ); $I->loginAsAdmin(); // Go to Issue Test Module $navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME); $listView->waitForListViewVisible(); // Select record from list view $listView->clickFilterButton(); $listView->click('Quick Filter'); $this->fakeData->seed($this->fakeDataSeed); $listView->fillField('#name_basic', $this->fakeData->name); $listView->click('Search', '.submitButtons'); $listView->wait(1); $this->fakeData->seed($this->fakeDataSeed); $listView->clickNameLink($this->fakeData->name); } // Delete Record $detailView->clickActionMenuItem('Delete'); $detailView->acceptPopup(); $listView->waitForListViewVisible(); $this->lastView = 'ListView'; } }
Java
create table layer_prevent_geom_editors ( layer number(19,0) not null, role_name varchar2(255 char) ); alter table layer_prevent_geom_editors add constraint FKF2CC57D82AB24981 foreign key (layer) references layer;
Java
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ namespace Shopware\Bundle\ESIndexingBundle\Product; use Shopware\Bundle\ESIndexingBundle\LastIdQuery; /** * Class ProductQueryFactoryInterface */ interface ProductQueryFactoryInterface { /** * @param int $categoryId * @param int|null $limit * * @return LastIdQuery */ public function createCategoryQuery($categoryId, $limit = null); /** * @param int[] $priceIds * @param int|null $limit * * @return LastIdQuery */ public function createPriceIdQuery($priceIds, $limit = null); /** * @param int[] $unitIds * @param int|null $limit * * @return LastIdQuery */ public function createUnitIdQuery($unitIds, $limit = null); /** * @param int[] $voteIds * @param int|null $limit * * @return LastIdQuery */ public function createVoteIdQuery($voteIds, $limit = null); /** * @param int[] $productIds * @param int|null $limit * * @return LastIdQuery */ public function createProductIdQuery($productIds, $limit = null); /** * @param int[] $variantIds * @param int|null $limit * * @return LastIdQuery */ public function createVariantIdQuery($variantIds, $limit = null); /** * @param int[] $taxIds * @param int|null $limit * * @return LastIdQuery */ public function createTaxQuery($taxIds, $limit = null); /** * @param int[] $manufacturerIds * @param int|null $limit * * @return LastIdQuery */ public function createManufacturerQuery($manufacturerIds, $limit = null); /** * @param int[] $categoryIds * @param int|null $limit * * @return LastIdQuery */ public function createProductCategoryQuery($categoryIds, $limit = null); /** * @param int[] $groupIds * @param int|null $limit * * @return LastIdQuery */ public function createPropertyGroupQuery($groupIds, $limit = null); /** * @param int[] $optionIds * @param int|null $limit * * @return LastIdQuery */ public function createPropertyOptionQuery($optionIds, $limit = null); }
Java
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.resources.entities; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.Valid; /** * Represents entity. It is another type of work resource. * * @author Javier Moran Rua <[email protected]> * @author Fernando Bellas Permuy <[email protected]> */ public class Machine extends Resource { private final static ResourceEnum type = ResourceEnum.MACHINE; private String name; private String description; private Set<MachineWorkersConfigurationUnit> configurationUnits = new HashSet<>(); @Valid public Set<MachineWorkersConfigurationUnit> getConfigurationUnits() { return Collections.unmodifiableSet(configurationUnits); } public void addMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) { configurationUnits.add(unit); } public void removeMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) { configurationUnits.remove(unit); } public static Machine createUnvalidated(String code, String name, String description) { Machine machine = create(new Machine(), code); machine.name = name; machine.description = description; return machine; } public void updateUnvalidated(String name, String description) { if (!StringUtils.isBlank(name)) { this.name = name; } if (!StringUtils.isBlank(description)) { this.description = description; } } /** * Used by Hibernate. Do not use! */ protected Machine() {} public static Machine create() { return create(new Machine()); } public static Machine create(String code) { return create(new Machine(), code); } @NotEmpty(message = "machine name not specified") public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public String getShortDescription() { return name + " (" + getCode() + ")"; } public void setDescription(String description) { this.description = description; } @Override protected boolean isCriterionSatisfactionOfCorrectType(CriterionSatisfaction c) { return c.getResourceType().equals(ResourceEnum.MACHINE); } @Override public ResourceEnum getType() { return type; } @Override public String toString() { return String.format("MACHINE: %s", name); } @Override public String getHumanId() { return name; } }
Java
<?php /** * Live media server object, represents a media server association with live stream entry * * @package Core * @subpackage model * */ class kLiveMediaServer { /** * @var int */ protected $mediaServerId; /** * @var int */ protected $index; /** * @var int */ protected $dc; /** * @var string */ protected $hostname; /** * @var int */ protected $time; /** * @var string */ protected $applicationName; public function __construct($index, $hostname, $dc = null, $id = null, $applicationName = null) { $this->index = $index; $this->mediaServerId = $id; $this->hostname = $hostname; $this->dc = $dc; $this->time = time(); $this->applicationName = $applicationName; } /** * @return int $mediaServerId */ public function getMediaServerId() { return $this->mediaServerId; } /** * @return MediaServerNode */ public function getMediaServer() { $mediaServer = ServerNodePeer::retrieveByPK($this->mediaServerId); if($mediaServer instanceof MediaServerNode) return $mediaServer; return null; } /** * @return int $index */ public function getIndex() { return $this->index; } /** * @return int $dc */ public function getDc() { return $this->dc; } /** * @return string $hostname */ public function getHostname() { return $this->hostname; } /** * @return int $time */ public function getTime() { return $this->time; } /** * @return the $applicationName */ public function getApplicationName() { return $this->applicationName; } }
Java
//============================================================================= // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published // by the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // The GNU Public License is available in the file LICENSE, or you // can write to the Free Software Foundation, Inc., 59 Temple Place - // Suite 330, Boston, MA 02111-1307, USA, or you can find it on the // World Wide Web at http://www.fsf.org. //============================================================================= /** \file * \author John Bridgman */ #ifndef PARSEBOOL_H #define PARSEBOOL_H #pragma once #include <string> /** * \brief Parses string for a boolean value. * * Considers no, false, 0 and any abreviation * like " f" to be false * and everything else to be true (including * the empty string). * Ignores whitespace. * Note "false blah" is true! * \return true or false * \param str the string to parse */ bool ParseBool(const std::string &str); #endif
Java
/* * Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pydio 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. * * Description : focusable component / Tab navigation */ Interface.create("IContextMenuable", { setContextualMenu : function(contextMenu){} });
Java
module Formtastic module Helpers # @private module FieldsetWrapper protected # Generates a fieldset and wraps the content in an ordered list. When working # with nested attributes, it allows %i as interpolation option in :name. So you can do: # # f.inputs :name => 'Task #%i', :for => :tasks # # or the shorter equivalent: # # f.inputs 'Task #%i', :for => :tasks # # And it will generate a fieldset for each task with legend 'Task #1', 'Task #2', # 'Task #3' and so on. # # Note: Special case for the inline inputs (non-block): # f.inputs "My little legend", :title, :body, :author # Explicit legend string => "My little legend" # f.inputs :my_little_legend, :title, :body, :author # Localized (118n) legend with I18n key => I18n.t(:my_little_legend, ...) # f.inputs :title, :body, :author # First argument is a column => (no legend) def field_set_and_list_wrapping(*args, &block) # @private contents = args[-1].is_a?(::Hash) ? '' : args.pop.flatten html_options = args.extract_options! if block_given? contents = if template.respond_to?(:is_haml?) && template.is_haml? template.capture_haml(&block) else template.capture(&block) end end # Ruby 1.9: String#to_s behavior changed, need to make an explicit join. contents = contents.join if contents.respond_to?(:join) legend = field_set_legend(html_options) fieldset = template.content_tag(:fieldset, Formtastic::Util.html_safe(legend) << template.content_tag(:ol, Formtastic::Util.html_safe(contents)), html_options.except(:builder, :parent, :name) ) fieldset end def field_set_legend(html_options) legend = (html_options[:name] || '').to_s legend %= parent_child_index(html_options[:parent]) if html_options[:parent] && legend.include?('%i') # only applying if String includes '%i' avoids argument error when $DEBUG is true legend = template.content_tag(:legend, template.content_tag(:span, Formtastic::Util.html_safe(legend))) unless legend.blank? legend end # Gets the nested_child_index value from the parent builder. It returns a hash with each # association that the parent builds. def parent_child_index(parent) # @private # Could be {"post[authors_attributes]"=>0} or { :authors => 0 } duck = parent[:builder].instance_variable_get('@nested_child_index') # Could be symbol for the association, or a model (or an array of either, I think? TODO) child = parent[:for] # Pull a sybol or model out of Array (TODO: check if there's an Array) child = child.first if child.respond_to?(:first) # If it's an object, get a symbol from the class name child = child.class.name.underscore.to_sym unless child.is_a?(Symbol) key = "#{parent[:builder].object_name}[#{child}_attributes]" # TODO: One of the tests produces a scenario where duck is "0" and the test looks for a "1" # in the legend, so if we have a number, return it with a +1 until we can verify this scenario. return duck + 1 if duck.is_a?(Fixnum) # First try to extract key from duck Hash, then try child (duck[key] || duck[child]).to_i + 1 end end end end
Java
// NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> // Copyright (C) 2010 Winch Gate Property Limited // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef NL_MUTABLE_CONTAINER_H #define NL_MUTABLE_CONTAINER_H namespace NLMISC { /** Container wrapper that allow read/write access to element stored in * a const container. * In fact, the template only allow calling begin() and end() over * a const container. * This prevent the user to change the structure of the container. * Usage : * * class foo * { * typedef TMutableContainer<vector<string> > TMyCont; * TMyCont _MyCont; * * public: * // return the container with mutable item content but const item list * const TMyCont getContainer() const { return _MyCont; }; * } * */ template <class BaseContainer> struct TMutableContainer : public BaseContainer { typename BaseContainer::iterator begin() const { return const_cast<BaseContainer*>(static_cast<const BaseContainer*>(this))->begin(); } typename BaseContainer::iterator end() const { return const_cast<BaseContainer*>(static_cast<const BaseContainer*>(this))->end(); } }; } // namespace NLMISC #endif // NL_MUTABLE_CONTAINER_H
Java
## What is Runbook? [Runbook](https://runbook.io) is an open source monitoring service that allows you to perform automated "Reactions" when issues are detected. Runbook gives you the ability to automatically resolve DevOps alerts with zero human interaction. Simply put, Runbook is what you would get if Nagios and IFTTT had a baby. ## Open source and contributing Runbook is 100% open source and developed using the [Assembly](https://assembly.com/runbook) platform. Runbook runs as a SaaS application, with both free and paid plans. With the Assembly platform, all revenue from the product is funneled into the project and its contributors. After subtracting business expenses, 10% goes to Assembly as a fee and the rest is given back to project contributors based on a percentage of their contributions. Unlike other open source products, not only do you get the satisfaction of giving back to the community as a whole but you also get a cut of the profits. To get started, simply join us on our [Assembly Project Page](https://assembly.com/runbook). ## Documentation This page is the front page of our documentation for Runbook users and developers. Here you will find information about how Runbook works, how it is designed, and how you can contribute. To get started, we recommend these resources: [Quick Start guide](quick-start.md) [Community tutorials](community-tutorials/index.md) [Developer documentation](developers/index.md) ---
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.7"/> <title>Documentation: NexUpload.cpp File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="Logo.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">Documentation </div> <div id="projectbrief">For Arduino users</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.7 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('_nex_upload_8cpp.html','');}); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">NexUpload.cpp File Reference</div> </div> </div><!--header--> <div class="contents"> <p>The implementation of download tft file for nextion. <a href="#details">More...</a></p> <div class="textblock"><code>#include &quot;<a class="el" href="_nex_upload_8h_source.html">NexUpload.h</a>&quot;</code><br /> <code>#include &lt;SoftwareSerial.h&gt;</code><br /> </div> <p><a href="_nex_upload_8cpp_source.html">Go to the source code of this file.</a></p> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>The implementation of download tft file for nextion. </p> <dl class="section author"><dt>Author</dt><dd>Chen Zengpeng (email:<a href="#" onclick="location.href='mai'+'lto:'+'zen'+'gp'+'eng'+'.c'+'hen'+'@i'+'tea'+'d.'+'cc'; return false;">zengp<span style="display: none;">.nosp@m.</span>eng.<span style="display: none;">.nosp@m.</span>chen@<span style="display: none;">.nosp@m.</span>itea<span style="display: none;">.nosp@m.</span>d.cc</a>) </dd></dl> <dl class="section date"><dt>Date</dt><dd>2016/3/29 </dd></dl> <dl class="section copyright"><dt>Copyright</dt><dd>Copyright (C) 2014-2015 ITEAD Intelligent Systems Co., Ltd. <br /> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. </dd></dl> <p>Definition in file <a class="el" href="_nex_upload_8cpp_source.html">NexUpload.cpp</a>.</p> </div></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="_nex_upload_8cpp.html">NexUpload.cpp</a></li> <li class="footer">Generated on Fri Jan 6 2017 14:00:38 for Documentation by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.7 </li> </ul> </div> </body> </html>
Java
@charset "UTF-8"; /* Animate.css - http://daneden.me/animate Licensed under the ☺ license (http://licence.visualidiot.com/) Copyright (c) 2012 Dan Eden 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. */ body { /* Addresses a small issue in webkit: http://bit.ly/NEdoDq */ /* -webkit-backface-visibility: hidden;*/ } .animated { -webkit-animation-duration: 1s; -moz-animation-duration: 1s; -o-animation-duration: 1s; animation-duration: 1s; -webkit-animation-fill-mode: both; -moz-animation-fill-mode: both; -o-animation-fill-mode: both; animation-fill-mode: both; } .animated.hinge { -webkit-animation-duration: 2s; -moz-animation-duration: 2s; -o-animation-duration: 2s; animation-duration: 2s; } @-webkit-keyframes flash { 0%, 50%, 100% {opacity: 1;} 25%, 75% {opacity: 0;} } @-moz-keyframes flash { 0%, 50%, 100% {opacity: 1;} 25%, 75% {opacity: 0;} } @-o-keyframes flash { 0%, 50%, 100% {opacity: 1;} 25%, 75% {opacity: 0;} } @keyframes flash { 0%, 50%, 100% {opacity: 1;} 25%, 75% {opacity: 0;} } .flash { -webkit-animation-name: flash; -moz-animation-name: flash; -o-animation-name: flash; animation-name: flash; } @-webkit-keyframes shake { 0%, 100% {-webkit-transform: translateX(0);} 10%, 30%, 50%, 70%, 90% {-webkit-transform: translateX(-10px);} 20%, 40%, 60%, 80% {-webkit-transform: translateX(10px);} } @-moz-keyframes shake { 0%, 100% {-moz-transform: translateX(0);} 10%, 30%, 50%, 70%, 90% {-moz-transform: translateX(-10px);} 20%, 40%, 60%, 80% {-moz-transform: translateX(10px);} } @-o-keyframes shake { 0%, 100% {-o-transform: translateX(0);} 10%, 30%, 50%, 70%, 90% {-o-transform: translateX(-10px);} 20%, 40%, 60%, 80% {-o-transform: translateX(10px);} } @keyframes shake { 0%, 100% {transform: translateX(0);} 10%, 30%, 50%, 70%, 90% {transform: translateX(-10px);} 20%, 40%, 60%, 80% {transform: translateX(10px);} } .shake { -webkit-animation-name: shake; -moz-animation-name: shake; -o-animation-name: shake; animation-name: shake; } @-webkit-keyframes bounce { 0%, 20%, 50%, 80%, 100% {-webkit-transform: translateY(0);} 40% {-webkit-transform: translateY(-30px);} 60% {-webkit-transform: translateY(-15px);} } @-moz-keyframes bounce { 0%, 20%, 50%, 80%, 100% {-moz-transform: translateY(0);} 40% {-moz-transform: translateY(-30px);} 60% {-moz-transform: translateY(-15px);} } @-o-keyframes bounce { 0%, 20%, 50%, 80%, 100% {-o-transform: translateY(0);} 40% {-o-transform: translateY(-30px);} 60% {-o-transform: translateY(-15px);} } @keyframes bounce { 0%, 20%, 50%, 80%, 100% {transform: translateY(0);} 40% {transform: translateY(-30px);} 60% {transform: translateY(-15px);} } .bounce { -webkit-animation-name: bounce; -moz-animation-name: bounce; -o-animation-name: bounce; animation-name: bounce; } @-webkit-keyframes tada { 0% {-webkit-transform: scale(1);} 10%, 20% {-webkit-transform: scale(0.9) rotate(-3deg);} 30%, 50%, 70%, 90% {-webkit-transform: scale(1.1) rotate(3deg);} 40%, 60%, 80% {-webkit-transform: scale(1.1) rotate(-3deg);} 100% {-webkit-transform: scale(1) rotate(0);} } @-moz-keyframes tada { 0% {-moz-transform: scale(1);} 10%, 20% {-moz-transform: scale(0.9) rotate(-3deg);} 30%, 50%, 70%, 90% {-moz-transform: scale(1.1) rotate(3deg);} 40%, 60%, 80% {-moz-transform: scale(1.1) rotate(-3deg);} 100% {-moz-transform: scale(1) rotate(0);} } @-o-keyframes tada { 0% {-o-transform: scale(1);} 10%, 20% {-o-transform: scale(0.9) rotate(-3deg);} 30%, 50%, 70%, 90% {-o-transform: scale(1.1) rotate(3deg);} 40%, 60%, 80% {-o-transform: scale(1.1) rotate(-3deg);} 100% {-o-transform: scale(1) rotate(0);} } @keyframes tada { 0% {transform: scale(1);} 10%, 20% {transform: scale(0.9) rotate(-3deg);} 30%, 50%, 70%, 90% {transform: scale(1.1) rotate(3deg);} 40%, 60%, 80% {transform: scale(1.1) rotate(-3deg);} 100% {transform: scale(1) rotate(0);} } .tada { -webkit-animation-name: tada; -moz-animation-name: tada; -o-animation-name: tada; animation-name: tada; } @-webkit-keyframes swing { 20%, 40%, 60%, 80%, 100% { -webkit-transform-origin: top center; } 20% { -webkit-transform: rotate(15deg); } 40% { -webkit-transform: rotate(-10deg); } 60% { -webkit-transform: rotate(5deg); } 80% { -webkit-transform: rotate(-5deg); } 100% { -webkit-transform: rotate(0deg); } } @-moz-keyframes swing { 20% { -moz-transform: rotate(15deg); } 40% { -moz-transform: rotate(-10deg); } 60% { -moz-transform: rotate(5deg); } 80% { -moz-transform: rotate(-5deg); } 100% { -moz-transform: rotate(0deg); } } @-o-keyframes swing { 20% { -o-transform: rotate(15deg); } 40% { -o-transform: rotate(-10deg); } 60% { -o-transform: rotate(5deg); } 80% { -o-transform: rotate(-5deg); } 100% { -o-transform: rotate(0deg); } } @keyframes swing { 20% { transform: rotate(15deg); } 40% { transform: rotate(-10deg); } 60% { transform: rotate(5deg); } 80% { transform: rotate(-5deg); } 100% { transform: rotate(0deg); } } .swing { -webkit-transform-origin: top center; -moz-transform-origin: top center; -o-transform-origin: top center; transform-origin: top center; -webkit-animation-name: swing; -moz-animation-name: swing; -o-animation-name: swing; animation-name: swing; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes wobble { 0% { -webkit-transform: translateX(0%); } 15% { -webkit-transform: translateX(-25%) rotate(-5deg); } 30% { -webkit-transform: translateX(20%) rotate(3deg); } 45% { -webkit-transform: translateX(-15%) rotate(-3deg); } 60% { -webkit-transform: translateX(10%) rotate(2deg); } 75% { -webkit-transform: translateX(-5%) rotate(-1deg); } 100% { -webkit-transform: translateX(0%); } } @-moz-keyframes wobble { 0% { -moz-transform: translateX(0%); } 15% { -moz-transform: translateX(-25%) rotate(-5deg); } 30% { -moz-transform: translateX(20%) rotate(3deg); } 45% { -moz-transform: translateX(-15%) rotate(-3deg); } 60% { -moz-transform: translateX(10%) rotate(2deg); } 75% { -moz-transform: translateX(-5%) rotate(-1deg); } 100% { -moz-transform: translateX(0%); } } @-o-keyframes wobble { 0% { -o-transform: translateX(0%); } 15% { -o-transform: translateX(-25%) rotate(-5deg); } 30% { -o-transform: translateX(20%) rotate(3deg); } 45% { -o-transform: translateX(-15%) rotate(-3deg); } 60% { -o-transform: translateX(10%) rotate(2deg); } 75% { -o-transform: translateX(-5%) rotate(-1deg); } 100% { -o-transform: translateX(0%); } } @keyframes wobble { 0% { transform: translateX(0%); } 15% { transform: translateX(-25%) rotate(-5deg); } 30% { transform: translateX(20%) rotate(3deg); } 45% { transform: translateX(-15%) rotate(-3deg); } 60% { transform: translateX(10%) rotate(2deg); } 75% { transform: translateX(-5%) rotate(-1deg); } 100% { transform: translateX(0%); } } .wobble { -webkit-animation-name: wobble; -moz-animation-name: wobble; -o-animation-name: wobble; animation-name: wobble; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes pulse { 0% { -webkit-transform: scale(1); } 50% { -webkit-transform: scale(1.1); } 100% { -webkit-transform: scale(1); } } @-moz-keyframes pulse { 0% { -moz-transform: scale(1); } 50% { -moz-transform: scale(1.1); } 100% { -moz-transform: scale(1); } } @-o-keyframes pulse { 0% { -o-transform: scale(1); } 50% { -o-transform: scale(1.1); } 100% { -o-transform: scale(1); } } @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } } .pulse { -webkit-animation-name: pulse; -moz-animation-name: pulse; -o-animation-name: pulse; animation-name: pulse; } @-webkit-keyframes flip { 0% { -webkit-transform: perspective(400px) rotateY(0); -webkit-animation-timing-function: ease-out; } 40% { -webkit-transform: perspective(400px) translateZ(150px) rotateY(170deg); -webkit-animation-timing-function: ease-out; } 50% { -webkit-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); -webkit-animation-timing-function: ease-in; } 80% { -webkit-transform: perspective(400px) rotateY(360deg) scale(.95); -webkit-animation-timing-function: ease-in; } 100% { -webkit-transform: perspective(400px) scale(1); -webkit-animation-timing-function: ease-in; } } @-moz-keyframes flip { 0% { -moz-transform: perspective(400px) rotateY(0); -moz-animation-timing-function: ease-out; } 40% { -moz-transform: perspective(400px) translateZ(150px) rotateY(170deg); -moz-animation-timing-function: ease-out; } 50% { -moz-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); -moz-animation-timing-function: ease-in; } 80% { -moz-transform: perspective(400px) rotateY(360deg) scale(.95); -moz-animation-timing-function: ease-in; } 100% { -moz-transform: perspective(400px) scale(1); -moz-animation-timing-function: ease-in; } } @-o-keyframes flip { 0% { -o-transform: perspective(400px) rotateY(0); -o-animation-timing-function: ease-out; } 40% { -o-transform: perspective(400px) translateZ(150px) rotateY(170deg); -o-animation-timing-function: ease-out; } 50% { -o-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); -o-animation-timing-function: ease-in; } 80% { -o-transform: perspective(400px) rotateY(360deg) scale(.95); -o-animation-timing-function: ease-in; } 100% { -o-transform: perspective(400px) scale(1); -o-animation-timing-function: ease-in; } } @keyframes flip { 0% { transform: perspective(400px) rotateY(0); animation-timing-function: ease-out; } 40% { transform: perspective(400px) translateZ(150px) rotateY(170deg); animation-timing-function: ease-out; } 50% { transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); animation-timing-function: ease-in; } 80% { transform: perspective(400px) rotateY(360deg) scale(.95); animation-timing-function: ease-in; } 100% { transform: perspective(400px) scale(1); animation-timing-function: ease-in; } } .flip { -webkit-backface-visibility: visible !important; -webkit-animation-name: flip; -moz-backface-visibility: visible !important; -moz-animation-name: flip; -o-backface-visibility: visible !important; -o-animation-name: flip; backface-visibility: visible !important; animation-name: flip; } @-webkit-keyframes flipInX { 0% { -webkit-transform: perspective(400px) rotateX(90deg); opacity: 0; } 40% { -webkit-transform: perspective(400px) rotateX(-10deg); } 70% { -webkit-transform: perspective(400px) rotateX(10deg); } 100% { -webkit-transform: perspective(400px) rotateX(0deg); opacity: 1; } } @-moz-keyframes flipInX { 0% { -moz-transform: perspective(400px) rotateX(90deg); opacity: 0; } 40% { -moz-transform: perspective(400px) rotateX(-10deg); } 70% { -moz-transform: perspective(400px) rotateX(10deg); } 100% { -moz-transform: perspective(400px) rotateX(0deg); opacity: 1; } } @-o-keyframes flipInX { 0% { -o-transform: perspective(400px) rotateX(90deg); opacity: 0; } 40% { -o-transform: perspective(400px) rotateX(-10deg); } 70% { -o-transform: perspective(400px) rotateX(10deg); } 100% { -o-transform: perspective(400px) rotateX(0deg); opacity: 1; } } @keyframes flipInX { 0% { transform: perspective(400px) rotateX(90deg); opacity: 0; } 40% { transform: perspective(400px) rotateX(-10deg); } 70% { transform: perspective(400px) rotateX(10deg); } 100% { transform: perspective(400px) rotateX(0deg); opacity: 1; } } .flipInX { -webkit-backface-visibility: visible !important; -webkit-animation-name: flipInX; -moz-backface-visibility: visible !important; -moz-animation-name: flipInX; -o-backface-visibility: visible !important; -o-animation-name: flipInX; backface-visibility: visible !important; animation-name: flipInX; } @-webkit-keyframes flipOutX { 0% { -webkit-transform: perspective(400px) rotateX(0deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotateX(90deg); opacity: 0; } } @-moz-keyframes flipOutX { 0% { -moz-transform: perspective(400px) rotateX(0deg); opacity: 1; } 100% { -moz-transform: perspective(400px) rotateX(90deg); opacity: 0; } } @-o-keyframes flipOutX { 0% { -o-transform: perspective(400px) rotateX(0deg); opacity: 1; } 100% { -o-transform: perspective(400px) rotateX(90deg); opacity: 0; } } @keyframes flipOutX { 0% { transform: perspective(400px) rotateX(0deg); opacity: 1; } 100% { transform: perspective(400px) rotateX(90deg); opacity: 0; } } .flipOutX { -webkit-animation-name: flipOutX; -webkit-backface-visibility: visible !important; -moz-animation-name: flipOutX; -moz-backface-visibility: visible !important; -o-animation-name: flipOutX; -o-backface-visibility: visible !important; animation-name: flipOutX; backface-visibility: visible !important; } @-webkit-keyframes flipInY { 0% { -webkit-transform: perspective(400px) rotateY(90deg); opacity: 0; } 40% { -webkit-transform: perspective(400px) rotateY(-10deg); } 70% { -webkit-transform: perspective(400px) rotateY(10deg); } 100% { -webkit-transform: perspective(400px) rotateY(0deg); opacity: 1; } } @-moz-keyframes flipInY { 0% { -moz-transform: perspective(400px) rotateY(90deg); opacity: 0; } 40% { -moz-transform: perspective(400px) rotateY(-10deg); } 70% { -moz-transform: perspective(400px) rotateY(10deg); } 100% { -moz-transform: perspective(400px) rotateY(0deg); opacity: 1; } } @-o-keyframes flipInY { 0% { -o-transform: perspective(400px) rotateY(90deg); opacity: 0; } 40% { -o-transform: perspective(400px) rotateY(-10deg); } 70% { -o-transform: perspective(400px) rotateY(10deg); } 100% { -o-transform: perspective(400px) rotateY(0deg); opacity: 1; } } @keyframes flipInY { 0% { transform: perspective(400px) rotateY(90deg); opacity: 0; } 40% { transform: perspective(400px) rotateY(-10deg); } 70% { transform: perspective(400px) rotateY(10deg); } 100% { transform: perspective(400px) rotateY(0deg); opacity: 1; } } .flipInY { -webkit-backface-visibility: visible !important; -webkit-animation-name: flipInY; -moz-backface-visibility: visible !important; -moz-animation-name: flipInY; -o-backface-visibility: visible !important; -o-animation-name: flipInY; backface-visibility: visible !important; animation-name: flipInY; } @-webkit-keyframes flipOutY { 0% { -webkit-transform: perspective(400px) rotateY(0deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotateY(90deg); opacity: 0; } } @-moz-keyframes flipOutY { 0% { -moz-transform: perspective(400px) rotateY(0deg); opacity: 1; } 100% { -moz-transform: perspective(400px) rotateY(90deg); opacity: 0; } } @-o-keyframes flipOutY { 0% { -o-transform: perspective(400px) rotateY(0deg); opacity: 1; } 100% { -o-transform: perspective(400px) rotateY(90deg); opacity: 0; } } @keyframes flipOutY { 0% { transform: perspective(400px) rotateY(0deg); opacity: 1; } 100% { transform: perspective(400px) rotateY(90deg); opacity: 0; } } .flipOutY { -webkit-backface-visibility: visible !important; -webkit-animation-name: flipOutY; -moz-backface-visibility: visible !important; -moz-animation-name: flipOutY; -o-backface-visibility: visible !important; -o-animation-name: flipOutY; backface-visibility: visible !important; animation-name: flipOutY; } @-webkit-keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;} } @-moz-keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;} } @-o-keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;} } @keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;} } .fadeIn { -webkit-animation-name: fadeIn; -moz-animation-name: fadeIn; -o-animation-name: fadeIn; animation-name: fadeIn; } @-webkit-keyframes fadeInUp { 0% { opacity: 0; -webkit-transform: translateY(20px); } 100% { opacity: 1; -webkit-transform: translateY(0); } } @-moz-keyframes fadeInUp { 0% { opacity: 0; -moz-transform: translateY(20px); } 100% { opacity: 1; -moz-transform: translateY(0); } } @-o-keyframes fadeInUp { 0% { opacity: 0; -o-transform: translateY(20px); } 100% { opacity: 1; -o-transform: translateY(0); } } @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } } .fadeInUp { -webkit-animation-name: fadeInUp; -moz-animation-name: fadeInUp; -o-animation-name: fadeInUp; animation-name: fadeInUp; } @-webkit-keyframes fadeInDown { 0% { opacity: 0; -webkit-transform: translateY(-20px); } 100% { opacity: 1; -webkit-transform: translateY(0); } } @-moz-keyframes fadeInDown { 0% { opacity: 0; -moz-transform: translateY(-20px); } 100% { opacity: 1; -moz-transform: translateY(0); } } @-o-keyframes fadeInDown { 0% { opacity: 0; -o-transform: translateY(-20px); } 100% { opacity: 1; -o-transform: translateY(0); } } @keyframes fadeInDown { 0% { opacity: 0; transform: translateY(-20px); } 100% { opacity: 1; transform: translateY(0); } } .fadeInDown { -webkit-animation-name: fadeInDown; -moz-animation-name: fadeInDown; -o-animation-name: fadeInDown; animation-name: fadeInDown; } @-webkit-keyframes fadeInLeft { 0% { opacity: 0; -webkit-transform: translateX(-20px); } 100% { opacity: 1; -webkit-transform: translateX(0); } } @-moz-keyframes fadeInLeft { 0% { opacity: 0; -moz-transform: translateX(-20px); } 100% { opacity: 1; -moz-transform: translateX(0); } } @-o-keyframes fadeInLeft { 0% { opacity: 0; -o-transform: translateX(-20px); } 100% { opacity: 1; -o-transform: translateX(0); } } @keyframes fadeInLeft { 0% { opacity: 0; transform: translateX(-20px); } 100% { opacity: 1; transform: translateX(0); } } .fadeInLeft { -webkit-animation-name: fadeInLeft; -moz-animation-name: fadeInLeft; -o-animation-name: fadeInLeft; animation-name: fadeInLeft; } @-webkit-keyframes fadeInRight { 0% { opacity: 0; -webkit-transform: translateX(20px); } 100% { opacity: 1; -webkit-transform: translateX(0); } } @-moz-keyframes fadeInRight { 0% { opacity: 0; -moz-transform: translateX(20px); } 100% { opacity: 1; -moz-transform: translateX(0); } } @-o-keyframes fadeInRight { 0% { opacity: 0; -o-transform: translateX(20px); } 100% { opacity: 1; -o-transform: translateX(0); } } @keyframes fadeInRight { 0% { opacity: 0; transform: translateX(20px); } 100% { opacity: 1; transform: translateX(0); } } .fadeInRight { -webkit-animation-name: fadeInRight; -moz-animation-name: fadeInRight; -o-animation-name: fadeInRight; animation-name: fadeInRight; } @-webkit-keyframes fadeInUpBig { 0% { opacity: 0; -webkit-transform: translateY(2000px); } 100% { opacity: 1; -webkit-transform: translateY(0); } } @-moz-keyframes fadeInUpBig { 0% { opacity: 0; -moz-transform: translateY(2000px); } 100% { opacity: 1; -moz-transform: translateY(0); } } @-o-keyframes fadeInUpBig { 0% { opacity: 0; -o-transform: translateY(2000px); } 100% { opacity: 1; -o-transform: translateY(0); } } @keyframes fadeInUpBig { 0% { opacity: 0; transform: translateY(2000px); } 100% { opacity: 1; transform: translateY(0); } } .fadeInUpBig { -webkit-animation-name: fadeInUpBig; -moz-animation-name: fadeInUpBig; -o-animation-name: fadeInUpBig; animation-name: fadeInUpBig; } @-webkit-keyframes fadeInDownBig { 0% { opacity: 0; -webkit-transform: translateY(-2000px); } 100% { opacity: 1; -webkit-transform: translateY(0); } } @-moz-keyframes fadeInDownBig { 0% { opacity: 0; -moz-transform: translateY(-2000px); } 100% { opacity: 1; -moz-transform: translateY(0); } } @-o-keyframes fadeInDownBig { 0% { opacity: 0; -o-transform: translateY(-2000px); } 100% { opacity: 1; -o-transform: translateY(0); } } @keyframes fadeInDownBig { 0% { opacity: 0; transform: translateY(-2000px); } 100% { opacity: 1; transform: translateY(0); } } .fadeInDownBig { -webkit-animation-name: fadeInDownBig; -moz-animation-name: fadeInDownBig; -o-animation-name: fadeInDownBig; animation-name: fadeInDownBig; } @-webkit-keyframes fadeInLeftBig { 0% { opacity: 0; -webkit-transform: translateX(-2000px); } 100% { opacity: 1; -webkit-transform: translateX(0); } } @-moz-keyframes fadeInLeftBig { 0% { opacity: 0; -moz-transform: translateX(-2000px); } 100% { opacity: 1; -moz-transform: translateX(0); } } @-o-keyframes fadeInLeftBig { 0% { opacity: 0; -o-transform: translateX(-2000px); } 100% { opacity: 1; -o-transform: translateX(0); } } @keyframes fadeInLeftBig { 0% { opacity: 0; transform: translateX(-2000px); } 100% { opacity: 1; transform: translateX(0); } } .fadeInLeftBig { -webkit-animation-name: fadeInLeftBig; -moz-animation-name: fadeInLeftBig; -o-animation-name: fadeInLeftBig; animation-name: fadeInLeftBig; } @-webkit-keyframes fadeInRightBig { 0% { opacity: 0; -webkit-transform: translateX(2000px); } 100% { opacity: 1; -webkit-transform: translateX(0); } } @-moz-keyframes fadeInRightBig { 0% { opacity: 0; -moz-transform: translateX(2000px); } 100% { opacity: 1; -moz-transform: translateX(0); } } @-o-keyframes fadeInRightBig { 0% { opacity: 0; -o-transform: translateX(2000px); } 100% { opacity: 1; -o-transform: translateX(0); } } @keyframes fadeInRightBig { 0% { opacity: 0; transform: translateX(2000px); } 100% { opacity: 1; transform: translateX(0); } } .fadeInRightBig { -webkit-animation-name: fadeInRightBig; -moz-animation-name: fadeInRightBig; -o-animation-name: fadeInRightBig; animation-name: fadeInRightBig; } @-webkit-keyframes fadeOut { 0% {opacity: 1;} 100% {opacity: 0;} } @-moz-keyframes fadeOut { 0% {opacity: 1;} 100% {opacity: 0;} } @-o-keyframes fadeOut { 0% {opacity: 1;} 100% {opacity: 0;} } @keyframes fadeOut { 0% {opacity: 1;} 100% {opacity: 0;} } .fadeOut { -webkit-animation-name: fadeOut; -moz-animation-name: fadeOut; -o-animation-name: fadeOut; animation-name: fadeOut; } @-webkit-keyframes fadeOutUp { 0% { opacity: 1; -webkit-transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-20px); } } @-moz-keyframes fadeOutUp { 0% { opacity: 1; -moz-transform: translateY(0); } 100% { opacity: 0; -moz-transform: translateY(-20px); } } @-o-keyframes fadeOutUp { 0% { opacity: 1; -o-transform: translateY(0); } 100% { opacity: 0; -o-transform: translateY(-20px); } } @keyframes fadeOutUp { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-20px); } } .fadeOutUp { -webkit-animation-name: fadeOutUp; -moz-animation-name: fadeOutUp; -o-animation-name: fadeOutUp; animation-name: fadeOutUp; } @-webkit-keyframes fadeOutDown { 0% { opacity: 1; -webkit-transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(20px); } } @-moz-keyframes fadeOutDown { 0% { opacity: 1; -moz-transform: translateY(0); } 100% { opacity: 0; -moz-transform: translateY(20px); } } @-o-keyframes fadeOutDown { 0% { opacity: 1; -o-transform: translateY(0); } 100% { opacity: 0; -o-transform: translateY(20px); } } @keyframes fadeOutDown { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(20px); } } .fadeOutDown { -webkit-animation-name: fadeOutDown; -moz-animation-name: fadeOutDown; -o-animation-name: fadeOutDown; animation-name: fadeOutDown; } @-webkit-keyframes fadeOutLeft { 0% { opacity: 1; -webkit-transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-20px); } } @-moz-keyframes fadeOutLeft { 0% { opacity: 1; -moz-transform: translateX(0); } 100% { opacity: 0; -moz-transform: translateX(-20px); } } @-o-keyframes fadeOutLeft { 0% { opacity: 1; -o-transform: translateX(0); } 100% { opacity: 0; -o-transform: translateX(-20px); } } @keyframes fadeOutLeft { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(-20px); } } .fadeOutLeft { -webkit-animation-name: fadeOutLeft; -moz-animation-name: fadeOutLeft; -o-animation-name: fadeOutLeft; animation-name: fadeOutLeft; } @-webkit-keyframes fadeOutRight { 0% { opacity: 1; -webkit-transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(20px); } } @-moz-keyframes fadeOutRight { 0% { opacity: 1; -moz-transform: translateX(0); } 100% { opacity: 0; -moz-transform: translateX(20px); } } @-o-keyframes fadeOutRight { 0% { opacity: 1; -o-transform: translateX(0); } 100% { opacity: 0; -o-transform: translateX(20px); } } @keyframes fadeOutRight { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(20px); } } .fadeOutRight { -webkit-animation-name: fadeOutRight; -moz-animation-name: fadeOutRight; -o-animation-name: fadeOutRight; animation-name: fadeOutRight; } @-webkit-keyframes fadeOutUpBig { 0% { opacity: 1; -webkit-transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); } } @-moz-keyframes fadeOutUpBig { 0% { opacity: 1; -moz-transform: translateY(0); } 100% { opacity: 0; -moz-transform: translateY(-2000px); } } @-o-keyframes fadeOutUpBig { 0% { opacity: 1; -o-transform: translateY(0); } 100% { opacity: 0; -o-transform: translateY(-2000px); } } @keyframes fadeOutUpBig { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-2000px); } } .fadeOutUpBig { -webkit-animation-name: fadeOutUpBig; -moz-animation-name: fadeOutUpBig; -o-animation-name: fadeOutUpBig; animation-name: fadeOutUpBig; } @-webkit-keyframes fadeOutDownBig { 0% { opacity: 1; -webkit-transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(2000px); } } @-moz-keyframes fadeOutDownBig { 0% { opacity: 1; -moz-transform: translateY(0); } 100% { opacity: 0; -moz-transform: translateY(2000px); } } @-o-keyframes fadeOutDownBig { 0% { opacity: 1; -o-transform: translateY(0); } 100% { opacity: 0; -o-transform: translateY(2000px); } } @keyframes fadeOutDownBig { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(2000px); } } .fadeOutDownBig { -webkit-animation-name: fadeOutDownBig; -moz-animation-name: fadeOutDownBig; -o-animation-name: fadeOutDownBig; animation-name: fadeOutDownBig; } @-webkit-keyframes fadeOutLeftBig { 0% { opacity: 1; -webkit-transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); } } @-moz-keyframes fadeOutLeftBig { 0% { opacity: 1; -moz-transform: translateX(0); } 100% { opacity: 0; -moz-transform: translateX(-2000px); } } @-o-keyframes fadeOutLeftBig { 0% { opacity: 1; -o-transform: translateX(0); } 100% { opacity: 0; -o-transform: translateX(-2000px); } } @keyframes fadeOutLeftBig { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(-2000px); } } .fadeOutLeftBig { -webkit-animation-name: fadeOutLeftBig; -moz-animation-name: fadeOutLeftBig; -o-animation-name: fadeOutLeftBig; animation-name: fadeOutLeftBig; } @-webkit-keyframes fadeOutRightBig { 0% { opacity: 1; -webkit-transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(2000px); } } @-moz-keyframes fadeOutRightBig { 0% { opacity: 1; -moz-transform: translateX(0); } 100% { opacity: 0; -moz-transform: translateX(2000px); } } @-o-keyframes fadeOutRightBig { 0% { opacity: 1; -o-transform: translateX(0); } 100% { opacity: 0; -o-transform: translateX(2000px); } } @keyframes fadeOutRightBig { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(2000px); } } .fadeOutRightBig { -webkit-animation-name: fadeOutRightBig; -moz-animation-name: fadeOutRightBig; -o-animation-name: fadeOutRightBig; animation-name: fadeOutRightBig; } @-webkit-keyframes bounceIn { 0% { opacity: 0; -webkit-transform: scale(.3); } 50% { opacity: 1; -webkit-transform: scale(1.05); } 70% { -webkit-transform: scale(.9); } 100% { -webkit-transform: scale(1); } } @-moz-keyframes bounceIn { 0% { opacity: 0; -moz-transform: scale(.3); } 50% { opacity: 1; -moz-transform: scale(1.05); } 70% { -moz-transform: scale(.9); } 100% { -moz-transform: scale(1); } } @-o-keyframes bounceIn { 0% { opacity: 0; -o-transform: scale(.3); } 50% { opacity: 1; -o-transform: scale(1.05); } 70% { -o-transform: scale(.9); } 100% { -o-transform: scale(1); } } @keyframes bounceIn { 0% { opacity: 0; transform: scale(.3); } 50% { opacity: 1; transform: scale(1.05); } 70% { transform: scale(.9); } 100% { transform: scale(1); } } .bounceIn { -webkit-animation-name: bounceIn; -moz-animation-name: bounceIn; -o-animation-name: bounceIn; animation-name: bounceIn; } @-webkit-keyframes bounceInUp { 0% { opacity: 0; -webkit-transform: translateY(2000px); } 60% { opacity: 1; -webkit-transform: translateY(-30px); } 80% { -webkit-transform: translateY(10px); } 100% { -webkit-transform: translateY(0); } } @-moz-keyframes bounceInUp { 0% { opacity: 0; -moz-transform: translateY(2000px); } 60% { opacity: 1; -moz-transform: translateY(-30px); } 80% { -moz-transform: translateY(10px); } 100% { -moz-transform: translateY(0); } } @-o-keyframes bounceInUp { 0% { opacity: 0; -o-transform: translateY(2000px); } 60% { opacity: 1; -o-transform: translateY(-30px); } 80% { -o-transform: translateY(10px); } 100% { -o-transform: translateY(0); } } @keyframes bounceInUp { 0% { opacity: 0; transform: translateY(2000px); } 60% { opacity: 1; transform: translateY(-30px); } 80% { transform: translateY(10px); } 100% { transform: translateY(0); } } .bounceInUp { -webkit-animation-name: bounceInUp; -moz-animation-name: bounceInUp; -o-animation-name: bounceInUp; animation-name: bounceInUp; } @-webkit-keyframes bounceInDown { 0% { opacity: 0; -webkit-transform: translateY(-2000px); } 60% { opacity: 1; -webkit-transform: translateY(30px); } 80% { -webkit-transform: translateY(-10px); } 100% { -webkit-transform: translateY(0); } } @-moz-keyframes bounceInDown { 0% { opacity: 0; -moz-transform: translateY(-2000px); } 60% { opacity: 1; -moz-transform: translateY(30px); } 80% { -moz-transform: translateY(-10px); } 100% { -moz-transform: translateY(0); } } @-o-keyframes bounceInDown { 0% { opacity: 0; -o-transform: translateY(-2000px); } 60% { opacity: 1; -o-transform: translateY(30px); } 80% { -o-transform: translateY(-10px); } 100% { -o-transform: translateY(0); } } @keyframes bounceInDown { 0% { opacity: 0; transform: translateY(-2000px); } 60% { opacity: 1; transform: translateY(30px); } 80% { transform: translateY(-10px); } 100% { transform: translateY(0); } } .bounceInDown { -webkit-animation-name: bounceInDown; -moz-animation-name: bounceInDown; -o-animation-name: bounceInDown; animation-name: bounceInDown; } @-webkit-keyframes bounceInLeft { 0% { opacity: 0; -webkit-transform: translateX(-2000px); } 60% { opacity: 1; -webkit-transform: translateX(30px); } 80% { -webkit-transform: translateX(-10px); } 100% { -webkit-transform: translateX(0); } } @-moz-keyframes bounceInLeft { 0% { opacity: 0; -moz-transform: translateX(-2000px); } 60% { opacity: 1; -moz-transform: translateX(30px); } 80% { -moz-transform: translateX(-10px); } 100% { -moz-transform: translateX(0); } } @-o-keyframes bounceInLeft { 0% { opacity: 0; -o-transform: translateX(-2000px); } 60% { opacity: 1; -o-transform: translateX(30px); } 80% { -o-transform: translateX(-10px); } 100% { -o-transform: translateX(0); } } @keyframes bounceInLeft { 0% { opacity: 0; transform: translateX(-2000px); } 60% { opacity: 1; transform: translateX(30px); } 80% { transform: translateX(-10px); } 100% { transform: translateX(0); } } .bounceInLeft { -webkit-animation-name: bounceInLeft; -moz-animation-name: bounceInLeft; -o-animation-name: bounceInLeft; animation-name: bounceInLeft; } @-webkit-keyframes bounceInRight { 0% { opacity: 0; -webkit-transform: translateX(2000px); } 60% { opacity: 1; -webkit-transform: translateX(-30px); } 80% { -webkit-transform: translateX(10px); } 100% { -webkit-transform: translateX(0); } } @-moz-keyframes bounceInRight { 0% { opacity: 0; -moz-transform: translateX(2000px); } 60% { opacity: 1; -moz-transform: translateX(-30px); } 80% { -moz-transform: translateX(10px); } 100% { -moz-transform: translateX(0); } } @-o-keyframes bounceInRight { 0% { opacity: 0; -o-transform: translateX(2000px); } 60% { opacity: 1; -o-transform: translateX(-30px); } 80% { -o-transform: translateX(10px); } 100% { -o-transform: translateX(0); } } @keyframes bounceInRight { 0% { opacity: 0; transform: translateX(2000px); } 60% { opacity: 1; transform: translateX(-30px); } 80% { transform: translateX(10px); } 100% { transform: translateX(0); } } .bounceInRight { -webkit-animation-name: bounceInRight; -moz-animation-name: bounceInRight; -o-animation-name: bounceInRight; animation-name: bounceInRight; } @-webkit-keyframes bounceOut { 0% { -webkit-transform: scale(1); } 25% { -webkit-transform: scale(.95); } 50% { opacity: 1; -webkit-transform: scale(1.1); } 100% { opacity: 0; -webkit-transform: scale(.3); } } @-moz-keyframes bounceOut { 0% { -moz-transform: scale(1); } 25% { -moz-transform: scale(.95); } 50% { opacity: 1; -moz-transform: scale(1.1); } 100% { opacity: 0; -moz-transform: scale(.3); } } @-o-keyframes bounceOut { 0% { -o-transform: scale(1); } 25% { -o-transform: scale(.95); } 50% { opacity: 1; -o-transform: scale(1.1); } 100% { opacity: 0; -o-transform: scale(.3); } } @keyframes bounceOut { 0% { transform: scale(1); } 25% { transform: scale(.95); } 50% { opacity: 1; transform: scale(1.1); } 100% { opacity: 0; transform: scale(.3); } } .bounceOut { -webkit-animation-name: bounceOut; -moz-animation-name: bounceOut; -o-animation-name: bounceOut; animation-name: bounceOut; } @-webkit-keyframes bounceOutUp { 0% { -webkit-transform: translateY(0); } 20% { opacity: 1; -webkit-transform: translateY(20px); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); } } @-moz-keyframes bounceOutUp { 0% { -moz-transform: translateY(0); } 20% { opacity: 1; -moz-transform: translateY(20px); } 100% { opacity: 0; -moz-transform: translateY(-2000px); } } @-o-keyframes bounceOutUp { 0% { -o-transform: translateY(0); } 20% { opacity: 1; -o-transform: translateY(20px); } 100% { opacity: 0; -o-transform: translateY(-2000px); } } @keyframes bounceOutUp { 0% { transform: translateY(0); } 20% { opacity: 1; transform: translateY(20px); } 100% { opacity: 0; transform: translateY(-2000px); } } .bounceOutUp { -webkit-animation-name: bounceOutUp; -moz-animation-name: bounceOutUp; -o-animation-name: bounceOutUp; animation-name: bounceOutUp; } @-webkit-keyframes bounceOutDown { 0% { -webkit-transform: translateY(0); } 20% { opacity: 1; -webkit-transform: translateY(-20px); } 100% { opacity: 0; -webkit-transform: translateY(2000px); } } @-moz-keyframes bounceOutDown { 0% { -moz-transform: translateY(0); } 20% { opacity: 1; -moz-transform: translateY(-20px); } 100% { opacity: 0; -moz-transform: translateY(2000px); } } @-o-keyframes bounceOutDown { 0% { -o-transform: translateY(0); } 20% { opacity: 1; -o-transform: translateY(-20px); } 100% { opacity: 0; -o-transform: translateY(2000px); } } @keyframes bounceOutDown { 0% { transform: translateY(0); } 20% { opacity: 1; transform: translateY(-20px); } 100% { opacity: 0; transform: translateY(2000px); } } .bounceOutDown { -webkit-animation-name: bounceOutDown; -moz-animation-name: bounceOutDown; -o-animation-name: bounceOutDown; animation-name: bounceOutDown; } @-webkit-keyframes bounceOutLeft { 0% { -webkit-transform: translateX(0); } 20% { opacity: 1; -webkit-transform: translateX(20px); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); } } @-moz-keyframes bounceOutLeft { 0% { -moz-transform: translateX(0); } 20% { opacity: 1; -moz-transform: translateX(20px); } 100% { opacity: 0; -moz-transform: translateX(-2000px); } } @-o-keyframes bounceOutLeft { 0% { -o-transform: translateX(0); } 20% { opacity: 1; -o-transform: translateX(20px); } 100% { opacity: 0; -o-transform: translateX(-2000px); } } @keyframes bounceOutLeft { 0% { transform: translateX(0); } 20% { opacity: 1; transform: translateX(20px); } 100% { opacity: 0; transform: translateX(-2000px); } } .bounceOutLeft { -webkit-animation-name: bounceOutLeft; -moz-animation-name: bounceOutLeft; -o-animation-name: bounceOutLeft; animation-name: bounceOutLeft; } @-webkit-keyframes bounceOutRight { 0% { -webkit-transform: translateX(0); } 20% { opacity: 1; -webkit-transform: translateX(-20px); } 100% { opacity: 0; -webkit-transform: translateX(2000px); } } @-moz-keyframes bounceOutRight { 0% { -moz-transform: translateX(0); } 20% { opacity: 1; -moz-transform: translateX(-20px); } 100% { opacity: 0; -moz-transform: translateX(2000px); } } @-o-keyframes bounceOutRight { 0% { -o-transform: translateX(0); } 20% { opacity: 1; -o-transform: translateX(-20px); } 100% { opacity: 0; -o-transform: translateX(2000px); } } @keyframes bounceOutRight { 0% { transform: translateX(0); } 20% { opacity: 1; transform: translateX(-20px); } 100% { opacity: 0; transform: translateX(2000px); } } .bounceOutRight { -webkit-animation-name: bounceOutRight; -moz-animation-name: bounceOutRight; -o-animation-name: bounceOutRight; animation-name: bounceOutRight; } @-webkit-keyframes rotateIn { 0% { -webkit-transform-origin: center center; -webkit-transform: rotate(-200deg); opacity: 0; } 100% { -webkit-transform-origin: center center; -webkit-transform: rotate(0); opacity: 1; } } @-moz-keyframes rotateIn { 0% { -moz-transform-origin: center center; -moz-transform: rotate(-200deg); opacity: 0; } 100% { -moz-transform-origin: center center; -moz-transform: rotate(0); opacity: 1; } } @-o-keyframes rotateIn { 0% { -o-transform-origin: center center; -o-transform: rotate(-200deg); opacity: 0; } 100% { -o-transform-origin: center center; -o-transform: rotate(0); opacity: 1; } } @keyframes rotateIn { 0% { transform-origin: center center; transform: rotate(-200deg); opacity: 0; } 100% { transform-origin: center center; transform: rotate(0); opacity: 1; } } .rotateIn { -webkit-animation-name: rotateIn; -moz-animation-name: rotateIn; -o-animation-name: rotateIn; animation-name: rotateIn; } @-webkit-keyframes rotateInUpLeft { 0% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(90deg); opacity: 0; } 100% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(0); opacity: 1; } } @-moz-keyframes rotateInUpLeft { 0% { -moz-transform-origin: left bottom; -moz-transform: rotate(90deg); opacity: 0; } 100% { -moz-transform-origin: left bottom; -moz-transform: rotate(0); opacity: 1; } } @-o-keyframes rotateInUpLeft { 0% { -o-transform-origin: left bottom; -o-transform: rotate(90deg); opacity: 0; } 100% { -o-transform-origin: left bottom; -o-transform: rotate(0); opacity: 1; } } @keyframes rotateInUpLeft { 0% { transform-origin: left bottom; transform: rotate(90deg); opacity: 0; } 100% { transform-origin: left bottom; transform: rotate(0); opacity: 1; } } .rotateInUpLeft { -webkit-animation-name: rotateInUpLeft; -moz-animation-name: rotateInUpLeft; -o-animation-name: rotateInUpLeft; animation-name: rotateInUpLeft; } @-webkit-keyframes rotateInDownLeft { 0% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(-90deg); opacity: 0; } 100% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(0); opacity: 1; } } @-moz-keyframes rotateInDownLeft { 0% { -moz-transform-origin: left bottom; -moz-transform: rotate(-90deg); opacity: 0; } 100% { -moz-transform-origin: left bottom; -moz-transform: rotate(0); opacity: 1; } } @-o-keyframes rotateInDownLeft { 0% { -o-transform-origin: left bottom; -o-transform: rotate(-90deg); opacity: 0; } 100% { -o-transform-origin: left bottom; -o-transform: rotate(0); opacity: 1; } } @keyframes rotateInDownLeft { 0% { transform-origin: left bottom; transform: rotate(-90deg); opacity: 0; } 100% { transform-origin: left bottom; transform: rotate(0); opacity: 1; } } .rotateInDownLeft { -webkit-animation-name: rotateInDownLeft; -moz-animation-name: rotateInDownLeft; -o-animation-name: rotateInDownLeft; animation-name: rotateInDownLeft; } @-webkit-keyframes rotateInUpRight { 0% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(-90deg); opacity: 0; } 100% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(0); opacity: 1; } } @-moz-keyframes rotateInUpRight { 0% { -moz-transform-origin: right bottom; -moz-transform: rotate(-90deg); opacity: 0; } 100% { -moz-transform-origin: right bottom; -moz-transform: rotate(0); opacity: 1; } } @-o-keyframes rotateInUpRight { 0% { -o-transform-origin: right bottom; -o-transform: rotate(-90deg); opacity: 0; } 100% { -o-transform-origin: right bottom; -o-transform: rotate(0); opacity: 1; } } @keyframes rotateInUpRight { 0% { transform-origin: right bottom; transform: rotate(-90deg); opacity: 0; } 100% { transform-origin: right bottom; transform: rotate(0); opacity: 1; } } .rotateInUpRight { -webkit-animation-name: rotateInUpRight; -moz-animation-name: rotateInUpRight; -o-animation-name: rotateInUpRight; animation-name: rotateInUpRight; } @-webkit-keyframes rotateInDownRight { 0% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(90deg); opacity: 0; } 100% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(0); opacity: 1; } } @-moz-keyframes rotateInDownRight { 0% { -moz-transform-origin: right bottom; -moz-transform: rotate(90deg); opacity: 0; } 100% { -moz-transform-origin: right bottom; -moz-transform: rotate(0); opacity: 1; } } @-o-keyframes rotateInDownRight { 0% { -o-transform-origin: right bottom; -o-transform: rotate(90deg); opacity: 0; } 100% { -o-transform-origin: right bottom; -o-transform: rotate(0); opacity: 1; } } @keyframes rotateInDownRight { 0% { transform-origin: right bottom; transform: rotate(90deg); opacity: 0; } 100% { transform-origin: right bottom; transform: rotate(0); opacity: 1; } } .rotateInDownRight { -webkit-animation-name: rotateInDownRight; -moz-animation-name: rotateInDownRight; -o-animation-name: rotateInDownRight; animation-name: rotateInDownRight; } @-webkit-keyframes rotateOut { 0% { -webkit-transform-origin: center center; -webkit-transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: center center; -webkit-transform: rotate(200deg); opacity: 0; } } @-moz-keyframes rotateOut { 0% { -moz-transform-origin: center center; -moz-transform: rotate(0); opacity: 1; } 100% { -moz-transform-origin: center center; -moz-transform: rotate(200deg); opacity: 0; } } @-o-keyframes rotateOut { 0% { -o-transform-origin: center center; -o-transform: rotate(0); opacity: 1; } 100% { -o-transform-origin: center center; -o-transform: rotate(200deg); opacity: 0; } } @keyframes rotateOut { 0% { transform-origin: center center; transform: rotate(0); opacity: 1; } 100% { transform-origin: center center; transform: rotate(200deg); opacity: 0; } } .rotateOut { -webkit-animation-name: rotateOut; -moz-animation-name: rotateOut; -o-animation-name: rotateOut; animation-name: rotateOut; } @-webkit-keyframes rotateOutUpLeft { 0% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(-90deg); opacity: 0; } } @-moz-keyframes rotateOutUpLeft { 0% { -moz-transform-origin: left bottom; -moz-transform: rotate(0); opacity: 1; } 100% { -moz-transform-origin: left bottom; -moz-transform: rotate(-90deg); opacity: 0; } } @-o-keyframes rotateOutUpLeft { 0% { -o-transform-origin: left bottom; -o-transform: rotate(0); opacity: 1; } 100% { -o-transform-origin: left bottom; -o-transform: rotate(-90deg); opacity: 0; } } @keyframes rotateOutUpLeft { 0% { transform-origin: left bottom; transform: rotate(0); opacity: 1; } 100% { transform-origin: left bottom; transform: rotate(-90deg); opacity: 0; } } .rotateOutUpLeft { -webkit-animation-name: rotateOutUpLeft; -moz-animation-name: rotateOutUpLeft; -o-animation-name: rotateOutUpLeft; animation-name: rotateOutUpLeft; } @-webkit-keyframes rotateOutDownLeft { 0% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: left bottom; -webkit-transform: rotate(90deg); opacity: 0; } } @-moz-keyframes rotateOutDownLeft { 0% { -moz-transform-origin: left bottom; -moz-transform: rotate(0); opacity: 1; } 100% { -moz-transform-origin: left bottom; -moz-transform: rotate(90deg); opacity: 0; } } @-o-keyframes rotateOutDownLeft { 0% { -o-transform-origin: left bottom; -o-transform: rotate(0); opacity: 1; } 100% { -o-transform-origin: left bottom; -o-transform: rotate(90deg); opacity: 0; } } @keyframes rotateOutDownLeft { 0% { transform-origin: left bottom; transform: rotate(0); opacity: 1; } 100% { transform-origin: left bottom; transform: rotate(90deg); opacity: 0; } } .rotateOutDownLeft { -webkit-animation-name: rotateOutDownLeft; -moz-animation-name: rotateOutDownLeft; -o-animation-name: rotateOutDownLeft; animation-name: rotateOutDownLeft; } @-webkit-keyframes rotateOutUpRight { 0% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(90deg); opacity: 0; } } @-moz-keyframes rotateOutUpRight { 0% { -moz-transform-origin: right bottom; -moz-transform: rotate(0); opacity: 1; } 100% { -moz-transform-origin: right bottom; -moz-transform: rotate(90deg); opacity: 0; } } @-o-keyframes rotateOutUpRight { 0% { -o-transform-origin: right bottom; -o-transform: rotate(0); opacity: 1; } 100% { -o-transform-origin: right bottom; -o-transform: rotate(90deg); opacity: 0; } } @keyframes rotateOutUpRight { 0% { transform-origin: right bottom; transform: rotate(0); opacity: 1; } 100% { transform-origin: right bottom; transform: rotate(90deg); opacity: 0; } } .rotateOutUpRight { -webkit-animation-name: rotateOutUpRight; -moz-animation-name: rotateOutUpRight; -o-animation-name: rotateOutUpRight; animation-name: rotateOutUpRight; } @-webkit-keyframes rotateOutDownRight { 0% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: right bottom; -webkit-transform: rotate(-90deg); opacity: 0; } } @-moz-keyframes rotateOutDownRight { 0% { -moz-transform-origin: right bottom; -moz-transform: rotate(0); opacity: 1; } 100% { -moz-transform-origin: right bottom; -moz-transform: rotate(-90deg); opacity: 0; } } @-o-keyframes rotateOutDownRight { 0% { -o-transform-origin: right bottom; -o-transform: rotate(0); opacity: 1; } 100% { -o-transform-origin: right bottom; -o-transform: rotate(-90deg); opacity: 0; } } @keyframes rotateOutDownRight { 0% { transform-origin: right bottom; transform: rotate(0); opacity: 1; } 100% { transform-origin: right bottom; transform: rotate(-90deg); opacity: 0; } } .rotateOutDownRight { -webkit-animation-name: rotateOutDownRight; -moz-animation-name: rotateOutDownRight; -o-animation-name: rotateOutDownRight; animation-name: rotateOutDownRight; } @-webkit-keyframes hinge { 0% { -webkit-transform: rotate(0); -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; } 20%, 60% { -webkit-transform: rotate(80deg); -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; } 40% { -webkit-transform: rotate(60deg); -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; } 80% { -webkit-transform: rotate(60deg) translateY(0); opacity: 1; -webkit-transform-origin: top left; -webkit-animation-timing-function: ease-in-out; } 100% { -webkit-transform: translateY(700px); opacity: 0; } } @-moz-keyframes hinge { 0% { -moz-transform: rotate(0); -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; } 20%, 60% { -moz-transform: rotate(80deg); -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; } 40% { -moz-transform: rotate(60deg); -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; } 80% { -moz-transform: rotate(60deg) translateY(0); opacity: 1; -moz-transform-origin: top left; -moz-animation-timing-function: ease-in-out; } 100% { -moz-transform: translateY(700px); opacity: 0; } } @-o-keyframes hinge { 0% { -o-transform: rotate(0); -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; } 20%, 60% { -o-transform: rotate(80deg); -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; } 40% { -o-transform: rotate(60deg); -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; } 80% { -o-transform: rotate(60deg) translateY(0); opacity: 1; -o-transform-origin: top left; -o-animation-timing-function: ease-in-out; } 100% { -o-transform: translateY(700px); opacity: 0; } } @keyframes hinge { 0% { transform: rotate(0); transform-origin: top left; animation-timing-function: ease-in-out; } 20%, 60% { transform: rotate(80deg); transform-origin: top left; animation-timing-function: ease-in-out; } 40% { transform: rotate(60deg); transform-origin: top left; animation-timing-function: ease-in-out; } 80% { transform: rotate(60deg) translateY(0); opacity: 1; transform-origin: top left; animation-timing-function: ease-in-out; } 100% { transform: translateY(700px); opacity: 0; } } .hinge { -webkit-animation-name: hinge; -moz-animation-name: hinge; -o-animation-name: hinge; animation-name: hinge; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes rollIn { 0% { opacity: 0; -webkit-transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); } } @-moz-keyframes rollIn { 0% { opacity: 0; -moz-transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; -moz-transform: translateX(0px) rotate(0deg); } } @-o-keyframes rollIn { 0% { opacity: 0; -o-transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; -o-transform: translateX(0px) rotate(0deg); } } @keyframes rollIn { 0% { opacity: 0; transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; transform: translateX(0px) rotate(0deg); } } .rollIn { -webkit-animation-name: rollIn; -moz-animation-name: rollIn; -o-animation-name: rollIn; animation-name: rollIn; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes rollOut { 0% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; -webkit-transform: translateX(100%) rotate(120deg); } } @-moz-keyframes rollOut { 0% { opacity: 1; -moz-transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; -moz-transform: translateX(100%) rotate(120deg); } } @-o-keyframes rollOut { 0% { opacity: 1; -o-transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; -o-transform: translateX(100%) rotate(120deg); } } @keyframes rollOut { 0% { opacity: 1; transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; transform: translateX(100%) rotate(120deg); } } .rollOut { -webkit-animation-name: rollOut; -moz-animation-name: rollOut; -o-animation-name: rollOut; animation-name: rollOut; } /* originally authored by Angelo Rohit - https://github.com/angelorohit */ @-webkit-keyframes lightSpeedIn { 0% { -webkit-transform: translateX(100%) skewX(-30deg); opacity: 0; } 60% { -webkit-transform: translateX(-20%) skewX(30deg); opacity: 1; } 80% { -webkit-transform: translateX(0%) skewX(-15deg); opacity: 1; } 100% { -webkit-transform: translateX(0%) skewX(0deg); opacity: 1; } } @-moz-keyframes lightSpeedIn { 0% { -moz-transform: translateX(100%) skewX(-30deg); opacity: 0; } 60% { -moz-transform: translateX(-20%) skewX(30deg); opacity: 1; } 80% { -moz-transform: translateX(0%) skewX(-15deg); opacity: 1; } 100% { -moz-transform: translateX(0%) skewX(0deg); opacity: 1; } } @-o-keyframes lightSpeedIn { 0% { -o-transform: translateX(100%) skewX(-30deg); opacity: 0; } 60% { -o-transform: translateX(-20%) skewX(30deg); opacity: 1; } 80% { -o-transform: translateX(0%) skewX(-15deg); opacity: 1; } 100% { -o-transform: translateX(0%) skewX(0deg); opacity: 1; } } @keyframes lightSpeedIn { 0% { transform: translateX(100%) skewX(-30deg); opacity: 0; } 60% { transform: translateX(-20%) skewX(30deg); opacity: 1; } 80% { transform: translateX(0%) skewX(-15deg); opacity: 1; } 100% { transform: translateX(0%) skewX(0deg); opacity: 1; } } .lightSpeedIn { -webkit-animation-name: lightSpeedIn; -moz-animation-name: lightSpeedIn; -o-animation-name: lightSpeedIn; animation-name: lightSpeedIn; -webkit-animation-timing-function: ease-out; -moz-animation-timing-function: ease-out; -o-animation-timing-function: ease-out; animation-timing-function: ease-out; } .animated.lightSpeedIn { -webkit-animation-duration: 0.5s; -moz-animation-duration: 0.5s; -o-animation-duration: 0.5s; animation-duration: 0.5s; } /* originally authored by Angelo Rohit - https://github.com/angelorohit */ @-webkit-keyframes lightSpeedOut { 0% { -webkit-transform: translateX(0%) skewX(0deg); opacity: 1; } 100% { -webkit-transform: translateX(100%) skewX(-30deg); opacity: 0; } } @-moz-keyframes lightSpeedOut { 0% { -moz-transform: translateX(0%) skewX(0deg); opacity: 1; } 100% { -moz-transform: translateX(100%) skewX(-30deg); opacity: 0; } } @-o-keyframes lightSpeedOut { 0% { -o-transform: translateX(0%) skewX(0deg); opacity: 1; } 100% { -o-transform: translateX(100%) skewX(-30deg); opacity: 0; } } @keyframes lightSpeedOut { 0% { transform: translateX(0%) skewX(0deg); opacity: 1; } 100% { transform: translateX(100%) skewX(-30deg); opacity: 0; } } .lightSpeedOut { -webkit-animation-name: lightSpeedOut; -moz-animation-name: lightSpeedOut; -o-animation-name: lightSpeedOut; animation-name: lightSpeedOut; -webkit-animation-timing-function: ease-in; -moz-animation-timing-function: ease-in; -o-animation-timing-function: ease-in; animation-timing-function: ease-in; } .animated.lightSpeedOut { -webkit-animation-duration: 0.25s; -moz-animation-duration: 0.25s; -o-animation-duration: 0.25s; animation-duration: 0.25s; } /* originally authored by Angelo Rohit - https://github.com/angelorohit */ @-webkit-keyframes wiggle { 0% { -webkit-transform: skewX(9deg); } 10% { -webkit-transform: skewX(-8deg); } 20% { -webkit-transform: skewX(7deg); } 30% { -webkit-transform: skewX(-6deg); } 40% { -webkit-transform: skewX(5deg); } 50% { -webkit-transform: skewX(-4deg); } 60% { -webkit-transform: skewX(3deg); } 70% { -webkit-transform: skewX(-2deg); } 80% { -webkit-transform: skewX(1deg); } 90% { -webkit-transform: skewX(0deg); } 100% { -webkit-transform: skewX(0deg); } } @-moz-keyframes wiggle { 0% { -moz-transform: skewX(9deg); } 10% { -moz-transform: skewX(-8deg); } 20% { -moz-transform: skewX(7deg); } 30% { -moz-transform: skewX(-6deg); } 40% { -moz-transform: skewX(5deg); } 50% { -moz-transform: skewX(-4deg); } 60% { -moz-transform: skewX(3deg); } 70% { -moz-transform: skewX(-2deg); } 80% { -moz-transform: skewX(1deg); } 90% { -moz-transform: skewX(0deg); } 100% { -moz-transform: skewX(0deg); } } @-o-keyframes wiggle { 0% { -o-transform: skewX(9deg); } 10% { -o-transform: skewX(-8deg); } 20% { -o-transform: skewX(7deg); } 30% { -o-transform: skewX(-6deg); } 40% { -o-transform: skewX(5deg); } 50% { -o-transform: skewX(-4deg); } 60% { -o-transform: skewX(3deg); } 70% { -o-transform: skewX(-2deg); } 80% { -o-transform: skewX(1deg); } 90% { -o-transform: skewX(0deg); } 100% { -o-transform: skewX(0deg); } } @keyframes wiggle { 0% { transform: skewX(9deg); } 10% { transform: skewX(-8deg); } 20% { transform: skewX(7deg); } 30% { transform: skewX(-6deg); } 40% { transform: skewX(5deg); } 50% { transform: skewX(-4deg); } 60% { transform: skewX(3deg); } 70% { transform: skewX(-2deg); } 80% { transform: skewX(1deg); } 90% { transform: skewX(0deg); } 100% { transform: skewX(0deg); } } .wiggle { -webkit-animation-name: wiggle; -moz-animation-name: wiggle; -o-animation-name: wiggle; animation-name: wiggle; -webkit-animation-timing-function: ease-in; -moz-animation-timing-function: ease-in; -o-animation-timing-function: ease-in; animation-timing-function: ease-in; } .animated.wiggle { -webkit-animation-duration: 0.75s; -moz-animation-duration: 0.75s; -o-animation-duration: 0.75s; animation-duration: 0.75s; }
Java
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $app_list_strings['moduleList']['CON_Contratos'] = 'Contratos'; $app_list_strings['con_contratos_type_dom']['Administration'] = 'Administration'; $app_list_strings['con_contratos_type_dom']['Product'] = 'Product'; $app_list_strings['con_contratos_type_dom']['User'] = 'User'; $app_list_strings['con_contratos_status_dom']['New'] = 'New'; $app_list_strings['con_contratos_status_dom']['Assigned'] = 'Assigned'; $app_list_strings['con_contratos_status_dom']['Closed'] = 'Closed'; $app_list_strings['con_contratos_status_dom']['Pending Input'] = 'Pending Input'; $app_list_strings['con_contratos_status_dom']['Rejected'] = 'Rejected'; $app_list_strings['con_contratos_status_dom']['Duplicate'] = 'Duplicate'; $app_list_strings['con_contratos_priority_dom']['P1'] = 'High'; $app_list_strings['con_contratos_priority_dom']['P2'] = 'Medium'; $app_list_strings['con_contratos_priority_dom']['P3'] = 'Low'; $app_list_strings['con_contratos_resolution_dom'][''] = ''; $app_list_strings['con_contratos_resolution_dom']['Accepted'] = 'Accepted'; $app_list_strings['con_contratos_resolution_dom']['Duplicate'] = 'Duplicate'; $app_list_strings['con_contratos_resolution_dom']['Closed'] = 'Closed'; $app_list_strings['con_contratos_resolution_dom']['Out of Date'] = 'Out of Date'; $app_list_strings['con_contratos_resolution_dom']['Invalid'] = 'Invalid'; $app_list_strings['accion_list']['Alta'] = 'Alta'; $app_list_strings['accion_list']['Baja'] = 'Baja'; $app_list_strings['accion_list']['Modificacion'] = 'Modificacion'; $app_list_strings['tipo_contrato_list']['Indefinido'] = 'Indefinido'; $app_list_strings['tipo_contrato_list']['Temporal'] = 'Temporal'; $app_list_strings['tipo_contrato_list']['Obra'] = 'Obra'; $app_list_strings['tipo_contrato_list'][''] = ''; $app_list_strings['categoria_list']['Profesor'] = 'Profesor'; $app_list_strings['categoria_list']['Administrativo'] = 'Administrativo'; $app_list_strings['categoria_list'][''] = ''; $app_list_strings['_type_dom']['Administration'] = 'Administración'; $app_list_strings['_type_dom']['Product'] = 'Producto'; $app_list_strings['_type_dom']['User'] = 'Usuario'; $app_list_strings['_status_dom']['New'] = 'Nuevo'; $app_list_strings['_status_dom']['Assigned'] = 'Asignado'; $app_list_strings['_status_dom']['Closed'] = 'Cerrado'; $app_list_strings['_status_dom']['Pending Input'] = 'Pendiente de Información'; $app_list_strings['_status_dom']['Rejected'] = 'Rechazado'; $app_list_strings['_status_dom']['Duplicate'] = 'Duplicado'; $app_list_strings['_priority_dom']['P1'] = 'Alta'; $app_list_strings['_priority_dom']['P2'] = 'Media'; $app_list_strings['_priority_dom']['P3'] = 'Baja'; $app_list_strings['_resolution_dom'][''] = ''; $app_list_strings['_resolution_dom']['Accepted'] = 'Aceptado'; $app_list_strings['_resolution_dom']['Duplicate'] = 'Duplicado'; $app_list_strings['_resolution_dom']['Closed'] = 'Cerrado'; $app_list_strings['_resolution_dom']['Out of Date'] = 'Caducado'; $app_list_strings['_resolution_dom']['Invalid'] = 'No Válido';
Java
// // Copyright (C) 2016 - present Instructure, Inc. // // This file is part of Canvas. // // Canvas is free software: you can redistribute it and/or modify it under // the terms of the GNU Affero General Public License as published by the Free // Software Foundation, version 3 of the License. // // Canvas 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 Affero General Public License for more // details. // // You should have received a copy of the GNU Affero General Public License along // with this program. If not, see <http://www.gnu.org/licenses/>. import _ from 'underscore' import Depaginate from 'jsx/shared/CheatDepaginator' const listUrl = () => ENV.ENROLLMENT_TERMS_URL const deserializeTerms = termGroups => _.flatten( _.map(termGroups, group => _.map(group.enrollment_terms, (term) => { const groupID = term.grading_period_group_id const newGroupID = _.isNumber(groupID) ? groupID.toString() : groupID return { id: term.id.toString(), name: term.name, startAt: term.start_at ? new Date(term.start_at) : null, endAt: term.end_at ? new Date(term.end_at) : null, createdAt: term.created_at ? new Date(term.created_at) : null, gradingPeriodGroupId: newGroupID, } }) ) ) export default { list (terms) { return new Promise((resolve, reject) => { Depaginate(listUrl()) .then(response => resolve(deserializeTerms(response))) .fail(error => reject(error)) }) } }
Java
/*====================================================== ************ Pull To Refresh ************ ======================================================*/ app.initPullToRefresh = function (pageContainer) { var eventsTarget = $(pageContainer); if (!eventsTarget.hasClass('pull-to-refresh-content')) { eventsTarget = eventsTarget.find('.pull-to-refresh-content'); } if (!eventsTarget || eventsTarget.length === 0) return; var touchId, isTouched, isMoved, touchesStart = {}, isScrolling, touchesDiff, touchStartTime, container, refresh = false, useTranslate = false, startTranslate = 0, translate, scrollTop, wasScrolled, layer, triggerDistance, dynamicTriggerDistance, pullStarted; var page = eventsTarget.hasClass('page') ? eventsTarget : eventsTarget.parents('.page'); var hasNavbar = false; if (page.find('.navbar').length > 0 || page.parents('.navbar-fixed, .navbar-through').length > 0 || page.hasClass('navbar-fixed') || page.hasClass('navbar-through')) hasNavbar = true; if (page.hasClass('no-navbar')) hasNavbar = false; if (!hasNavbar) eventsTarget.addClass('pull-to-refresh-no-navbar'); container = eventsTarget; // Define trigger distance if (container.attr('data-ptr-distance')) { dynamicTriggerDistance = true; } else { triggerDistance = 44; } function handleTouchStart(e) { if (isTouched) { if (app.device.os === 'android') { if ('targetTouches' in e && e.targetTouches.length > 1) return; } else return; } /*jshint validthis:true */ container = $(this); if (container.hasClass('refreshing')) { return; } isMoved = false; pullStarted = false; isTouched = true; isScrolling = undefined; wasScrolled = undefined; if (e.type === 'touchstart') touchId = e.targetTouches[0].identifier; touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX; touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY; touchStartTime = (new Date()).getTime(); } function handleTouchMove(e) { if (!isTouched) return; var pageX, pageY, touch; if (e.type === 'touchmove') { if (touchId && e.touches) { for (var i = 0; i < e.touches.length; i++) { if (e.touches[i].identifier === touchId) { touch = e.touches[i]; } } } if (!touch) touch = e.targetTouches[0]; pageX = touch.pageX; pageY = touch.pageY; } else { pageX = e.pageX; pageY = e.pageY; } if (!pageX || !pageY) return; if (typeof isScrolling === 'undefined') { isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x)); } if (!isScrolling) { isTouched = false; return; } scrollTop = container[0].scrollTop; if (typeof wasScrolled === 'undefined' && scrollTop !== 0) wasScrolled = true; if (!isMoved) { /*jshint validthis:true */ container.removeClass('transitioning'); if (scrollTop > container[0].offsetHeight) { isTouched = false; return; } if (dynamicTriggerDistance) { triggerDistance = container.attr('data-ptr-distance'); if (triggerDistance.indexOf('%') >= 0) triggerDistance = container[0].offsetHeight * parseInt(triggerDistance, 10) / 100; } startTranslate = container.hasClass('refreshing') ? triggerDistance : 0; if (container[0].scrollHeight === container[0].offsetHeight || app.device.os !== 'ios') { useTranslate = true; } else { useTranslate = false; } } isMoved = true; touchesDiff = pageY - touchesStart.y; if (touchesDiff > 0 && scrollTop <= 0 || scrollTop < 0) { // iOS 8 fix if (app.device.os === 'ios' && parseInt(app.device.osVersion.split('.')[0], 10) > 7 && scrollTop === 0 && !wasScrolled) useTranslate = true; if (useTranslate) { e.preventDefault(); translate = (Math.pow(touchesDiff, 0.85) + startTranslate); container.transform('translate3d(0,' + translate + 'px,0)'); } if ((useTranslate && Math.pow(touchesDiff, 0.85) > triggerDistance) || (!useTranslate && touchesDiff >= triggerDistance * 2)) { refresh = true; container.addClass('pull-up').removeClass('pull-down'); } else { refresh = false; container.removeClass('pull-up').addClass('pull-down'); } if (!pullStarted) { container.trigger('pullstart'); pullStarted = true; } container.trigger('pullmove', { event: e, scrollTop: scrollTop, translate: translate, touchesDiff: touchesDiff }); } else { pullStarted = false; container.removeClass('pull-up pull-down'); refresh = false; return; } } function handleTouchEnd(e) { if (e.type === 'touchend' && e.changedTouches && e.changedTouches.length > 0 && touchId) { if (e.changedTouches[0].identifier !== touchId) return; } if (!isTouched || !isMoved) { isTouched = false; isMoved = false; return; } if (translate) { container.addClass('transitioning'); translate = 0; } container.transform(''); if (refresh) { container.addClass('refreshing'); container.trigger('refresh', { done: function () { app.pullToRefreshDone(container); } }); } else { container.removeClass('pull-down'); } isTouched = false; isMoved = false; if (pullStarted) container.trigger('pullend'); } // Attach Events var passiveListener = app.touchEvents.start === 'touchstart' && app.support.passiveListener ? {passive: true, capture: false} : false; eventsTarget.on(app.touchEvents.start, handleTouchStart, passiveListener); eventsTarget.on(app.touchEvents.move, handleTouchMove); eventsTarget.on(app.touchEvents.end, handleTouchEnd, passiveListener); // Detach Events on page remove if (page.length === 0) return; function destroyPullToRefresh() { eventsTarget.off(app.touchEvents.start, handleTouchStart); eventsTarget.off(app.touchEvents.move, handleTouchMove); eventsTarget.off(app.touchEvents.end, handleTouchEnd); } eventsTarget[0].f7DestroyPullToRefresh = destroyPullToRefresh; function detachEvents() { destroyPullToRefresh(); page.off('pageBeforeRemove', detachEvents); } page.on('pageBeforeRemove', detachEvents); }; app.pullToRefreshDone = function (container) { container = $(container); if (container.length === 0) container = $('.pull-to-refresh-content.refreshing'); container.removeClass('refreshing').addClass('transitioning'); container.transitionEnd(function () { container.removeClass('transitioning pull-up pull-down'); container.trigger('refreshdone'); }); }; app.pullToRefreshTrigger = function (container) { container = $(container); if (container.length === 0) container = $('.pull-to-refresh-content'); if (container.hasClass('refreshing')) return; container.addClass('transitioning refreshing'); container.trigger('refresh', { done: function () { app.pullToRefreshDone(container); } }); }; app.destroyPullToRefresh = function (pageContainer) { pageContainer = $(pageContainer); var pullToRefreshContent = pageContainer.hasClass('pull-to-refresh-content') ? pageContainer : pageContainer.find('.pull-to-refresh-content'); if (pullToRefreshContent.length === 0) return; if (pullToRefreshContent[0].f7DestroyPullToRefresh) pullToRefreshContent[0].f7DestroyPullToRefresh(); };
Java
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.vaadin.web.ui; import com.vaadin.ui.CheckBox; import com.vaadin.ui.themes.ValoTheme; /** * @author MyCollab Ltd. * @since 3.0 */ public class CheckBoxDecor extends CheckBox { private static final long serialVersionUID = 1L; public CheckBoxDecor(String title, boolean value) { super(title, value); this.addStyleName(ValoTheme.CHECKBOX_SMALL); } }
Java
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2016-2016 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.poller.remote.metadata; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.opennms.netmgt.poller.remote.metadata.MetadataField.Validator; public class EmailValidatorTest { private Validator m_validator; @Before public void setUp() { m_validator = new EmailValidator(); } @Test public void testValid() { assertTrue(m_validator.isValid("[email protected]")); assertTrue(m_validator.isValid("[email protected]")); assertTrue(m_validator.isValid("[email protected]")); } @Test public void testInvalid() { assertFalse(m_validator.isValid("ranger@opennms")); assertFalse(m_validator.isValid("ranger.monkey.esophagus")); assertFalse(m_validator.isValid("ranger@")); assertFalse(m_validator.isValid("@foo.com")); assertFalse(m_validator.isValid("@foo.com.")); assertFalse(m_validator.isValid("@foo.com")); assertFalse(m_validator.isValid("[email protected]")); assertFalse(m_validator.isValid("[email protected]")); } }
Java
/* * ProActive Parallel Suite(TM): * The Open Source library for parallel and distributed * Workflows & Scheduling, Orchestration, Cloud Automation * and Big Data Analysis on Enterprise Grids & Clouds. * * Copyright (c) 2007 - 2017 ActiveEon * Contact: [email protected] * * This library is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation: version 3 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. */ package org.objectweb.proactive.core.jmx.mbean; import java.io.Serializable; /** * This interface is used to add a class loader to the MBean Server repository. * See JMX Specification, version 1.4 ; Chap 8.4.1 : 'A class loader is added to the repository if it is registered as an MBean'. * @author The ProActive Team */ public interface JMXClassLoaderMBean extends Serializable { }
Java
<?php /** * Copyright (C) 2020 Xibo Signage Ltd * * Xibo - Digital Signage - http://www.xibo.org.uk * * This file is part of Xibo. * * Xibo is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Xibo 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Xibo. If not, see <http://www.gnu.org/licenses/>. */ namespace Xibo\Widget; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; /** * Class TwitterBase * @package Xibo\Widget */ abstract class TwitterBase extends ModuleWidget { /** * Get a auth token * @return bool|mixed */ protected function getToken() { // Prepare the URL $url = 'https://api.twitter.com/oauth2/token'; // Prepare the consumer key and secret $key = base64_encode(urlencode($this->getSetting('apiKey')) . ':' . urlencode($this->getSetting('apiSecret'))); // Check to see if we have the bearer token already cached $cache = $this->getPool()->getItem($this->makeCacheKey('bearer_' . $key)); $token = $cache->get(); if ($cache->isHit()) { $this->getLog()->debug('Bearer Token served from cache'); return $token; } // We can take up to 30 seconds to request a new token $cache->lock(30); $this->getLog()->debug('Bearer Token served from API'); $client = new Client($this->getConfig()->getGuzzleProxy()); try { $response = $client->request('POST', $url, [ 'form_params' => [ 'grant_type' => 'client_credentials' ], 'headers' => [ 'Authorization' => 'Basic ' . $key ] ]); $result = json_decode($response->getBody()->getContents()); if ($result->token_type !== 'bearer') { $this->getLog()->error('Twitter API returned OK, but without a bearer token. ' . var_export($result, true)); return false; } // It is, so lets cache it // long times... $cache->set($result->access_token); $cache->expiresAfter(100000); $this->getPool()->saveDeferred($cache); return $result->access_token; } catch (RequestException $requestException) { $this->getLog()->error('Twitter API returned ' . $requestException->getMessage() . ' status. Unable to proceed.'); return false; } } /** * Search the twitter API * @param $token * @param $term * @param $language * @param string $resultType * @param string $geoCode * @param int $count * @return bool|mixed * @throws \GuzzleHttp\Exception\GuzzleException */ protected function searchApi($token, $term, $language = '', $resultType = 'mixed', $geoCode = '', $count = 15) { $client = new Client($this->getConfig()->getGuzzleProxy()); $query = [ 'q' => trim($term), 'result_type' => $resultType, 'count' => $count, 'include_entities' => true, 'tweet_mode' => 'extended' ]; if ($geoCode != '') $query['geocode'] = $geoCode; if ($language != '') $query['lang'] = $language; $this->getLog()->debug('Query is: ' . json_encode($query)); try { $request = $client->request('GET', 'https://api.twitter.com/1.1/search/tweets.json', [ 'headers' => [ 'Authorization' => 'Bearer ' . $token ], 'query' => $query ]); return json_decode($request->getBody()->getContents()); } catch (RequestException $requestException) { $this->getLog()->error('Unable to reach twitter api. ' . $requestException->getMessage()); return false; } } }
Java
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.propdev.impl.action; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.sys.framework.rule.KcTransactionalDocumentRuleBase; import org.kuali.rice.core.api.util.RiceKeyConstants; public class ProposalDevelopmentRejectionRule extends KcTransactionalDocumentRuleBase { private static final String ACTION_REASON = "proposalDevelopmentRejectionBean.actionReason"; public boolean proccessProposalDevelopmentRejection(ProposalDevelopmentActionBean bean) { boolean valid = true; if (StringUtils.isEmpty(bean.getActionReason())) { valid = false; String errorParams = ""; reportError(ACTION_REASON, RiceKeyConstants.ERROR_REQUIRED, errorParams); } return valid; } }
Java
# lint-amnesty, pylint: disable=missing-module-docstring from unittest.mock import patch from django.test import TestCase from common.djangoapps.track.backends.mongodb import MongoBackend class TestMongoBackend(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring def setUp(self): super().setUp() self.mongo_patcher = patch('common.djangoapps.track.backends.mongodb.MongoClient') self.mongo_patcher.start() self.addCleanup(self.mongo_patcher.stop) self.backend = MongoBackend() def test_mongo_backend(self): events = [{'test': 1}, {'test': 2}] self.backend.send(events[0]) self.backend.send(events[1]) # Check if we inserted events into the database calls = self.backend.collection.insert.mock_calls assert len(calls) == 2 # Unpack the arguments and check if the events were used # as the first argument to collection.insert def first_argument(call): _, args, _ = call return args[0] assert events[0] == first_argument(calls[0]) assert events[1] == first_argument(calls[1])
Java
## Institutional Proposal Persons [/instprop/api/v1/institutional-proposal-persons/] ### Get Institutional Proposal Persons by Key [GET /instprop/api/v1/institutional-proposal-persons/(key)] + Request + Headers Authorization: Bearer {api-key} Content-Type: application/json + Response 200 + Headers Content-Type: application/json;charset=UTF-8 + Body {"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"} ### Get All Institutional Proposal Persons [GET /instprop/api/v1/institutional-proposal-persons/] + Request + Headers Authorization: Bearer {api-key} Content-Type: application/json + Response 200 + Headers Content-Type: application/json;charset=UTF-8 + Body [ {"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"}, {"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"} ] ### Get All Institutional Proposal Persons with Filtering [GET /instprop/api/v1/institutional-proposal-persons/] + Parameters + institutionalProposalContactId (optional) - InstitutionalProposal Contact ID. Maximum length is 8. + personId (optional) - + rolodexId (optional) - + fullName (optional) - Full Name. Maximum length is 90. + academicYearEffort (optional) - Academic Year Effort. Maximum length is 7. + calendarYearEffort (optional) - Calendar Year Effort. Maximum length is 7. + summerEffort (optional) - Summer Effort. Maximum length is 7. + totalEffort (optional) - Total Effort. Maximum length is 7. + faculty (optional) - Faculty flag. Maximum length is 1. + roleCode (optional) - + keyPersonRole (optional) - Project Role. Maximum length is 60. + proposalNumber (optional) - Institutional Proposal Number. Maximum length is 8. + sequenceNumber (optional) - Sequence Number. Maximum length is 4. + institutionalProposal.proposalId (optional) - + Request + Headers Authorization: Bearer {api-key} Content-Type: application/json + Response 200 + Headers Content-Type: application/json;charset=UTF-8 + Body [ {"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"}, {"institutionalProposalContactId": "(val)","personId": "(val)","rolodexId": "(val)","fullName": "(val)","academicYearEffort": "(val)","calendarYearEffort": "(val)","summerEffort": "(val)","totalEffort": "(val)","faculty": "(val)","roleCode": "(val)","keyPersonRole": "(val)","proposalNumber": "(val)","sequenceNumber": "(val)","institutionalProposal.proposalId": "(val)","_primaryKey": "(val)"} ] ### Get Schema for Institutional Proposal Persons [GET /instprop/api/v1/institutional-proposal-persons/] + Parameters + _schema (required) - will instruct the endpoint to return a schema data structure for the resource + Request + Headers Authorization: Bearer {api-key} Content-Type: application/json + Response 200 + Headers Content-Type: application/json;charset=UTF-8 + Body {"columns":["institutionalProposalContactId","personId","rolodexId","fullName","academicYearEffort","calendarYearEffort","summerEffort","totalEffort","faculty","roleCode","keyPersonRole","proposalNumber","sequenceNumber","institutionalProposal.proposalId"],"primaryKey":"institutionalProposalContactId"} ### Get Blueprint API specification for Institutional Proposal Persons [GET /instprop/api/v1/institutional-proposal-persons/] + Parameters + _blueprint (required) - will instruct the endpoint to return an api blueprint markdown file for the resource + Request + Headers Authorization: Bearer {api-key} Content-Type: text/markdown + Response 200 + Headers Content-Type: text/markdown;charset=UTF-8 Content-Disposition:attachment; filename="Institutional Proposal Persons.md" transfer-encoding:chunked
Java
"""Capa's specialized use of codejail.safe_exec.""" import hashlib from codejail.safe_exec import SafeExecException, json_safe from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec from codejail.safe_exec import safe_exec as codejail_safe_exec from edx_django_utils.monitoring import function_trace import six from six import text_type from . import lazymod from .remote_exec import is_codejail_rest_service_enabled, get_remote_exec # Establish the Python environment for Capa. # Capa assumes float-friendly division always. # The name "random" is a properly-seeded stand-in for the random module. CODE_PROLOG = """\ from __future__ import absolute_import, division import os os.environ["OPENBLAS_NUM_THREADS"] = "1" # See TNL-6456 import random2 as random_module import sys from six.moves import xrange random = random_module.Random(%r) random.Random = random_module.Random sys.modules['random'] = random """ ASSUMED_IMPORTS = [ ("numpy", "numpy"), ("math", "math"), ("scipy", "scipy"), ("calc", "calc"), ("eia", "eia"), ("chemcalc", "chem.chemcalc"), ("chemtools", "chem.chemtools"), ("miller", "chem.miller"), ("draganddrop", "verifiers.draganddrop"), ] # We'll need the code from lazymod.py for use in safe_exec, so read it now. lazymod_py_file = lazymod.__file__ if lazymod_py_file.endswith("c"): lazymod_py_file = lazymod_py_file[:-1] with open(lazymod_py_file) as f: lazymod_py = f.read() LAZY_IMPORTS = [lazymod_py] for name, modname in ASSUMED_IMPORTS: LAZY_IMPORTS.append("{} = LazyModule('{}')\n".format(name, modname)) LAZY_IMPORTS = "".join(LAZY_IMPORTS) def update_hash(hasher, obj): """ Update a `hashlib` hasher with a nested object. To properly cache nested structures, we need to compute a hash from the entire structure, canonicalizing at every level. `hasher`'s `.update()` method is called a number of times, touching all of `obj` in the process. Only primitive JSON-safe types are supported. """ hasher.update(six.b(str(type(obj)))) if isinstance(obj, (tuple, list)): for e in obj: update_hash(hasher, e) elif isinstance(obj, dict): for k in sorted(obj): update_hash(hasher, k) update_hash(hasher, obj[k]) else: hasher.update(six.b(repr(obj))) @function_trace('safe_exec') def safe_exec( code, globals_dict, random_seed=None, python_path=None, extra_files=None, cache=None, limit_overrides_context=None, slug=None, unsafely=False, ): """ Execute python code safely. `code` is the Python code to execute. It has access to the globals in `globals_dict`, and any changes it makes to those globals are visible in `globals_dict` when this function returns. `random_seed` will be used to see the `random` module available to the code. `python_path` is a list of filenames or directories to add to the Python path before execution. If the name is not in `extra_files`, then it will also be copied into the sandbox. `extra_files` is a list of (filename, contents) pairs. These files are created in the sandbox. `cache` is an object with .get(key) and .set(key, value) methods. It will be used to cache the execution, taking into account the code, the values of the globals, and the random seed. `limit_overrides_context` is an optional string to be used as a key on the `settings.CODE_JAIL['limit_overrides']` dictionary in order to apply context-specific overrides to the codejail execution limits. If `limit_overrides_context` is omitted or not present in limit_overrides, then use the default limits specified insettings.CODE_JAIL['limits']. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. If `unsafely` is true, then the code will actually be executed without sandboxing. """ # Check the cache for a previous result. if cache: safe_globals = json_safe(globals_dict) md5er = hashlib.md5() md5er.update(repr(code).encode('utf-8')) update_hash(md5er, safe_globals) key = "safe_exec.%r.%s" % (random_seed, md5er.hexdigest()) cached = cache.get(key) if cached is not None: # We have a cached result. The result is a pair: the exception # message, if any, else None; and the resulting globals dictionary. emsg, cleaned_results = cached globals_dict.update(cleaned_results) if emsg: raise SafeExecException(emsg) return # Create the complete code we'll run. code_prolog = CODE_PROLOG % random_seed if is_codejail_rest_service_enabled(): data = { "code": code_prolog + LAZY_IMPORTS + code, "globals_dict": globals_dict, "python_path": python_path, "limit_overrides_context": limit_overrides_context, "slug": slug, "unsafely": unsafely, "extra_files": extra_files, } emsg, exception = get_remote_exec(data) else: # Decide which code executor to use. if unsafely: exec_fn = codejail_not_safe_exec else: exec_fn = codejail_safe_exec # Run the code! Results are side effects in globals_dict. try: exec_fn( code_prolog + LAZY_IMPORTS + code, globals_dict, python_path=python_path, extra_files=extra_files, limit_overrides_context=limit_overrides_context, slug=slug, ) except SafeExecException as e: # Saving SafeExecException e in exception to be used later. exception = e emsg = text_type(e) else: emsg = None # Put the result back in the cache. This is complicated by the fact that # the globals dict might not be entirely serializable. if cache: cleaned_results = json_safe(globals_dict) cache.set(key, (emsg, cleaned_results)) # If an exception happened, raise it now. if emsg: raise exception
Java
<?php require_once __DIR__.'/Base.php'; use Subscriber\ProjectModificationDateSubscriber; use Model\Project; use Model\ProjectPermission; use Model\User; use Model\Task; use Model\TaskCreation; use Model\Acl; use Model\Board; use Model\Config; use Model\Category; class ProjectTest extends Base { public function testCreation() { $p = new Project($this->container); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertEquals(1, $project['is_active']); $this->assertEquals(0, $project['is_public']); $this->assertEquals(0, $project['is_private']); $this->assertEquals(time(), $project['last_modified']); $this->assertEmpty($project['token']); } public function testCreationWithDefaultCategories() { $p = new Project($this->container); $c = new Config($this->container); $cat = new Category($this->container); // Multiple categories correctly formatted $this->assertTrue($c->save(array('project_categories' => 'Test1, Test2'))); $this->assertEquals(1, $p->create(array('name' => 'UnitTest1'))); $project = $p->getById(1); $this->assertNotEmpty($project); $categories = $cat->getAll(1); $this->assertNotEmpty($categories); $this->assertEquals(2, count($categories)); $this->assertEquals('Test1', $categories[0]['name']); $this->assertEquals('Test2', $categories[1]['name']); // Single category $this->assertTrue($c->save(array('project_categories' => 'Test1'))); $this->assertEquals(2, $p->create(array('name' => 'UnitTest2'))); $project = $p->getById(2); $this->assertNotEmpty($project); $categories = $cat->getAll(2); $this->assertNotEmpty($categories); $this->assertEquals(1, count($categories)); $this->assertEquals('Test1', $categories[0]['name']); // Multiple categories badly formatted $this->assertTrue($c->save(array('project_categories' => 'ABC, , DEF 3, '))); $this->assertEquals(3, $p->create(array('name' => 'UnitTest3'))); $project = $p->getById(3); $this->assertNotEmpty($project); $categories = $cat->getAll(3); $this->assertNotEmpty($categories); $this->assertEquals(2, count($categories)); $this->assertEquals('ABC', $categories[0]['name']); $this->assertEquals('DEF 3', $categories[1]['name']); // No default categories $this->assertTrue($c->save(array('project_categories' => ' '))); $this->assertEquals(4, $p->create(array('name' => 'UnitTest4'))); $project = $p->getById(4); $this->assertNotEmpty($project); $categories = $cat->getAll(4); $this->assertEmpty($categories); } public function testUpdateLastModifiedDate() { $p = new Project($this->container); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $now = time(); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertEquals($now, $project['last_modified'], 'Wrong Timestamp', 1); sleep(1); $this->assertTrue($p->updateModificationDate(1)); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertGreaterThan($now, $project['last_modified']); } public function testIsLastModified() { $p = new Project($this->container); $tc = new TaskCreation($this->container); $now = time(); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertEquals($now, $project['last_modified']); sleep(1); $listener = new ProjectModificationDateSubscriber($this->container); $this->container['dispatcher']->addListener(Task::EVENT_CREATE_UPDATE, array($listener, 'execute')); $this->assertEquals(1, $tc->create(array('title' => 'Task #1', 'project_id' => 1))); $called = $this->container['dispatcher']->getCalledListeners(); $this->assertArrayHasKey(Task::EVENT_CREATE_UPDATE.'.Subscriber\ProjectModificationDateSubscriber::execute', $called); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertTrue($p->isModifiedSince(1, $now)); } public function testRemove() { $p = new Project($this->container); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $this->assertTrue($p->remove(1)); $this->assertFalse($p->remove(1234)); } public function testEnable() { $p = new Project($this->container); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $this->assertTrue($p->disable(1)); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertEquals(0, $project['is_active']); $this->assertFalse($p->disable(1111)); } public function testDisable() { $p = new Project($this->container); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $this->assertTrue($p->disable(1)); $this->assertTrue($p->enable(1)); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertEquals(1, $project['is_active']); $this->assertFalse($p->enable(1234567)); } public function testEnablePublicAccess() { $p = new Project($this->container); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $this->assertTrue($p->enablePublicAccess(1)); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertEquals(1, $project['is_public']); $this->assertNotEmpty($project['token']); $this->assertFalse($p->enablePublicAccess(123)); } public function testDisablePublicAccess() { $p = new Project($this->container); $this->assertEquals(1, $p->create(array('name' => 'UnitTest'))); $this->assertTrue($p->enablePublicAccess(1)); $this->assertTrue($p->disablePublicAccess(1)); $project = $p->getById(1); $this->assertNotEmpty($project); $this->assertEquals(0, $project['is_public']); $this->assertEmpty($project['token']); $this->assertFalse($p->disablePublicAccess(123)); } }
Java
from ddt import ddt, data from django.core.urlresolvers import reverse from django.test import TestCase import mock from analyticsclient.exceptions import NotFoundError from courses.tests import SwitchMixin from courses.tests.test_views import ViewTestMixin, DEMO_COURSE_ID, DEPRECATED_DEMO_COURSE_ID from courses.tests.utils import convert_list_of_dicts_to_csv, get_mock_api_enrollment_geography_data, \ get_mock_api_enrollment_data, get_mock_api_course_activity, get_mock_api_enrollment_age_data, \ get_mock_api_enrollment_education_data, get_mock_api_enrollment_gender_data @ddt # pylint: disable=abstract-method class CourseCSVTestMixin(ViewTestMixin): client = None column_headings = None base_file_name = None def assertIsValidCSV(self, course_id, csv_data): response = self.client.get(self.path(course_id=course_id)) # Check content type self.assertResponseContentType(response, 'text/csv') # Check filename csv_prefix = u'edX-DemoX-Demo_2014' if course_id == DEMO_COURSE_ID else u'edX-DemoX-Demo_Course' filename = '{0}--{1}.csv'.format(csv_prefix, self.base_file_name) self.assertResponseFilename(response, filename) # Check data self.assertEqual(response.content, csv_data) def assertResponseContentType(self, response, content_type): self.assertEqual(response['Content-Type'], content_type) def assertResponseFilename(self, response, filename): self.assertEqual(response['Content-Disposition'], 'attachment; filename="{0}"'.format(filename)) def _test_csv(self, course_id, csv_data): with mock.patch(self.api_method, return_value=csv_data): self.assertIsValidCSV(course_id, csv_data) @data(DEMO_COURSE_ID, DEPRECATED_DEMO_COURSE_ID) def test_response_no_data(self, course_id): # Create an "empty" CSV that only has headers csv_data = convert_list_of_dicts_to_csv([], self.column_headings) self._test_csv(course_id, csv_data) @data(DEMO_COURSE_ID, DEPRECATED_DEMO_COURSE_ID) def test_response(self, course_id): csv_data = self.get_mock_data(course_id) csv_data = convert_list_of_dicts_to_csv(csv_data) self._test_csv(course_id, csv_data) def test_404(self): course_id = 'fakeOrg/soFake/Fake_Course' self.grant_permission(self.user, course_id) path = reverse(self.viewname, kwargs={'course_id': course_id}) with mock.patch(self.api_method, side_effect=NotFoundError): response = self.client.get(path, follow=True) self.assertEqual(response.status_code, 404) class CourseEnrollmentByCountryCSVViewTests(CourseCSVTestMixin, TestCase): viewname = 'courses:csv:enrollment_geography' column_headings = ['count', 'country', 'course_id', 'date'] base_file_name = 'enrollment-location' api_method = 'analyticsclient.course.Course.enrollment' def get_mock_data(self, course_id): return get_mock_api_enrollment_geography_data(course_id) class CourseEnrollmentCSVViewTests(CourseCSVTestMixin, TestCase): viewname = 'courses:csv:enrollment' column_headings = ['count', 'course_id', 'date'] base_file_name = 'enrollment' api_method = 'analyticsclient.course.Course.enrollment' def get_mock_data(self, course_id): return get_mock_api_enrollment_data(course_id) class CourseEnrollmentModeCSVViewTests(SwitchMixin, CourseCSVTestMixin, TestCase): viewname = 'courses:csv:enrollment' column_headings = ['count', 'course_id', 'date', 'audit', 'honor', 'professional', 'verified'] base_file_name = 'enrollment' api_method = 'analyticsclient.course.Course.enrollment' @classmethod def setUpClass(cls): cls.toggle_switch('display_verified_enrollment', True) def get_mock_data(self, course_id): return get_mock_api_enrollment_data(course_id) class CourseEnrollmentDemographicsByAgeCSVViewTests(CourseCSVTestMixin, TestCase): viewname = 'courses:csv:enrollment_demographics_age' column_headings = ['birth_year', 'count', 'course_id', 'created', 'date'] base_file_name = 'enrollment-by-birth-year' api_method = 'analyticsclient.course.Course.enrollment' def get_mock_data(self, course_id): return get_mock_api_enrollment_age_data(course_id) class CourseEnrollmentDemographicsByEducationCSVViewTests(CourseCSVTestMixin, TestCase): viewname = 'courses:csv:enrollment_demographics_education' column_headings = ['count', 'course_id', 'created', 'date', 'education_level.name', 'education_level.short_name'] base_file_name = 'enrollment-by-education' api_method = 'analyticsclient.course.Course.enrollment' def get_mock_data(self, course_id): return get_mock_api_enrollment_education_data(course_id) class CourseEnrollmentByDemographicsGenderCSVViewTests(CourseCSVTestMixin, TestCase): viewname = 'courses:csv:enrollment_demographics_gender' column_headings = ['count', 'course_id', 'created', 'date', 'gender'] base_file_name = 'enrollment-by-gender' api_method = 'analyticsclient.course.Course.enrollment' def get_mock_data(self, course_id): return get_mock_api_enrollment_gender_data(course_id) class CourseEngagementActivityTrendCSVViewTests(CourseCSVTestMixin, TestCase): viewname = 'courses:csv:engagement_activity_trend' column_headings = ['any', 'attempted_problem', 'course_id', 'interval_end', 'interval_start', 'played_video', 'posted_forum'] base_file_name = 'engagement-activity' api_method = 'analyticsclient.course.Course.activity' def get_mock_data(self, course_id): return get_mock_api_course_activity(course_id)
Java
<?php $module_name='Cosib_postsale'; $subpanel_layout = array ( 'top_buttons' => array ( 0 => array ( 'widget_class' => 'SubPanelTopCreateButton', ), 1 => array ( 'widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'Cosib_postsale', ), ), 'where' => '', 'list_fields' => array ( 'date_modified' => array ( 'vname' => 'LBL_DATE_MODIFIED', 'width' => '45%', ), 'edit_button' => array ( 'widget_class' => 'SubPanelEditButton', 'module' => 'Cosib_postsale', 'width' => '4%', ), 'remove_button' => array ( 'widget_class' => 'SubPanelRemoveButton', 'module' => 'Cosib_postsale', 'width' => '5%', ), ), );
Java
<h1>Welcome to FixMyStreet</h1> <p> Using this app you can report common street problems, like potholes or broken street lights, to councils throughout the UK. </p> <p> It works online and offline, because we know that there isn't always a signal when you need one. </p>
Java
class CreateIdentities < ActiveRecord::Migration def change create_table :identities do |t| t.references :user, index: true t.string :provider t.string :uid t.timestamps null: false end end end
Java
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo import api, fields, models class ProductProduct(models.Model): _inherit = "product.product" date_from = fields.Date(compute='_compute_product_margin_fields_values', string='Margin Date From') date_to = fields.Date(compute='_compute_product_margin_fields_values', string='Margin Date To') invoice_state = fields.Selection(compute='_compute_product_margin_fields_values', selection=[ ('paid', 'Paid'), ('open_paid', 'Open and Paid'), ('draft_open_paid', 'Draft, Open and Paid') ], string='Invoice State', readonly=True) sale_avg_price = fields.Float(compute='_compute_product_margin_fields_values', string='Avg. Sale Unit Price', help="Avg. Price in Customer Invoices.") purchase_avg_price = fields.Float(compute='_compute_product_margin_fields_values', string='Avg. Purchase Unit Price', help="Avg. Price in Vendor Bills ") sale_num_invoiced = fields.Float(compute='_compute_product_margin_fields_values', string='# Invoiced in Sale', help="Sum of Quantity in Customer Invoices") purchase_num_invoiced = fields.Float(compute='_compute_product_margin_fields_values', string='# Invoiced in Purchase', help="Sum of Quantity in Vendor Bills") sales_gap = fields.Float(compute='_compute_product_margin_fields_values', string='Sales Gap', help="Expected Sale - Turn Over") purchase_gap = fields.Float(compute='_compute_product_margin_fields_values', string='Purchase Gap', help="Normal Cost - Total Cost") turnover = fields.Float(compute='_compute_product_margin_fields_values', string='Turnover', help="Sum of Multiplication of Invoice price and quantity of Customer Invoices") total_cost = fields.Float(compute='_compute_product_margin_fields_values', string='Total Cost', help="Sum of Multiplication of Invoice price and quantity of Vendor Bills ") sale_expected = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Sale', help="Sum of Multiplication of Sale Catalog price and quantity of Customer Invoices") normal_cost = fields.Float(compute='_compute_product_margin_fields_values', string='Normal Cost', help="Sum of Multiplication of Cost price and quantity of Vendor Bills") total_margin = fields.Float(compute='_compute_product_margin_fields_values', string='Total Margin', help="Turnover - Standard price") expected_margin = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Margin', help="Expected Sale - Normal Cost") total_margin_rate = fields.Float(compute='_compute_product_margin_fields_values', string='Total Margin Rate(%)', help="Total margin * 100 / Turnover") expected_margin_rate = fields.Float(compute='_compute_product_margin_fields_values', string='Expected Margin (%)', help="Expected margin * 100 / Expected Sale") @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): """ Inherit read_group to calculate the sum of the non-stored fields, as it is not automatically done anymore through the XML. """ res = super(ProductProduct, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) fields_list = ['turnover', 'sale_avg_price', 'sale_purchase_price', 'sale_num_invoiced', 'purchase_num_invoiced', 'sales_gap', 'purchase_gap', 'total_cost', 'sale_expected', 'normal_cost', 'total_margin', 'expected_margin', 'total_margin_rate', 'expected_margin_rate'] if any(x in fields for x in fields_list): # Calculate first for every product in which line it needs to be applied re_ind = 0 prod_re = {} tot_products = self.browse([]) for re in res: if re.get('__domain'): products = self.search(re['__domain']) tot_products |= products for prod in products: prod_re[prod.id] = re_ind re_ind += 1 res_val = tot_products._compute_product_margin_fields_values(field_names=[x for x in fields if fields in fields_list]) for key in res_val: for l in res_val[key]: re = res[prod_re[key]] if re.get(l): re[l] += res_val[key][l] else: re[l] = res_val[key][l] return res def _compute_product_margin_fields_values(self, field_names=None): res = {} if field_names is None: field_names = [] for val in self: res[val.id] = {} date_from = self.env.context.get('date_from', time.strftime('%Y-01-01')) date_to = self.env.context.get('date_to', time.strftime('%Y-12-31')) invoice_state = self.env.context.get('invoice_state', 'open_paid') res[val.id]['date_from'] = date_from res[val.id]['date_to'] = date_to res[val.id]['invoice_state'] = invoice_state states = () payment_states = () if invoice_state == 'paid': states = ('posted',) payment_states = ('paid',) elif invoice_state == 'open_paid': states = ('posted',) payment_states = ('not_paid', 'paid') elif invoice_state == 'draft_open_paid': states = ('posted', 'draft') payment_states = ('not_paid', 'paid') company_id = self.env.company.id #Cost price is calculated afterwards as it is a property self.env['account.move.line'].flush(['price_unit', 'quantity', 'balance', 'product_id', 'display_type']) self.env['account.move'].flush(['state', 'payment_state', 'move_type', 'invoice_date', 'company_id']) self.env['product.template'].flush(['list_price']) sqlstr = """ WITH currency_rate AS ({}) SELECT SUM(l.price_unit / (CASE COALESCE(cr.rate, 0) WHEN 0 THEN 1.0 ELSE cr.rate END) * l.quantity) / NULLIF(SUM(l.quantity),0) AS avg_unit_price, SUM(l.quantity * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS num_qty, SUM(ABS(l.balance) * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS total, SUM(l.quantity * pt.list_price * (CASE WHEN i.move_type IN ('out_invoice', 'in_invoice') THEN 1 ELSE -1 END)) AS sale_expected FROM account_move_line l LEFT JOIN account_move i ON (l.move_id = i.id) LEFT JOIN product_product product ON (product.id=l.product_id) LEFT JOIN product_template pt ON (pt.id = product.product_tmpl_id) left join currency_rate cr on (cr.currency_id = i.currency_id and cr.company_id = i.company_id and cr.date_start <= COALESCE(i.invoice_date, NOW()) and (cr.date_end IS NULL OR cr.date_end > COALESCE(i.invoice_date, NOW()))) WHERE l.product_id = %s AND i.state IN %s AND i.payment_state IN %s AND i.move_type IN %s AND i.invoice_date BETWEEN %s AND %s AND i.company_id = %s AND l.display_type IS NULL AND l.exclude_from_invoice_tab = false """.format(self.env['res.currency']._select_companies_rates()) invoice_types = ('out_invoice', 'out_refund') self.env.cr.execute(sqlstr, (val.id, states, payment_states, invoice_types, date_from, date_to, company_id)) result = self.env.cr.fetchall()[0] res[val.id]['sale_avg_price'] = result[0] and result[0] or 0.0 res[val.id]['sale_num_invoiced'] = result[1] and result[1] or 0.0 res[val.id]['turnover'] = result[2] and result[2] or 0.0 res[val.id]['sale_expected'] = result[3] and result[3] or 0.0 res[val.id]['sales_gap'] = res[val.id]['sale_expected'] - res[val.id]['turnover'] invoice_types = ('in_invoice', 'in_refund') self.env.cr.execute(sqlstr, (val.id, states, payment_states, invoice_types, date_from, date_to, company_id)) result = self.env.cr.fetchall()[0] res[val.id]['purchase_avg_price'] = result[0] and result[0] or 0.0 res[val.id]['purchase_num_invoiced'] = result[1] and result[1] or 0.0 res[val.id]['total_cost'] = result[2] and result[2] or 0.0 res[val.id]['normal_cost'] = val.standard_price * res[val.id]['purchase_num_invoiced'] res[val.id]['purchase_gap'] = res[val.id]['normal_cost'] - res[val.id]['total_cost'] res[val.id]['total_margin'] = res[val.id]['turnover'] - res[val.id]['total_cost'] res[val.id]['expected_margin'] = res[val.id]['sale_expected'] - res[val.id]['normal_cost'] res[val.id]['total_margin_rate'] = res[val.id]['turnover'] and res[val.id]['total_margin'] * 100 / res[val.id]['turnover'] or 0.0 res[val.id]['expected_margin_rate'] = res[val.id]['sale_expected'] and res[val.id]['expected_margin'] * 100 / res[val.id]['sale_expected'] or 0.0 for k, v in res[val.id].items(): setattr(val, k, v) return res
Java
# clean sequences after alignment, criteria based on sequences # make inline with canonical ordering (no extra gaps) import os, datetime, time, re from itertools import izip from Bio.Align import MultipleSeqAlignment from Bio.Seq import Seq from scipy import stats import numpy as np class virus_clean(object): """docstring for virus_clean""" def __init__(self,n_iqd = 5, **kwargs): ''' parameters n_std -- number of interquartile distances accepted in molecular clock filter ''' self.n_iqd = n_iqd def remove_insertions(self): ''' remove all columns from the alignment in which the outgroup is gapped ''' outgroup_ok = np.array(self.sequence_lookup[self.outgroup['strain']])!='-' for seq in self.viruses: seq.seq = Seq("".join(np.array(seq.seq)[outgroup_ok]).upper()) def clean_gaps(self): ''' remove viruses with gaps -- not part of the standard pipeline ''' self.viruses = filter(lambda x: '-' in x.seq, self.viruses) def clean_ambiguous(self): ''' substitute all ambiguous characters with '-', ancestral inference will interpret this as missing data ''' for v in self.viruses: v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq))) def unique_date(self): ''' add a unique numerical date to each leaf. uniqueness is achieved adding a small number ''' from date_util import numerical_date og = self.sequence_lookup[self.outgroup['strain']] if hasattr(og, 'date'): try: og.num_date = numerical_date(og.date) except: print "cannot parse date" og.num_date="undefined"; for ii, v in enumerate(self.viruses): if hasattr(v, 'date'): try: v.num_date = numerical_date(v.date, self.date_format['fields']) + 1e-7*(ii+1) except: print "cannot parse date" v.num_date="undefined"; def times_from_outgroup(self): outgroup_date = self.sequence_lookup[self.outgroup['strain']].num_date return np.array([x.num_date-outgroup_date for x in self.viruses if x.strain]) def distance_from_outgroup(self): from seq_util import hamming_distance outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain]) def clean_distances(self): """Remove viruses that don't follow a loose clock """ times = self.times_from_outgroup() distances = self.distance_from_outgroup() slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances) residuals = slope*times + intercept - distances r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25) if self.verbose: print "\tslope: " + str(slope) print "\tr: " + str(r_value) print "\tresiduals iqd: " + str(r_iqd) new_viruses = [] for (v,r) in izip(self.viruses,residuals): # filter viruses more than n_std standard devitations up or down if np.abs(r)<self.n_iqd * r_iqd or v.id == self.outgroup["strain"]: new_viruses.append(v) else: if self.verbose>1: print "\t\tresidual:", r, "\nremoved ",v.strain self.viruses = MultipleSeqAlignment(new_viruses) def clean_generic(self): print "Number of viruses before cleaning:",len(self.viruses) self.unique_date() self.remove_insertions() self.clean_ambiguous() self.clean_distances() self.viruses.sort(key=lambda x:x.num_date) print "Number of viruses after outlier filtering:",len(self.viruses)
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <title>libtcod documentation | Pseudorandom number generator</title> <script type="text/javascript" src="../js/doctcod.js"></script> <link href="../css/style.css" rel="stylesheet" type="text/css"></head> <link type="text/css" rel="stylesheet" href="../css/shCore.css"></link> <link type="text/css" rel="stylesheet" href="../css/shThemeDefault.css"></link> <script language="javascript" src="../js/shCore.js"></script> <script language="javascript" src="../js/shBrushBash.js"></script> <body><div class="header"> <p><span class="title1">libtcod</span><span class="title2">documentation</span></p> </div> <div class="breadcrumb"><div class="breadcrumbtext"><p> you are here: <a onclick="link('../index2.html')">Index</a> &gt; <a onclick="link('random.html')">7. Pseudorandom number generator</a><br> <a class="prev" onclick="link('list.html')">6. All purposes container</a> | <a class="next" onclick="link('mouse.html')">8. Mouse support</a> </p></div></div> <div class="filter"><input type="checkbox" id="chk_c" name="chk_c" onchange="enable('c',this.checked)" checked='checked' ><label for='chk_c'> C </label><input type="checkbox" id="chk_cpp" name="chk_cpp" onchange="enable('cpp',this.checked)" checked='checked' ><label for='chk_cpp'> C++ </label><input type="checkbox" id="chk_py" name="chk_py" onchange="enable('py',this.checked)" checked='checked' ><label for='chk_py'> Py </label><input type="checkbox" id="chk_lua" name="chk_lua" onchange="enable('lua',this.checked)" disabled='disabled'><label class='disabled' for='chk_lua'> Lua </label><input type="checkbox" id="chk_cs" name="chk_cs" onchange="enable('cs',this.checked)" disabled='disabled'><label class='disabled' for='chk_cs'> C# </label></div> <div class="main"><div class="maintext"> <h1>7. Pseudorandom number generator</h1> <div id="toc"><ul><li><a onclick="link('random_init.html')">7.1. Creating a generator</a></li> <li><a onclick="link('random_distro.html')">7.2. Using a generator</a></li> <li><a onclick="link('random_use.html')">7.3. Using a generator</a></li> </ul></div> <p>This toolkit is an implementation of two fast and high quality pseudorandom number generators:<br />* a Mersenne twister generator,<br />* a Complementary-Multiply-With-Carry generator.<br />CMWC is faster than MT (see table below) and has a much better period (1039460 vs. 106001). It is the default algo since libtcod 1.5.0.<br /><br />Relative performances in two independent tests (lower is better) :<br /><table class="param"> <tr> <th>Algorithm</th> <th>Numbers generated</th> <th>Perf (1)</th> <th>Perf (2)</th> </tr> <tr class="hilite"> <td>MT</td> <td>integer</td> <td>62</td> <td>50</td> </tr> <tr> <td>MT</td> <td>float</td> <td>54</td> <td>45</td> </tr> <tr class="hilite"> <td>CMWC</td> <td>integer</td> <td>21</td> <td>34</td> </tr> <tr> <td>CMWC</td> <td>float</td> <td>32</td> <td>27</td> </tr> </table><br /><br /><h6>For python users:</h6><br />Python already has great builtin random generators. But some parts of the Doryen library (noise, heightmap, ...) uses RNG as parameters. If you intend to use those functions, you must provide a RNG created with the library.<br /><br /><h6>For C# users:</h6><br />.NET already has great builtin random generators. But some parts of the Doryen library (noise, heightmap, ...) uses RNG as parameters. If you intend to use those functions, you must provide a RNG created with the library.<br /> </p> </div></div> <div class="footer"><div class="footertext"> <p>libtcod 1.5.2, &copy; 2008, 2009, 2010, 2012 Jice & Mingos<br> This file has been generated by doctcod.</p> <p><table width='100%'><tr><td><a href="http://doryen.eptalys.net/libtcod">libtcod website</a></td> <td><a href="http://doryen.eptalys.net/forum/index.php?board=12.0">libtcod on Roguecentral forums</a></td> <td><a href="http://doryen.eptalys.net/libtcod/tutorial">libtcod tutorials</a></td> </tr></table></p> </div></div> </body> <script> initFilter(); SyntaxHighlighter.all(); </script> </html>
Java
<?php // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. return [ 'availability' => [ 'disabled' => 'Ez a beatmap jelenleg nem letölthető.', 'parts-removed' => 'Ez a beatmap eltávolításra került a készítő vagy egy jogbirtokos harmadik fél kérésére.', 'more-info' => 'Itt találsz több információt.', 'rule_violation' => 'Ennek a map-nek néhány elemét eltávolítottuk, mert nem találtuk őket megfelelőnek az osu!-ban történő használathoz.', ], 'download' => [ 'limit_exceeded' => 'Lassíts le, játssz többet.', ], 'featured_artist_badge' => [ 'label' => 'Kiemelt előadó', ], 'index' => [ 'title' => 'Beatmap lista', 'guest_title' => 'Beatmap-ek', ], 'panel' => [ 'empty' => 'nincs beatmap', 'download' => [ 'all' => 'letöltés', 'video' => 'letöltés videóval', 'no_video' => 'letöltés videó nélkül', 'direct' => 'megnyitás osu!direct-ben', ], ], 'nominate' => [ 'hybrid_requires_modes' => 'Egy hibrid beatmap szettet legalább egy játékmódra nominálni kell.', 'incorrect_mode' => 'Nincs jogosultságod :mode módban nominálni', 'full_bn_required' => 'Teljes jogú nominátornak kell lenned a kvalifikálásra nomináláshoz.', 'too_many' => 'A nominálási követelmények már teljesültek.', 'dialog' => [ 'confirmation' => 'Biztosan nominálni szeretnéd ezt a Beatmap-et?', 'header' => 'Beatmap Nominálása', 'hybrid_warning' => 'megjegyzés: csak egyszer nominálhatsz, ezért kérlek győződj meg róla, hogy minden játékmódra nominálsz, amire szeretnél', 'which_modes' => 'Mely módokra nominálsz?', ], ], 'nsfw_badge' => [ 'label' => 'Felnőtt', ], 'show' => [ 'discussion' => 'Beszélgetés', 'details' => [ 'by_artist' => ':artist által', 'favourite' => 'A beatmap kedvencek közé tétele', 'favourite_login' => 'Jelentkezz be, hogy kedvencnek jelölt ezt beatmap-et', 'logged-out' => 'Beatmapek letöltéshez be kell jelentkezned!', 'mapped_by' => 'mappolva :mapper által', 'unfavourite' => 'Beatmap eltávolitása a kedvencek közül', 'updated_timeago' => 'utóljára frissítve: :timeago', 'download' => [ '_' => 'Letöltés', 'direct' => '', 'no-video' => 'Videó nélkül', 'video' => 'Videóval', ], 'login_required' => [ 'bottom' => 'további funkciók eléréséhez', 'top' => 'Bejelentkezés', ], ], 'details_date' => [ 'approved' => 'jóváhagyva: :timeago', 'loved' => 'szerette: :timeago', 'qualified' => 'kvalifikálva: :timeago', 'ranked' => 'rangsorolva: :timeago', 'submitted' => 'beküldve: :timeago', 'updated' => 'utolsó frissítés: :timeago', ], 'favourites' => [ 'limit_reached' => 'Túl sok beatmap van a kedvenceid között! Kérlek távolíts el néhányat az újrapróbálkozás előtt.', ], 'hype' => [ 'action' => 'Hype-old a beatmapet ha élvezted rajta a játékot, hogy segíthesd a <strong>Rangsorolt</strong> állapot felé jutásban.', 'current' => [ '_' => 'Ez a map :status jelenleg.', 'status' => [ 'pending' => 'függőben', 'qualified' => 'kvalifikált', 'wip' => 'munkálatok alatt', ], ], 'disqualify' => [ '_' => 'Ha találsz javaslatokat, problémákat a térképpel kapcsolatban, kérlek diszkvalifikáld ezen a linken keresztül: :link', ], 'report' => [ '_' => 'Ha találsz javaslatokat, problémákat a térképpel kapcsolatban, kérlek jelentsd az alábbi linken keresztül: :link', 'button' => 'Probléma jelentése', 'link' => 'itt', ], ], 'info' => [ 'description' => 'Leírás', 'genre' => 'Műfaj', 'language' => 'Nyelv', 'no_scores' => 'Az adatok még számítás alatt...', 'nsfw' => 'Felnőtt tartalom', 'points-of-failure' => 'Kibukási Alkalmak', 'source' => 'Forrás', 'storyboard' => 'Ez a beatmap storyboard-ot tartalmaz', 'success-rate' => 'Teljesítési arány', 'tags' => 'Címkék', 'video' => 'Ez a beatmap videót tartalmaz', ], 'nsfw_warning' => [ 'details' => 'Ez a beatmap szókimondó, sértő vagy felkavaró tartalmú. Továbbra is meg szeretnéd tekinteni?', 'title' => 'Felnőtt tartalom', 'buttons' => [ 'disable' => 'Figyelmeztetés kikapcsolása', 'listing' => 'Beatmap lista', 'show' => 'Mutassa', ], ], 'scoreboard' => [ 'achieved' => 'elérve: :when', 'country' => 'Országos Ranglista', 'error' => '', 'friend' => 'Baráti Ranglista', 'global' => 'Globális Ranglista', 'supporter-link' => 'Kattints <a href=":link">ide</a>,hogy megtekinthesd azt a sok jó funkciót amit kaphatsz!', 'supporter-only' => 'Támogató kell legyél, hogy elérd a baráti és az országos ranglistát!', 'title' => 'Eredménylista', 'headers' => [ 'accuracy' => 'Pontosság', 'combo' => 'Legmagasabb kombó', 'miss' => 'Miss', 'mods' => 'Modok', 'pin' => '', 'player' => 'Játékos', 'pp' => '', 'rank' => 'Rang', 'score' => 'Pontszám', 'score_total' => 'Összpontszám', 'time' => 'Idő', ], 'no_scores' => [ 'country' => 'Senki sem ért még el eredményt az országodból ezen a map-en!', 'friend' => 'Senki sem ért még el eredményt a barátaid közül ezen a map-en!', 'global' => 'Egyetlen eredmény sincs. Esetleg megpróbálhatnál szerezni párat?', 'loading' => 'Eredmények betöltése...', 'unranked' => 'Rangsorolatlan beatmap.', ], 'score' => [ 'first' => 'Az élen', 'own' => 'A legjobbad', ], 'supporter_link' => [ '_' => '', 'here' => '', ], ], 'stats' => [ 'cs' => 'Kör nagyság', 'cs-mania' => 'Billentyűk száma', 'drain' => 'HP Vesztés', 'accuracy' => 'Pontosság', 'ar' => 'Közelítési sebesség', 'stars' => 'Nehézség', 'total_length' => 'Hossz', 'bpm' => 'BPM', 'count_circles' => 'Körök Száma', 'count_sliders' => 'Sliderek Száma', 'user-rating' => 'Felhasználói Értékelés', 'rating-spread' => 'Értékelési Szórás', 'nominations' => 'Nominálások', 'playcount' => 'Játékszám', ], 'status' => [ 'ranked' => 'Rangsorolt', 'approved' => 'Jóváhagyott', 'loved' => 'Szeretett', 'qualified' => 'Kvalifikálva', 'wip' => 'Készítés alatt', 'pending' => 'Függőben', 'graveyard' => 'Temető', ], ], ];
Java
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('contentstore.rest_api.v1.serializers', 'cms.djangoapps.contentstore.rest_api.v1.serializers') from cms.djangoapps.contentstore.rest_api.v1.serializers import *
Java
/** \file * \author John Bridgman * \brief */ #include <Variant/Blob.h> #include <stdlib.h> #include <new> #include <string.h> #include <algorithm> namespace libvariant { static void MallocFree(void *ptr, void *) { free(ptr); } shared_ptr<Blob> Blob::Create(void *ptr, unsigned len, BlobFreeFunc ffunc, void *context) { struct iovec iov = { ptr, len }; return shared_ptr<Blob>(new Blob(&iov, 1, ffunc, context)); } BlobPtr Blob::Create(struct iovec *iov, unsigned iov_len, BlobFreeFunc ffunc, void *context) { return BlobPtr(new Blob(iov, iov_len, ffunc, context)); } shared_ptr<Blob> Blob::CreateCopy(const void *ptr, unsigned len) { struct iovec iov = { (void*)ptr, len }; return CreateCopy(&iov, 1); } BlobPtr Blob::CreateCopy(const struct iovec *iov, unsigned iov_len) { unsigned len = 0; for (unsigned i = 0; i < iov_len; ++i) { len += iov[i].iov_len; } void *data = 0; #ifdef __APPLE__ // TODO: Remove when apple fixes this error. if (posix_memalign(&data, 64, std::max(len, 1u)) != 0) { throw std::bad_alloc(); } #else if (posix_memalign(&data, 64, len) != 0) { throw std::bad_alloc(); } #endif for (unsigned i = 0, copied = 0; i < iov_len; ++i) { memcpy((char*)data + copied, iov[i].iov_base, iov[i].iov_len); copied += iov[i].iov_len; } struct iovec v = { data, len }; return shared_ptr<Blob>(new Blob(&v, 1, MallocFree, 0)); } shared_ptr<Blob> Blob::CreateFree(void *ptr, unsigned len) { struct iovec iov = { ptr, len }; return CreateFree(&iov, 1); } BlobPtr Blob::CreateFree(struct iovec *iov, unsigned iov_len) { return shared_ptr<Blob>(new Blob(iov, iov_len, MallocFree, 0)); } shared_ptr<Blob> Blob::CreateReferenced(void *ptr, unsigned len) { struct iovec iov = { ptr, len }; return CreateReferenced(&iov, 1); } BlobPtr Blob::CreateReferenced(struct iovec *iov, unsigned iov_len) { return shared_ptr<Blob>(new Blob(iov, iov_len, 0, 0)); } Blob::Blob(struct iovec *v, unsigned l, BlobFreeFunc f, void *c) : iov(v, v+l), free_func(f), ctx(c) { } Blob::~Blob() { if (free_func) { for (unsigned i = 0; i < iov.size(); ++i) { free_func(iov[i].iov_base, ctx); } } iov.clear(); free_func = 0; ctx = 0; } shared_ptr<Blob> Blob::Copy() const { return CreateCopy(&iov[0], iov.size()); } unsigned Blob::GetTotalLength() const { unsigned size = 0; for (unsigned i = 0; i < iov.size(); ++i) { size += iov[i].iov_len; } return size; } int Blob::Compare(ConstBlobPtr other) const { unsigned our_offset = 0; unsigned oth_offset = 0; unsigned i = 0, j = 0; while (i < GetNumBuffers() && j < other->GetNumBuffers()) { unsigned len = std::min(GetLength(i) - our_offset, other->GetLength(j) - oth_offset); int res = memcmp((char*)(GetPtr(i)) + our_offset, (char*)(other->GetPtr(j)) + oth_offset, len); if (res != 0) { return res; } our_offset += len; if (our_offset >= GetLength(i)) { our_offset = 0; ++i; } oth_offset += len; if (oth_offset >= other->GetLength(j)) { oth_offset = 0; ++j; } } return 0; } }
Java
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2014 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address [email protected]. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2014. All rights reserved". ********************************************************************************/ class MergeTagGuideAjaxLinkActionElement extends AjaxLinkActionElement { public function getActionType() { return 'MergeTagGuide'; } public function render() { $this->registerScript(); return parent::render(); } public function renderMenuItem() { $this->registerScript(); return parent::renderMenuItem(); } protected function getDefaultLabel() { return Zurmo::t('EmailTemplatesModule', 'MergeTag Guide'); } protected function getDefaultRoute() { return Yii::app()->createUrl($this->moduleId . '/' . $this->controllerId . '/mergeTagGuide/'); } protected function getAjaxOptions() { $parentAjaxOptions = parent::getAjaxOptions(); $modalViewAjaxOptions = ModalView::getAjaxOptionsForModalLink($this->getDefaultLabel()); if (!isset($this->params['ajaxOptions'])) { $this->params['ajaxOptions'] = array(); } return CMap::mergeArray($parentAjaxOptions, $modalViewAjaxOptions, $this->params['ajaxOptions']); } protected function getHtmlOptions() { $htmlOptionsInParams = parent::getHtmlOptions(); $defaultHtmlOptions = array('id' => 'mergetag-guide', 'class' => 'simple-link'); return CMap::mergeArray($defaultHtmlOptions, $htmlOptionsInParams); } protected function registerScript() { $eventHandlerName = get_class($this); $ajaxOptions = CMap::mergeArray($this->getAjaxOptions(), array('url' => $this->route)); if (Yii::app()->clientScript->isScriptRegistered($eventHandlerName)) { return; } else { Yii::app()->clientScript->registerScript($eventHandlerName, " function ". $eventHandlerName ."() { " . ZurmoHtml::ajax($ajaxOptions)." } ", CClientScript::POS_HEAD); } return $eventHandlerName; } } ?>
Java
/** \file * \author John Bridgman * \brief */ #ifndef VARIANT_GUESSFORMAT_H #define VARIANT_GUESSFORMAT_H #pragma once #include <Variant/Variant.h> #include <Variant/Parser.h> namespace libvariant { /// // Try to guess the format of the input without removing any // input from the input object. // // Currently only looks at the first non-whitespace character // and if it is '<' then says XMLPLIST, otherwise says YAML // if enabled otherwise JSON. // SerializeType GuessFormat(ParserInput* in); } #endif
Java
class AddPublicDiscussionsCount < ActiveRecord::Migration def change add_column :groups, :public_discussions_count, :integer, null: false, default: 0 end end
Java
endor_lantern_bird_neutral_none = Lair:new { mobiles = {{"lantern_bird",1}}, spawnLimit = 15, buildingsVeryEasy = {}, buildingsEasy = {}, buildingsMedium = {}, buildingsHard = {}, buildingsVeryHard = {}, buildingType = "none", } addLairTemplate("endor_lantern_bird_neutral_none", endor_lantern_bird_neutral_none)
Java
<?php use MapasCulturais\i; $section = ''; $groups = $this->getDictGroups(); $editEntity = $this->controller->action === 'create' || $this->controller->action === 'edit'; $texts = \MapasCulturais\Themes\BaseV1\Theme::_dict(); ?> <div id="texts" class="aba-content"> <p class="alert info"> <?php i::_e('Nesta seção você configura os textos utilizados na interface do site. Cada texto tem uma explicação do local em que deverá aparecer a informação. A opção de “exibir opções avançadas” possibilita que outros campos apareçam para definição dos textos.'); ?> </p> <?php foreach($groups as $gname => $group): ?> <section class="filter-section"> <header> <?php echo $group['title']; ?> <label class="show-all"><input class="js-exibir-todos" type="checkbox"> <?php i::_e('exibir opções avançadas'); ?></label> </header> <p class="help"><?php echo $group['description']; ?></p> <?php foreach ($texts as $key => $def): $skey = str_replace(' ', '+', $key); $section = substr($key, 0, strpos($key, ":")); if($section != $gname) continue; ?> <p class="js-text-config <?php if (isset($def['required']) && $def['required']): ?> required<?php else: ?> js-optional hidden<?php endif; ?>"> <span class="label"> <?php echo $def['name'] ?><?php if ($def['description']): ?><span class="info hltip" title="<?= htmlentities($def['description']) ?>"></span><?php endif; ?>: </span> <span class="js-editable js-editable--subsite-text" data-edit="<?php echo "dict:" . $skey ?>" data-original-title="<?php echo htmlentities($def['name']) ?>" data-emptytext="<?php echo isset($entity->dict[$key]) && !empty($entity->dict[$key])? '': 'utilizando valor padrão (clique para definir)';?>" <?php if (isset($def['examples']) && $def['examples']): ?>data-examples="<?= htmlentities(json_encode($def['examples'])) ?>" <?php endif; ?> data-placeholder='<?php echo isset($entity->dict[$key]) && !empty($entity->dict[$key])? $entity->dict[$key]:$def['text'] ; ?>'><?php echo isset($entity->dict[$key]) ? $entity->dict[$key] : ''; ?></span> </p> <?php endforeach; ?> </section> <?php endforeach; ?> </div>
Java
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2014 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address [email protected]. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2014. All rights reserved". ********************************************************************************/ /** * Default controller for all report actions */ class ReportsDefaultController extends ZurmoBaseController { public function filters() { return array_merge(parent::filters(), array( array( self::getRightsFilterPath() . ' + drillDownDetails', 'moduleClassName' => 'ReportsModule', 'rightName' => ReportsModule::RIGHT_ACCESS_REPORTS, ), array( self::getRightsFilterPath() . ' + selectType', 'moduleClassName' => 'ReportsModule', 'rightName' => ReportsModule::RIGHT_CREATE_REPORTS, ), array( ZurmoModuleController::ZERO_MODELS_CHECK_FILTER_PATH . ' + list, index', 'controller' => $this, ), ) ); } public function actionIndex() { $this->actionList(); } public function actionList() { $pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType( 'listPageSize', get_class($this->getModule())); $savedReport = new SavedReport(false); $searchForm = new ReportsSearchForm($savedReport); $listAttributesSelector = new ListAttributesSelector('ReportsListView', get_class($this->getModule())); $searchForm->setListAttributesSelector($listAttributesSelector); $dataProvider = $this->resolveSearchDataProvider( $searchForm, $pageSize, null, 'ReportsSearchView' ); $title = Zurmo::t('ReportsModule', 'Reports'); $breadCrumbLinks = array( $title, ); if (isset($_GET['ajax']) && $_GET['ajax'] == 'list-view') { $mixedView = $this->makeListView( $searchForm, $dataProvider ); $view = new ReportsPageView($mixedView); } else { $mixedView = $this->makeActionBarSearchAndListView($searchForm, $dataProvider, 'SecuredActionBarForReportsSearchAndListView'); $view = new ReportsPageView(ZurmoDefaultViewUtil:: makeViewWithBreadcrumbsForCurrentUser( $this, $mixedView, $breadCrumbLinks, 'ReportBreadCrumbView')); } echo $view->render(); } public function actionDetails($id) { $savedReport = static::getModelAndCatchNotFoundAndDisplayError('SavedReport', intval($id)); ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport); AuditEvent::logAuditEvent('ZurmoModule', ZurmoModule::AUDIT_EVENT_ITEM_VIEWED, array(strval($savedReport), 'ReportsModule'), $savedReport); $breadCrumbLinks = array(strval($savedReport)); $breadCrumbView = new ReportBreadCrumbView($this->getId(), $this->getModule()->getId(), $breadCrumbLinks); $detailsAndRelationsView = $this->makeReportDetailsAndRelationsView($savedReport, Yii::app()->request->getRequestUri(), $breadCrumbView); $view = new ReportsPageView(ZurmoDefaultViewUtil:: makeStandardViewForCurrentUser($this, $detailsAndRelationsView)); echo $view->render(); } public function actionSelectType() { $breadCrumbLinks = array(Zurmo::t('ReportsModule', 'Select Report Type')); $view = new ReportsPageView(ZurmoDefaultViewUtil:: makeViewWithBreadcrumbsForCurrentUser( $this, new ReportWizardTypesGridView(), $breadCrumbLinks, 'ReportBreadCrumbView')); echo $view->render(); } public function actionCreate($type = null) { if ($type == null) { $this->actionSelectType(); Yii::app()->end(0, false); } $breadCrumbLinks = array(Zurmo::t('Core', 'Create')); assert('is_string($type)'); $report = new Report(); $report->setType($type); $progressBarAndStepsView = ReportWizardViewFactory::makeStepsAndProgressBarViewFromReport($report); $reportWizardView = ReportWizardViewFactory::makeViewFromReport($report); $view = new ReportsPageView(ZurmoDefaultViewUtil:: makeTwoViewsWithBreadcrumbsForCurrentUser( $this, $progressBarAndStepsView, $reportWizardView, $breadCrumbLinks, 'ReportBreadCrumbView')); echo $view->render(); } public function actionEdit($id, $isBeingCopied = false) { $savedReport = SavedReport::getById((int)$id); ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName); if (!$isBeingCopied) { ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($savedReport); } $breadCrumbLinks = array(strval($savedReport)); $report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport); $progressBarAndStepsView = ReportWizardViewFactory::makeStepsAndProgressBarViewFromReport($report); $reportWizardView = ReportWizardViewFactory::makeViewFromReport($report, (bool)$isBeingCopied); $view = new ReportsPageView(ZurmoDefaultViewUtil:: makeTwoViewsWithBreadcrumbsForCurrentUser( $this, $progressBarAndStepsView, $reportWizardView, $breadCrumbLinks, 'ReportBreadCrumbView')); echo $view->render(); } public function actionSave($type, $id = null, $isBeingCopied = false) { $postData = PostUtil::getData(); $savedReport = null; $report = null; $this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied); $reportToWizardFormAdapter = new ReportToWizardFormAdapter($report); $model = $reportToWizardFormAdapter->makeFormByType(); if (isset($postData['ajax']) && $postData['ajax'] === 'edit-form') { $errorData = ReportUtil::validateReportWizardForm($postData, $model); echo CJSON::encode($errorData); Yii::app()->end(0, false); } $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil:: resolveByPostDataAndModelThenMake($postData[get_class($model)], $savedReport); SavedReportToReportAdapter::resolveReportToSavedReport($report, $savedReport); if ($savedReport->id > 0) { ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName); } ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($savedReport); if ($savedReport->save()) { StickyReportUtil::clearDataByKey($savedReport->id); if ($explicitReadWriteModelPermissions != null) { ExplicitReadWriteModelPermissionsUtil::resolveExplicitReadWriteModelPermissions($savedReport, $explicitReadWriteModelPermissions); } //i can do a safety check on perms, then do flash here, on the jscript we can go to list instead and this should come up... //make sure you add to list of things to test. $redirectToList = $this->resolveAfterSaveHasPermissionsProblem($savedReport, $postData[get_class($model)]['name']); echo CJSON::encode(array('id' => $savedReport->id, 'redirectToList' => $redirectToList)); Yii::app()->end(0, false); } else { throw new FailedToSaveModelException(); } } public function actionRelationsAndAttributesTree($type, $treeType, $id = null, $nodeId = null, $isBeingCopied = false) { $postData = PostUtil::getData(); $savedReport = null; $report = null; $this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied); if ($nodeId != null) { $reportToTreeAdapter = new ReportRelationsAndAttributesToTreeAdapter($report, $treeType); echo ZurmoTreeView::saveDataAsJson($reportToTreeAdapter->getData($nodeId)); Yii::app()->end(0, false); } $view = new ReportRelationsAndAttributesTreeView($type, $treeType, 'edit-form'); $content = $view->render(); Yii::app()->getClientScript()->setToAjaxMode(); Yii::app()->getClientScript()->render($content); echo $content; } public function actionAddAttributeFromTree($type, $treeType, $nodeId, $rowNumber, $trackableStructurePosition = false, $id = null, $isBeingCopied = false) { $postData = PostUtil::getData(); $savedReport = null; $report = null; $this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied); ReportUtil::processAttributeAdditionFromTree($nodeId, $treeType, $report, $rowNumber, $trackableStructurePosition); } public function actionGetAvailableSeriesAndRangesForChart($type, $id = null, $isBeingCopied = false) { $postData = PostUtil::getData(); $savedReport = null; $report = null; $this->resolveSavedReportAndReportByPostData($postData, $savedReport, $report, $type, $id, (bool)$isBeingCopied); $moduleClassName = $report->getModuleClassName(); $modelClassName = $moduleClassName::getPrimaryModelName(); $modelToReportAdapter = ModelRelationsAndAttributesToReportAdapter:: make($moduleClassName, $modelClassName, $report->getType()); if (!$modelToReportAdapter instanceof ModelRelationsAndAttributesToSummationReportAdapter) { throw new NotSupportedException(); } $seriesAttributesData = $modelToReportAdapter-> getAttributesForChartSeries($report->getGroupBys(), $report->getDisplayAttributes()); $rangeAttributesData = $modelToReportAdapter-> getAttributesForChartRange ($report->getDisplayAttributes()); $dataAndLabels = array(); $dataAndLabels['firstSeriesDataAndLabels'] = array('' => Zurmo::t('Core', '(None)')); $dataAndLabels['firstSeriesDataAndLabels'] = array_merge($dataAndLabels['firstSeriesDataAndLabels'], ReportUtil::makeDataAndLabelsForSeriesOrRange($seriesAttributesData)); $dataAndLabels['firstRangeDataAndLabels'] = array('' => Zurmo::t('Core', '(None)')); $dataAndLabels['firstRangeDataAndLabels'] = array_merge($dataAndLabels['firstRangeDataAndLabels'], ReportUtil::makeDataAndLabelsForSeriesOrRange($rangeAttributesData)); $dataAndLabels['secondSeriesDataAndLabels'] = array('' => Zurmo::t('Core', '(None)')); $dataAndLabels['secondSeriesDataAndLabels'] = array_merge($dataAndLabels['secondSeriesDataAndLabels'], ReportUtil::makeDataAndLabelsForSeriesOrRange($seriesAttributesData)); $dataAndLabels['secondRangeDataAndLabels'] = array('' => Zurmo::t('Core', '(None)')); $dataAndLabels['secondRangeDataAndLabels'] = array_merge($dataAndLabels['secondRangeDataAndLabels'], ReportUtil::makeDataAndLabelsForSeriesOrRange($rangeAttributesData)); echo CJSON::encode($dataAndLabels); } public function actionApplyRuntimeFilters($id) { $postData = PostUtil::getData(); $savedReport = SavedReport::getById((int)$id); ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport); $report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport); $wizardFormClassName = ReportToWizardFormAdapter::getFormClassNameByType($report->getType()); if (!isset($postData[$wizardFormClassName])) { throw new NotSupportedException(); } DataToReportUtil::resolveFilters($postData[$wizardFormClassName], $report, true); if (isset($postData['ajax']) && $postData['ajax'] == 'edit-form') { $adapter = new ReportToWizardFormAdapter($report); $reportWizardForm = $adapter->makeFormByType(); $reportWizardForm->setScenario(reportWizardForm::FILTERS_VALIDATION_SCENARIO); if (!$reportWizardForm->validate()) { $errorData = array(); foreach ($reportWizardForm->getErrors() as $attribute => $errors) { $errorData[ZurmoHtml::activeId($reportWizardForm, $attribute)] = $errors; } echo CJSON::encode($errorData); Yii::app()->end(0, false); } } $filtersData = ArrayUtil::getArrayValue($postData[$wizardFormClassName], ComponentForReportForm::TYPE_FILTERS); $sanitizedFiltersData = DataToReportUtil::sanitizeFiltersData($report->getModuleClassName(), $report->getType(), $filtersData); $stickyData = array(ComponentForReportForm::TYPE_FILTERS => $sanitizedFiltersData); StickyReportUtil::setDataByKeyAndData($report->getId(), $stickyData); } public function actionResetRuntimeFilters($id) { $savedReport = SavedReport::getById((int)$id); ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport); $report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport); StickyReportUtil::clearDataByKey($report->getId()); } public function actionDelete($id) { $savedReport = SavedReport::GetById(intval($id)); ControllerSecurityUtil::resolveAccessCanCurrentUserDeleteModel($savedReport); $savedReport->delete(); $this->redirect(array($this->getId() . '/index')); } public function actionDrillDownDetails($id, $rowId) { $savedReport = SavedReport::getById((int)$id); ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport, true); $report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport); $report->resolveGroupBysAsFilters(GetUtil::getData()); if (null != $stickyData = StickyReportUtil::getDataByKey($report->id)) { StickyReportUtil::resolveStickyDataToReport($report, $stickyData); } $pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType( 'reportResultsSubListPageSize', get_class($this->getModule())); $dataProvider = ReportDataProviderFactory::makeForSummationDrillDown($report, $pageSize); $dataProvider->setRunReport(true); $view = new SummationDrillDownReportResultsGridView('default', 'reports', $dataProvider, $rowId); $content = $view->render(); Yii::app()->getClientScript()->setToAjaxMode(); Yii::app()->getClientScript()->render($content); echo $content; } public function actionExport($id, $stickySearchKey = null) { assert('$stickySearchKey == null || is_string($stickySearchKey)'); $savedReport = SavedReport::getById((int)$id); ControllerSecurityUtil::resolveCanCurrentUserAccessModule($savedReport->moduleClassName); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($savedReport); $report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport); $dataProvider = $this->getDataProviderForExport($report, $report->getId(), false); $totalItems = intval($dataProvider->calculateTotalItemCount()); $data = array(); if ($totalItems > 0) { if ($totalItems <= ExportModule::$asynchronousThreshold) { // Output csv file directly to user browser if ($dataProvider) { $reportToExportAdapter = ReportToExportAdapterFactory::createReportToExportAdapter($report, $dataProvider); $headerData = $reportToExportAdapter->getHeaderData(); $data = $reportToExportAdapter->getData(); } // Output data if (count($data)) { $fileName = $this->getModule()->getName() . ".csv"; ExportItemToCsvFileUtil::export($data, $headerData, $fileName, true); } else { Yii::app()->user->setFlash('notification', Zurmo::t('ZurmoModule', 'There is no data to export.') ); } } else { if ($dataProvider) { $serializedData = ExportUtil::getSerializedDataForExport($dataProvider); } // Create background job $exportItem = new ExportItem(); $exportItem->isCompleted = 0; $exportItem->exportFileType = 'csv'; $exportItem->exportFileName = $this->getModule()->getName(); $exportItem->modelClassName = 'SavedReport'; $exportItem->serializedData = $serializedData; $exportItem->save(); $exportItem->forget(); Yii::app()->user->setFlash('notification', Zurmo::t('ZurmoModule', 'A large amount of data has been requested for export. You will receive ' . 'a notification with the download link when the export is complete.') ); } } else { Yii::app()->user->setFlash('notification', Zurmo::t('ZurmoModule', 'There is no data to export.') ); } $this->redirect(array($this->getId() . '/index')); } public function actionModalList($stateMetadataAdapterClassName = null) { $modalListLinkProvider = new SelectFromRelatedEditModalListLinkProvider( $_GET['modalTransferInformation']['sourceIdFieldId'], $_GET['modalTransferInformation']['sourceNameFieldId'], $_GET['modalTransferInformation']['modalId'] ); echo ModalSearchListControllerUtil:: setAjaxModeAndRenderModalSearchList($this, $modalListLinkProvider, $stateMetadataAdapterClassName); } public function actionAutoComplete($term, $moduleClassName = null, $type = null, $autoCompleteOptions = null) { $pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType( 'autoCompleteListPageSize', get_class($this->getModule())); $autoCompleteResults = ReportAutoCompleteUtil::getByPartialName($term, $pageSize, $moduleClassName, $type, $autoCompleteOptions); echo CJSON::encode($autoCompleteResults); } protected function resolveCanCurrentUserAccessReports() { if (!RightsUtil::doesUserHaveAllowByRightName('ReportsModule', ReportsModule::RIGHT_CREATE_REPORTS, Yii::app()->user->userModel)) { $messageView = new AccessFailureView(); $view = new AccessFailurePageView($messageView); echo $view->render(); Yii::app()->end(0, false); } return true; } protected function resolveSavedReportAndReportByPostData(Array $postData, & $savedReport, & $report, $type, $id = null, $isBeingCopied = false) { if ($id == null) { $this->resolveCanCurrentUserAccessReports(); $savedReport = new SavedReport(); $report = new Report(); $report->setType($type); } elseif ($isBeingCopied) { $savedReport = new SavedReport(); $oldReport = SavedReport::getById(intval($id)); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($oldReport); ZurmoCopyModelUtil::copy($oldReport, $savedReport); $report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport); } else { $savedReport = SavedReport::getById(intval($id)); ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($savedReport); $report = SavedReportToReportAdapter::makeReportBySavedReport($savedReport); } DataToReportUtil::resolveReportByWizardPostData($report, $postData, ReportToWizardFormAdapter::getFormClassNameByType($type)); } protected function resolveAfterSaveHasPermissionsProblem(SavedReport $savedReport, $modelToStringValue) { assert('is_string($modelToStringValue)'); if (ControllerSecurityUtil::doesCurrentUserHavePermissionOnSecurableItem($savedReport, Permission::READ)) { return false; } else { $notificationContent = Zurmo::t( 'ReportsModule', 'You no longer have permissions to access {modelName}.', array('{modelName}' => $modelToStringValue) ); Yii::app()->user->setFlash('notification', $notificationContent); return true; } } protected function makeReportDetailsAndRelationsView(SavedReport $savedReport, $redirectUrl, ReportBreadCrumbView $breadCrumbView) { $reportDetailsAndRelationsView = ReportDetailsAndResultsViewFactory::makeView($savedReport, $this->getId(), $this->getModule()->getId(), $redirectUrl); $gridView = new GridView(2, 1); $gridView->setView($breadCrumbView, 0, 0); $gridView->setView($reportDetailsAndRelationsView, 1, 0); return $gridView; } protected function getDataProviderForExport(Report $report, $stickyKey, $runReport) { assert('is_string($stickyKey) || is_int($stickyKey)'); assert('is_bool($runReport)'); if (null != $stickyData = StickyReportUtil::getDataByKey($stickyKey)) { StickyReportUtil::resolveStickyDataToReport($report, $stickyData); } $pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType( 'reportResultsListPageSize', get_class($this->getModule())); $dataProvider = ReportDataProviderFactory::makeByReport($report, $pageSize); if (!($dataProvider instanceof MatrixReportDataProvider)) { $totalItems = intval($dataProvider->calculateTotalItemCount()); $dataProvider->getPagination()->setPageSize($totalItems); } if ($runReport) { $dataProvider->setRunReport($runReport); } return $dataProvider; } protected function resolveMetadataBeforeMakingDataProvider(& $metadata) { $metadata = SavedReportUtil::resolveSearchAttributeDataByModuleClassNames($metadata, Report::getReportableModulesClassNamesCurrentUserHasAccessTo()); } } ?>
Java
<%page expression_filter="h"/> <%inherit file="../main.html" /> <%! from django.utils.translation import ugettext as _ from django.urls import reverse from openedx.core.djangolib.js_utils import js_escaped_string from openedx.core.djangolib.markup import HTML, Text %> <%block name="bodyclass">register verification-process step-select-track</%block> <%block name="pagetitle"> ${_("Enroll In {course_name} | Choose Your Track").format(course_name=course_name)} </%block> <%block name="js_extra"> <script type="text/javascript"> var expandCallback = function(event) { event.preventDefault(); $(this).next('.expandable-area').slideToggle(); var title = $(this).parent(); title.toggleClass('is-expanded'); if (title.attr("aria-expanded") === "false") { title.attr("aria-expanded", "true"); } else { title.attr("aria-expanded", "false"); } }; $(document).ready(function() { $('.expandable-area').slideUp(); $('.is-expandable').addClass('is-ready'); $('.is-expandable .title-expand').click(expandCallback); $('.is-expandable .title-expand').keypress(function(e) { if (e.which == 13) { // only activate on pressing enter expandCallback.call(this, e); // make sure that we bind `this` correctly } }); $('#contribution-other-amt').focus(function() { $('#contribution-other').attr('checked',true); }); % if use_ecommerce_payment_flow: $('input[name=verified_mode]').click(function(e){ e.preventDefault(); window.location.href = '${ecommerce_payment_page | n, js_escaped_string}?sku=' + encodeURIComponent('${sku | n, js_escaped_string}'); }); % endif }); </script> </%block> <%block name="content"> % if error: <div class="wrapper-msg wrapper-msg-error"> <div class=" msg msg-error"> <span class="msg-icon icon fa fa-exclamation-triangle" aria-hidden="true"></span> <div class="msg-content"> <h3 class="title">${_("Sorry, there was an error when trying to enroll you")}</h3> <div class="copy"> <p>${error}</p> </div> </div> </div> </div> %endif <div class="container"> <section class="wrapper"> <div class="wrapper-register-choose wrapper-content-main"> <article class="register-choose content-main"> <header class="page-header content-main"> <h3 class="title"> ${title_content} </h3> </header> <form class="form-register-choose" method="post" name="enrollment_mode_form" id="enrollment_mode_form"> <% b_tag_kwargs = {'b_start': HTML('<b>'), 'b_end': HTML('</b>')} %> % if "verified" in modes: <div class="register-choice register-choice-certificate"> <div class="wrapper-copy"> <span class="deco-ribbon"></span> % if has_credit_upsell: % if content_gating_enabled or course_duration_limit_enabled: <h4 class="title">${_("Pursue Academic Credit with the Verified Track")}</h4> % else: <h4 class="title">${_("Pursue Academic Credit with a Verified Certificate")}</h4> % endif <div class="copy"> <p>${_("Become eligible for academic credit and highlight your new skills and knowledge with a verified certificate. Use this valuable credential to qualify for academic credit, advance your career, or strengthen your school applications.")}</p> <p> <div class="wrapper-copy-inline"> <div class="copy-inline"> % if content_gating_enabled or course_duration_limit_enabled: <h4>${_("Benefits of the Verified Track")}</h4> <ul> <li>${Text(_("{b_start}Eligible for credit:{b_end} Receive academic credit after successfully completing the course")).format(**b_tag_kwargs)}</li> % if course_duration_limit_enabled: <li>${Text(_("{b_start}Unlimited Course Access: {b_end}Learn at your own pace, and access materials anytime to brush up on what you've learned.")).format(**b_tag_kwargs)}</li> % endif % if content_gating_enabled: <li>${Text(_("{b_start}Graded Assignments: {b_end}Build your skills through graded assignments and projects.")).format(**b_tag_kwargs)}</li> % endif <li>${Text(_("{b_start}Easily Sharable: {b_end}Add the certificate to your CV or resume, or post it directly on LinkedIn.")).format(**b_tag_kwargs)}</li> </ul> % else: <h4>${_("Benefits of a Verified Certificate")}</h4> <ul> <li>${Text(_("{b_start}Eligible for credit:{b_end} Receive academic credit after successfully completing the course")).format(**b_tag_kwargs)}</li> <li>${Text(_("{b_start}Official:{b_end} Receive an instructor-signed certificate with the institution's logo")).format(**b_tag_kwargs)}</li> <li>${Text(_("{b_start}Easily shareable:{b_end} Add the certificate to your CV or resume, or post it directly on LinkedIn")).format(**b_tag_kwargs)}</li> </ul> % endif </div> <div class="copy-inline list-actions"> <ul class="list-actions"> <li class="action action-select"> <input type="hidden" name="contribution" value="${min_price}" /> <input type="submit" name="verified_mode" value="${_('Pursue a Verified Certificate')} ($${min_price} USD)" /> </li> </ul> </div> </div> </p> </div> % else: % if content_gating_enabled or course_duration_limit_enabled: <h4 class="title">${_("Pursue the Verified Track")}</h4> % else: <h4 class="title">${_("Pursue a Verified Certificate")}</h4> % endif <div class="copy"> <p>${_("Highlight your new knowledge and skills with a verified certificate. Use this valuable credential to improve your job prospects and advance your career, or highlight your certificate in school applications.")}</p> <p> <div class="wrapper-copy-inline"> <div class="copy-inline"> % if content_gating_enabled or course_duration_limit_enabled: <h4>${_("Benefits of the Verified Track")}</h4> <ul> % if course_duration_limit_enabled: <li>${Text(_("{b_start}Unlimited Course Access: {b_end}Learn at your own pace, and access materials anytime to brush up on what you've learned.")).format(**b_tag_kwargs)}</li> % endif % if content_gating_enabled: <li>${Text(_("{b_start}Graded Assignments: {b_end}Build your skills through graded assignments and projects.")).format(**b_tag_kwargs)}</li> % endif <li>${Text(_("{b_start}Easily Sharable: {b_end}Add the certificate to your CV or resume, or post it directly on LinkedIn.")).format(**b_tag_kwargs)}</li> </ul> % else: <h4>${_("Benefits of a Verified Certificate")}</h4> <ul> <li>${Text(_("{b_start}Official: {b_end}Receive an instructor-signed certificate with the institution's logo")).format(**b_tag_kwargs)}</li> <li>${Text(_("{b_start}Easily shareable: {b_end}Add the certificate to your CV or resume, or post it directly on LinkedIn")).format(**b_tag_kwargs)}</li> <li>${Text(_("{b_start}Motivating: {b_end}Give yourself an additional incentive to complete the course")).format(**b_tag_kwargs)}</li> </ul> % endif </div> <div class="copy-inline list-actions"> <ul class="list-actions"> <li class="action action-select"> <input type="hidden" name="contribution" value="${min_price}" /> % if content_gating_enabled or course_duration_limit_enabled: <input type="submit" name="verified_mode" value="${_('Pursue the Verified Track')} ($${min_price} USD)" /> % else: <input type="submit" name="verified_mode" value="${_('Pursue a Verified Certificate')} ($${min_price} USD)" /> % endif </li> </ul> </div> </div> </p> </div> % endif </div> </div> % endif % if "honor" in modes: <span class="deco-divider"> <span class="copy">${_("or")}</span> </span> <div class="register-choice register-choice-audit"> <div class="wrapper-copy"> <span class="deco-ribbon"></span> <h4 class="title">${_("Audit This Course")}</h4> <div class="copy"> <p>${_("Audit this course for free and have complete access to all the course material, activities, tests, and forums.")}</p> </div> </div> <ul class="list-actions"> <li class="action action-select"> <input type="submit" name="honor_mode" value="${_('Audit This Course')}" /> </li> </ul> </div> % elif "audit" in modes: <span class="deco-divider"> <span class="copy">${_("or")}</span> </span> <div class="register-choice register-choice-audit"> <div class="wrapper-copy"> <span class="deco-ribbon"></span> <h4 class="title">${_("Audit This Course (No Certificate)")}</h4> <div class="copy"> ## Translators: b_start notes the beginning of a section of text bolded for emphasis, and b_end marks the end of the bolded text. % if content_gating_enabled and course_duration_limit_enabled: <p>${Text(_("Audit this course for free and have access to course materials and discussions forums. {b_start}This track does not include graded assignments, or unlimited course access.{b_end}")).format(**b_tag_kwargs)}</p> % elif content_gating_enabled and not course_duration_limit_enabled: <p>${Text(_("Audit this course for free and have access to course materials and discussions forums. {b_start}This track does not include graded assignments.{b_end}")).format(**b_tag_kwargs)}</p> % elif not content_gating_enabled and course_duration_limit_enabled: <p>${Text(_("Audit this course for free and have access to course materials and discussions forums. {b_start}This track does not include unlimited course access.{b_end}")).format(**b_tag_kwargs)}</p> % else: <p>${Text(_("Audit this course for free and have complete access to all the course material, activities, tests, and forums. {b_start}Please note that this track does not offer a certificate for learners who earn a passing grade.{b_end}")).format(**b_tag_kwargs)}</p> % endif </div> </div> <ul class="list-actions"> <li class="action action-select"> <input type="submit" name="audit_mode" value="${_('Audit This Course')}" /> </li> </ul> </div> % endif <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }"> </form> </article> </div> <!-- /wrapper-content-main --> </section> </div> </%block>
Java