text
stringlengths
2
100k
meta
dict
<?xml version="1.0" encoding="ISO-8859-1"?> <aiml> <!-- Battledome.aiml --> <!-- Free software (c)2008 Square Bear --> <!-- This program is open source code released under --> <!-- the terms of the GNU General Public License --> <!-- as published by the Free Software Foundation. --> <!-- Complies with AIML 1.0 Tag Set Specification --> <!-- as adopted by the ALICE A.I. Foundation. --> <!-- A combat system for use in adventures --> <category> <pattern>BATTLEDOME</pattern> <template> <think> <set name="energy">50</set> <set name="topic">BATTLEDOME</set> </think> Welcome to the Battledome.<br/><br/>You have<get name="energy"/>energy points and your enemy has<srai>GETNEWENEMY</srai>points<br/>Type FIGHT to begin your fight against the<get name="enemytype"/>that blocks your path.</template> </category> <topic name="BATTLEDOME"> <category> <pattern>FIGHT</pattern> <template> <random> <li>You strike out at the<get name="enemytype"/>and hit him straight on his head. The<get name="enemytype"/>loses 10 HP.<think><set name="result">ENEMYLOSE10</set></think></li> <li>You strike out at the<get name="enemytype"/>. The<get name="enemytype"/>is quick but you manage to hit his shoulder. The<get name="enemytype"/>loses 5 HP.<think><set name="result">ENEMYLOSE5</set></think></li> <li>You strike out at the<get name="enemytype"/>but he is too quick and manages to avoid you.<think><set name="result">0</set></think></li> <li>You strike out at the<get name="enemytype"/>. The<get name="enemytype"/>sees you and hits your leg. You lose 5 HP.<think><set name="result">PLAYERLOSE5</set></think></li> <li>You fumble for your sword and in your panic, the<get name="enemytype"/>lashes out at your head. You lose 10 HP.<think><set name="result">PLAYERLOSE10</set></think></li> <li>The<get name="enemytype"/>reaches out for you but you hide in a corner. Hey you found an energy potion! You gain 5 HP.<think><set name="result">PLAYERGAIN5</set></think></li> <li>You trip as you go for the<get name="enemytype"/>. Lose 2 HP.<think><set name="result">PLAYERLOSE2</set></think></li> </random> <think> <condition name="result"> <li value="ENEMYLOSE10"><srai>ENEMYLOSE5</srai><srai>ENEMYLOSE5</srai></li> <li value="ENEMYLOSE5"><srai>ENEMYLOSE5</srai></li> <li value="PLAYERLOSE5"><srai>PLAYERLOSE5</srai></li> <li value="PLAYERLOSE10"><srai>PLAYERLOSE5</srai><srai>PLAYERLOSE5</srai></li> <li value="PLAYERGAIN5"><srai>PLAYERGAIN5</srai></li> <li value="PLAYERLOSE2"><srai>XKILLPLAYER</srai><srai>XKILLPLAYER</srai></li> </condition> </think> <br/><br/>Your energy:<get name="energy"/>.<br/>Enemy's energy:<get name="enemy"/>. <condition name="energy"> <li value="DEAD"><br/><br/>You have died. The monsters escape from the Battledome. Thanks for playing.</li> </condition> <condition name="enemy"> <li value="DEAD"><srai>NEXTBATTLE</srai></li> </condition> </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>NEXTBATTLE</pattern> <template> <think> <srai>PLAYERGAIN5</srai> </think> <br/><br/>You have defeated the<get name="enemytype"/>. You rest for a while and regain 5 energy points.<br/><br/> After a short rest, you walk further into the Battledome and meet a new enemy.<br/> His energy is<srai>GETNEWENEMY</srai>and yours is<get name="energy"/>. Type FIGHT to fight the<get name="enemytype"/>you now see before you. </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>ENEMYLOSE5</pattern> <template> <think> <srai>XKILLENEMY</srai> <srai>XKILLENEMY</srai> <srai>XKILLENEMY</srai> <srai>XKILLENEMY</srai> <srai>XKILLENEMY</srai> </think> </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>PLAYERLOSE5</pattern> <template> <think> <srai>XKILLPLAYER</srai> <srai>XKILLPLAYER</srai> <srai>XKILLPLAYER</srai> <srai>XKILLPLAYER</srai> <srai>XKILLPLAYER</srai> </think> </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>PLAYERGAIN5</pattern> <template> <think> <srai>XPLAYERGAIN</srai> <srai>XPLAYERGAIN</srai> <srai>XPLAYERGAIN</srai> <srai>XPLAYERGAIN</srai> <srai>XPLAYERGAIN</srai> </think> </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>GETNEWENEMY</pattern> <template> <random> <li><set name="enemy">30</set></li> <li><set name="enemy">25</set></li> <li><set name="enemy">22</set></li> <li><set name="enemy">20</set></li> <li><set name="enemy">17</set></li> <li><set name="enemy">4</set></li> </random> <think> <random> <li><set name="enemytype">troll</set></li> <li><set name="enemytype">shapeshifter</set></li> <li><set name="enemytype">crazy elf</set></li> <li><set name="enemytype">dragon</set></li> <li><set name="enemytype">mad wizard</set></li> <li><set name="enemytype">dwarf</set></li> <li><set name="enemytype">snake</set></li> <li><set name="enemytype">ghost</set></li> <li><set name="enemytype">vampire</set></li> <li><set name="enemytype">werewolf</set></li> <li><set name="enemytype">evil goblin</set></li> <li><set name="enemytype">demon</set></li> <li><set name="enemytype">spectre</set></li> <li><set name="enemytype">ogre</set></li> <li><set name="enemytype">fire spirit</set></li> </random> </think> </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>XKILLENEMY</pattern> <template> <think> <condition name="enemy"> <li value="30"><set name="enemy">29</set></li> <li value="29"><set name="enemy">28</set></li> <li value="28"><set name="enemy">27</set></li> <li value="27"><set name="enemy">26</set></li> <li value="26"><set name="enemy">25</set></li> <li value="25"><set name="enemy">24</set></li> <li value="24"><set name="enemy">23</set></li> <li value="23"><set name="enemy">22</set></li> <li value="22"><set name="enemy">21</set></li> <li value="21"><set name="enemy">20</set></li> <li value="20"><set name="enemy">19</set></li> <li value="19"><set name="enemy">18</set></li> <li value="18"><set name="enemy">17</set></li> <li value="17"><set name="enemy">16</set></li> <li value="16"><set name="enemy">15</set></li> <li value="15"><set name="enemy">14</set></li> <li value="14"><set name="enemy">13</set></li> <li value="13"><set name="enemy">12</set></li> <li value="12"><set name="enemy">11</set></li> <li value="11"><set name="enemy">10</set></li> <li value="10"><set name="enemy">9</set></li> <li value="9"><set name="enemy">8</set></li> <li value="8"><set name="enemy">7</set></li> <li value="7"><set name="enemy">6</set></li> <li value="6"><set name="enemy">5</set></li> <li value="5"><set name="enemy">4</set></li> <li value="4"><set name="enemy">3</set></li> <li value="3"><set name="enemy">2</set></li> <li value="2"><set name="enemy">1</set></li> <li value="1"><set name="enemy">DEAD</set></li> </condition> </think> </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>XKILLPLAYER</pattern> <template> <think> <condition name="energy"> <li value="50"><set name="energy">49</set></li> <li value="49"><set name="energy">48</set></li> <li value="48"><set name="energy">47</set></li> <li value="47"><set name="energy">46</set></li> <li value="46"><set name="energy">45</set></li> <li value="45"><set name="energy">44</set></li> <li value="44"><set name="energy">43</set></li> <li value="43"><set name="energy">42</set></li> <li value="42"><set name="energy">41</set></li> <li value="41"><set name="energy">40</set></li> <li value="40"><set name="energy">39</set></li> <li value="39"><set name="energy">38</set></li> <li value="38"><set name="energy">37</set></li> <li value="37"><set name="energy">36</set></li> <li value="36"><set name="energy">35</set></li> <li value="35"><set name="energy">34</set></li> <li value="34"><set name="energy">33</set></li> <li value="33"><set name="energy">32</set></li> <li value="32"><set name="energy">31</set></li> <li value="31"><set name="energy">30</set></li> <li value="30"><set name="energy">29</set></li> <li value="29"><set name="energy">28</set></li> <li value="28"><set name="energy">27</set></li> <li value="27"><set name="energy">26</set></li> <li value="26"><set name="energy">25</set></li> <li value="25"><set name="energy">24</set></li> <li value="24"><set name="energy">23</set></li> <li value="23"><set name="energy">22</set></li> <li value="22"><set name="energy">21</set></li> <li value="21"><set name="energy">20</set></li> <li value="20"><set name="energy">19</set></li> <li value="19"><set name="energy">18</set></li> <li value="18"><set name="energy">17</set></li> <li value="17"><set name="energy">16</set></li> <li value="16"><set name="energy">15</set></li> <li value="15"><set name="energy">14</set></li> <li value="14"><set name="energy">13</set></li> <li value="13"><set name="energy">12</set></li> <li value="12"><set name="energy">11</set></li> <li value="11"><set name="energy">10</set></li> <li value="10"><set name="energy">9</set></li> <li value="9"><set name="energy">8</set></li> <li value="8"><set name="energy">7</set></li> <li value="7"><set name="energy">6</set></li> <li value="6"><set name="energy">5</set></li> <li value="5"><set name="energy">4</set></li> <li value="4"><set name="energy">3</set></li> <li value="3"><set name="energy">2</set></li> <li value="2"><set name="energy">1</set></li> <li value="1"><set name="energy">DEAD</set></li> </condition> </think> </template> </category> </topic> <topic name="BATTLEDOME"> <category> <pattern>XPLAYERGAIN</pattern> <template> <think> <condition name="energy"> <li value="1"><set name="energy">2</set></li> <li value="2"><set name="energy">3</set></li> <li value="3"><set name="energy">4</set></li> <li value="4"><set name="energy">5</set></li> <li value="5"><set name="energy">6</set></li> <li value="6"><set name="energy">7</set></li> <li value="7"><set name="energy">8</set></li> <li value="8"><set name="energy">9</set></li> <li value="9"><set name="energy">10</set></li> <li value="10"><set name="energy">21</set></li> <li value="11"><set name="energy">12</set></li> <li value="12"><set name="energy">13</set></li> <li value="13"><set name="energy">14</set></li> <li value="14"><set name="energy">15</set></li> <li value="15"><set name="energy">16</set></li> <li value="16"><set name="energy">17</set></li> <li value="17"><set name="energy">18</set></li> <li value="18"><set name="energy">19</set></li> <li value="19"><set name="energy">20</set></li> <li value="20"><set name="energy">21</set></li> <li value="21"><set name="energy">22</set></li> <li value="22"><set name="energy">23</set></li> <li value="23"><set name="energy">24</set></li> <li value="24"><set name="energy">25</set></li> <li value="25"><set name="energy">26</set></li> <li value="26"><set name="energy">27</set></li> <li value="27"><set name="energy">28</set></li> <li value="28"><set name="energy">29</set></li> <li value="29"><set name="energy">30</set></li> <li value="30"><set name="energy">31</set></li> <li value="31"><set name="energy">32</set></li> <li value="32"><set name="energy">33</set></li> <li value="33"><set name="energy">34</set></li> <li value="34"><set name="energy">35</set></li> <li value="35"><set name="energy">36</set></li> <li value="36"><set name="energy">37</set></li> <li value="37"><set name="energy">38</set></li> <li value="38"><set name="energy">39</set></li> <li value="39"><set name="energy">40</set></li> <li value="40"><set name="energy">41</set></li> <li value="41"><set name="energy">42</set></li> <li value="42"><set name="energy">43</set></li> <li value="43"><set name="energy">44</set></li> <li value="44"><set name="energy">45</set></li> <li value="45"><set name="energy">46</set></li> <li value="46"><set name="energy">47</set></li> <li value="47"><set name="energy">48</set></li> <li value="48"><set name="energy">49</set></li> <li value="49"><set name="energy">50</set></li> </condition> </think> </template> </category> </topic> </aiml>
{ "pile_set_name": "Github" }
package mekanism.api.datagen.recipe.builder; import com.google.gson.JsonObject; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import mcp.MethodsReturnNonnullByDefault; import mekanism.api.JsonConstants; import mekanism.api.SerializerHelper; import mekanism.api.annotations.FieldsAreNonnullByDefault; import mekanism.api.chemical.gas.GasStack; import mekanism.api.datagen.recipe.MekanismRecipeBuilder; import mekanism.api.recipes.inputs.chemical.GasStackIngredient; import net.minecraft.util.ResourceLocation; @FieldsAreNonnullByDefault @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class ChemicalInfuserRecipeBuilder extends MekanismRecipeBuilder<ChemicalInfuserRecipeBuilder> { private final GasStackIngredient leftInput; private final GasStackIngredient rightInput; private final GasStack output; protected ChemicalInfuserRecipeBuilder(GasStackIngredient leftInput, GasStackIngredient rightInput, GasStack output) { super(mekSerializer("chemical_infusing")); this.leftInput = leftInput; this.rightInput = rightInput; this.output = output; } public static ChemicalInfuserRecipeBuilder chemicalInfusing(GasStackIngredient leftInput, GasStackIngredient rightInput, GasStack output) { if (output.isEmpty()) { throw new IllegalArgumentException("This chemical infusing recipe requires a non empty gas output."); } return new ChemicalInfuserRecipeBuilder(leftInput, rightInput, output); } @Override protected ChemicalInfuserRecipeResult getResult(ResourceLocation id) { return new ChemicalInfuserRecipeResult(id); } public class ChemicalInfuserRecipeResult extends RecipeResult { protected ChemicalInfuserRecipeResult(ResourceLocation id) { super(id); } @Override public void serialize(@Nonnull JsonObject json) { json.add(JsonConstants.LEFT_INPUT, leftInput.serialize()); json.add(JsonConstants.RIGHT_INPUT, rightInput.serialize()); json.add(JsonConstants.OUTPUT, SerializerHelper.serializeGasStack(output)); } } }
{ "pile_set_name": "Github" }
package com.fizzbuzz.android.dagger; /* * Copyright (C) 2007 The Guava Authors * * 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. */ /* * Note: this file was copied from Guava to cut down significantly on the library size, since we're only * using a small subset of Guava. */ public class Preconditions { /** * Ensures the truth of an expression involving the state of the calling * instance, but not involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will * be converted to a string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false */ public static void checkState( boolean expression, Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } }
{ "pile_set_name": "Github" }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.test.concurrency; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; import static org.junit.Assert.assertNull; import java.sql.Connection; import org.camunda.bpm.engine.CrdbTransactionRetryException; import org.camunda.bpm.engine.impl.BootstrapEngineCommand; import org.camunda.bpm.engine.impl.db.sql.DbSqlSessionFactory; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.test.RequiredDatabase; import org.camunda.bpm.engine.impl.test.TestHelper; import org.camunda.bpm.engine.test.util.DatabaseHelper; import org.junit.Before; import org.junit.Test; /** * <p>Tests cluster scenario with two nodes trying to write the installation id property in parallel.</p> * * <p><b>Note:</b> the test is not executed on H2 because it doesn't support the * exclusive lock on table.</p> * */ public class ConcurrentInstallationIdInitializationTest extends ConcurrencyTestCase { @Before public void setUp() { TestHelper.deleteInstallationId(processEngineConfiguration); } @Test @RequiredDatabase(excludes = {DbSqlSessionFactory.H2, DbSqlSessionFactory.MARIADB}) public void test() throws InterruptedException { Integer transactionIsolationLevel = DatabaseHelper.getTransactionIsolationLevel(processEngineConfiguration); assumeThat((transactionIsolationLevel != null && !transactionIsolationLevel.equals(Connection.TRANSACTION_READ_COMMITTED))); ThreadControl thread1 = executeControllableCommand(new ControllableInstallationIdInitializationCommand()); thread1.reportInterrupts(); thread1.waitForSync(); ThreadControl thread2 = executeControllableCommand(new ControllableInstallationIdInitializationCommand()); thread2.reportInterrupts(); thread2.waitForSync(); thread1.makeContinue(); thread1.waitForSync(); thread2.makeContinue(); Thread.sleep(2000); thread1.waitUntilDone(); thread2.waitForSync(); thread2.waitUntilDone(); assertNull(thread1.getException()); Throwable thread2Exception = thread2.getException(); if (testRule.isOptimisticLockingExceptionSuppressible()) { assertNull(thread2Exception); } else { // on CRDB, the pessimistic lock is disabled and the concurrent transaction // with fail with a CrdbTransactionRetryException and will need to be retried assertThat(thread2Exception).isInstanceOf(CrdbTransactionRetryException.class); } String id = processEngineConfiguration.getInstallationId(); assertThat(id).isNotEmpty(); assertThat(id).matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); } protected static class ControllableInstallationIdInitializationCommand extends ControllableCommand<Void> { public Void execute(CommandContext commandContext) { monitor.sync(); // thread will block here until makeContinue() is called form main thread new BootstrapEngineCommand().initializeInstallationId(commandContext); monitor.sync(); // thread will block here until waitUntilDone() is called form main thread return null; } } }
{ "pile_set_name": "Github" }
// boost/filesystem/operations.hpp ---------------------------------------------------// // Copyright Beman Dawes 2002-2009 // Copyright Jan Langer 2002 // Copyright Dietmar Kuehl 2001 // Copyright Vladimir Prus 2002 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // Library home page: http://www.boost.org/libs/filesystem //--------------------------------------------------------------------------------------// #ifndef BOOST_FILESYSTEM3_OPERATIONS_HPP #define BOOST_FILESYSTEM3_OPERATIONS_HPP #include <boost/config.hpp> # if defined( BOOST_NO_STD_WSTRING ) # error Configuration not supported: Boost.Filesystem V3 and later requires std::wstring support # endif #include <boost/filesystem/config.hpp> #include <boost/filesystem/path.hpp> #include <boost/detail/scoped_enum_emulation.hpp> #include <boost/detail/bitmask.hpp> #include <boost/system/error_code.hpp> #include <boost/system/system_error.hpp> #include <boost/shared_ptr.hpp> #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/cstdint.hpp> #include <boost/range/mutable_iterator.hpp> #include <boost/range/const_iterator.hpp> #include <boost/assert.hpp> #include <string> #include <utility> // for pair #include <ctime> #include <vector> #include <stack> #ifdef BOOST_WINDOWS_API # include <fstream> #endif #include <boost/config/abi_prefix.hpp> // must be the last #include //--------------------------------------------------------------------------------------// namespace boost { namespace filesystem { //--------------------------------------------------------------------------------------// // // // class filesystem_error // // // //--------------------------------------------------------------------------------------// class BOOST_SYMBOL_VISIBLE filesystem_error : public system::system_error { // see http://www.boost.org/more/error_handling.html for design rationale // all functions are inline to avoid issues with crossing dll boundaries // functions previously throw() are now BOOST_NOEXCEPT_OR_NOTHROW // functions previously without throw() are now BOOST_NOEXCEPT public: // compiler generates copy constructor and copy assignment filesystem_error( const std::string & what_arg, system::error_code ec) BOOST_NOEXCEPT : system::system_error(ec, what_arg) { try { m_imp_ptr.reset(new m_imp); } catch (...) { m_imp_ptr.reset(); } } filesystem_error( const std::string & what_arg, const path& path1_arg, system::error_code ec) BOOST_NOEXCEPT : system::system_error(ec, what_arg) { try { m_imp_ptr.reset(new m_imp); m_imp_ptr->m_path1 = path1_arg; } catch (...) { m_imp_ptr.reset(); } } filesystem_error( const std::string & what_arg, const path& path1_arg, const path& path2_arg, system::error_code ec) BOOST_NOEXCEPT : system::system_error(ec, what_arg) { try { m_imp_ptr.reset(new m_imp); m_imp_ptr->m_path1 = path1_arg; m_imp_ptr->m_path2 = path2_arg; } catch (...) { m_imp_ptr.reset(); } } ~filesystem_error() BOOST_NOEXCEPT_OR_NOTHROW{} const path& path1() const BOOST_NOEXCEPT { static const path empty_path; return m_imp_ptr.get() ? m_imp_ptr->m_path1 : empty_path; } const path& path2() const BOOST_NOEXCEPT { static const path empty_path; return m_imp_ptr.get() ? m_imp_ptr->m_path2 : empty_path; } const char* what() const BOOST_NOEXCEPT_OR_NOTHROW { if (!m_imp_ptr.get()) return system::system_error::what(); try { if (m_imp_ptr->m_what.empty()) { m_imp_ptr->m_what = system::system_error::what(); if (!m_imp_ptr->m_path1.empty()) { m_imp_ptr->m_what += ": \""; m_imp_ptr->m_what += m_imp_ptr->m_path1.string(); m_imp_ptr->m_what += "\""; } if (!m_imp_ptr->m_path2.empty()) { m_imp_ptr->m_what += ", \""; m_imp_ptr->m_what += m_imp_ptr->m_path2.string(); m_imp_ptr->m_what += "\""; } } return m_imp_ptr->m_what.c_str(); } catch (...) { return system::system_error::what(); } } private: struct m_imp { path m_path1; // may be empty() path m_path2; // may be empty() std::string m_what; // not built until needed }; boost::shared_ptr<m_imp> m_imp_ptr; }; //--------------------------------------------------------------------------------------// // file_type // //--------------------------------------------------------------------------------------// enum file_type { status_error, # ifndef BOOST_FILESYSTEM_NO_DEPRECATED status_unknown = status_error, # endif file_not_found, regular_file, directory_file, // the following may not apply to some operating systems or file systems symlink_file, block_file, character_file, fifo_file, socket_file, reparse_file, // Windows: FILE_ATTRIBUTE_REPARSE_POINT that is not a symlink type_unknown, // file does exist, but isn't one of the above types or // we don't have strong enough permission to find its type _detail_directory_symlink // internal use only; never exposed to users }; //--------------------------------------------------------------------------------------// // perms // //--------------------------------------------------------------------------------------// enum perms { no_perms = 0, // file_not_found is no_perms rather than perms_not_known // POSIX equivalent macros given in comments. // Values are from POSIX and are given in octal per the POSIX standard. // permission bits owner_read = 0400, // S_IRUSR, Read permission, owner owner_write = 0200, // S_IWUSR, Write permission, owner owner_exe = 0100, // S_IXUSR, Execute/search permission, owner owner_all = 0700, // S_IRWXU, Read, write, execute/search by owner group_read = 040, // S_IRGRP, Read permission, group group_write = 020, // S_IWGRP, Write permission, group group_exe = 010, // S_IXGRP, Execute/search permission, group group_all = 070, // S_IRWXG, Read, write, execute/search by group others_read = 04, // S_IROTH, Read permission, others others_write = 02, // S_IWOTH, Write permission, others others_exe = 01, // S_IXOTH, Execute/search permission, others others_all = 07, // S_IRWXO, Read, write, execute/search by others all_all = 0777, // owner_all|group_all|others_all // other POSIX bits set_uid_on_exe = 04000, // S_ISUID, Set-user-ID on execution set_gid_on_exe = 02000, // S_ISGID, Set-group-ID on execution sticky_bit = 01000, // S_ISVTX, // (POSIX XSI) On directories, restricted deletion flag // (V7) 'sticky bit': save swapped text even after use // (SunOS) On non-directories: don't cache this file // (SVID-v4.2) On directories: restricted deletion flag // Also see http://en.wikipedia.org/wiki/Sticky_bit perms_mask = 07777, // all_all|set_uid_on_exe|set_gid_on_exe|sticky_bit perms_not_known = 0xFFFF, // present when directory_entry cache not loaded // options for permissions() function add_perms = 0x1000, // adds the given permission bits to the current bits remove_perms = 0x2000, // removes the given permission bits from the current bits; // choose add_perms or remove_perms, not both; if neither add_perms // nor remove_perms is given, replace the current bits with // the given bits. symlink_perms = 0x4000 // on POSIX, don't resolve symlinks; implied on Windows }; BOOST_BITMASK(perms) //--------------------------------------------------------------------------------------// // file_status // //--------------------------------------------------------------------------------------// class BOOST_FILESYSTEM_DECL file_status { public: file_status() BOOST_NOEXCEPT : m_value(status_error), m_perms(perms_not_known) {} explicit file_status(file_type v) BOOST_NOEXCEPT : m_value(v), m_perms(perms_not_known) {} file_status(file_type v, perms prms) BOOST_NOEXCEPT : m_value(v), m_perms(prms) {} // As of October 2015 the interaction between noexcept and =default is so troublesome // for VC++, GCC, and probably other compilers, that =default is not used with noexcept // functions. GCC is not even consistent for the same release on different platforms. file_status(const file_status& rhs) BOOST_NOEXCEPT : m_value(rhs.m_value), m_perms(rhs.m_perms) {} file_status& operator=(const file_status& rhs) BOOST_NOEXCEPT { m_value = rhs.m_value; m_perms = rhs.m_perms; return *this; } # if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) file_status(file_status&& rhs) BOOST_NOEXCEPT { m_value = std::move(rhs.m_value); m_perms = std::move(rhs.m_perms); } file_status& operator=(file_status&& rhs) BOOST_NOEXCEPT { m_value = std::move(rhs.m_value); m_perms = std::move(rhs.m_perms); return *this; } # endif // observers file_type type() const BOOST_NOEXCEPT { return m_value; } perms permissions() const BOOST_NOEXCEPT { return m_perms; } // modifiers void type(file_type v) BOOST_NOEXCEPT { m_value = v; } void permissions(perms prms) BOOST_NOEXCEPT { m_perms = prms; } bool operator==(const file_status& rhs) const BOOST_NOEXCEPT { return type() == rhs.type() && permissions() == rhs.permissions(); } bool operator!=(const file_status& rhs) const BOOST_NOEXCEPT { return !(*this == rhs); } private: file_type m_value; enum perms m_perms; }; inline bool type_present(file_status f) BOOST_NOEXCEPT { return f.type() != status_error; } inline bool permissions_present(file_status f) BOOST_NOEXCEPT {return f.permissions() != perms_not_known;} inline bool status_known(file_status f) BOOST_NOEXCEPT { return type_present(f) && permissions_present(f); } inline bool exists(file_status f) BOOST_NOEXCEPT { return f.type() != status_error && f.type() != file_not_found; } inline bool is_regular_file(file_status f) BOOST_NOEXCEPT { return f.type() == regular_file; } inline bool is_directory(file_status f) BOOST_NOEXCEPT { return f.type() == directory_file; } inline bool is_symlink(file_status f) BOOST_NOEXCEPT { return f.type() == symlink_file; } inline bool is_other(file_status f) BOOST_NOEXCEPT { return exists(f) && !is_regular_file(f) && !is_directory(f) && !is_symlink(f); } # ifndef BOOST_FILESYSTEM_NO_DEPRECATED inline bool is_regular(file_status f) BOOST_NOEXCEPT { return f.type() == regular_file; } # endif struct space_info { // all values are byte counts boost::uintmax_t capacity; boost::uintmax_t free; // <= capacity boost::uintmax_t available; // <= free }; BOOST_SCOPED_ENUM_START(copy_option) {none=0, fail_if_exists = none, overwrite_if_exists}; BOOST_SCOPED_ENUM_END //--------------------------------------------------------------------------------------// // implementation details // //--------------------------------------------------------------------------------------// namespace detail { // We cannot pass a BOOST_SCOPED_ENUM to a compled function because it will result // in an undefined reference if the library is compled with -std=c++0x but the use // is compiled in C++03 mode, or visa versa. See tickets 6124, 6779, 10038. enum copy_option {none=0, fail_if_exists = none, overwrite_if_exists}; BOOST_FILESYSTEM_DECL file_status status(const path&p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL file_status symlink_status(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL bool is_empty(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL path initial_path(system::error_code* ec=0); BOOST_FILESYSTEM_DECL path canonical(const path& p, const path& base, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void copy(const path& from, const path& to, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void copy_directory(const path& from, const path& to, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void copy_file(const path& from, const path& to, // See ticket #2925 detail::copy_option option, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void copy_symlink(const path& existing_symlink, const path& new_symlink, system::error_code* ec=0); BOOST_FILESYSTEM_DECL bool create_directories(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL bool create_directory(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void create_directory_symlink(const path& to, const path& from, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void create_hard_link(const path& to, const path& from, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void create_symlink(const path& to, const path& from, system::error_code* ec=0); BOOST_FILESYSTEM_DECL path current_path(system::error_code* ec=0); BOOST_FILESYSTEM_DECL void current_path(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL bool equivalent(const path& p1, const path& p2, system::error_code* ec=0); BOOST_FILESYSTEM_DECL boost::uintmax_t file_size(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL boost::uintmax_t hard_link_count(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL std::time_t last_write_time(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void last_write_time(const path& p, const std::time_t new_time, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void permissions(const path& p, perms prms, system::error_code* ec=0); BOOST_FILESYSTEM_DECL path read_symlink(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL path relative(const path& p, const path& base, system::error_code* ec = 0); BOOST_FILESYSTEM_DECL bool remove(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL boost::uintmax_t remove_all(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void rename(const path& old_p, const path& new_p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL void resize_file(const path& p, uintmax_t size, system::error_code* ec=0); BOOST_FILESYSTEM_DECL space_info space(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL path system_complete(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL path temp_directory_path(system::error_code* ec=0); BOOST_FILESYSTEM_DECL path unique_path(const path& p, system::error_code* ec=0); BOOST_FILESYSTEM_DECL path weakly_canonical(const path& p, system::error_code* ec = 0); } // namespace detail //--------------------------------------------------------------------------------------// // // // status query functions // // // //--------------------------------------------------------------------------------------// inline file_status status(const path& p) {return detail::status(p);} inline file_status status(const path& p, system::error_code& ec) {return detail::status(p, &ec);} inline file_status symlink_status(const path& p) {return detail::symlink_status(p);} inline file_status symlink_status(const path& p, system::error_code& ec) {return detail::symlink_status(p, &ec);} inline bool exists(const path& p) {return exists(detail::status(p));} inline bool exists(const path& p, system::error_code& ec) {return exists(detail::status(p, &ec));} inline bool is_directory(const path& p) {return is_directory(detail::status(p));} inline bool is_directory(const path& p, system::error_code& ec) {return is_directory(detail::status(p, &ec));} inline bool is_regular_file(const path& p) {return is_regular_file(detail::status(p));} inline bool is_regular_file(const path& p, system::error_code& ec) {return is_regular_file(detail::status(p, &ec));} inline bool is_other(const path& p) {return is_other(detail::status(p));} inline bool is_other(const path& p, system::error_code& ec) {return is_other(detail::status(p, &ec));} inline bool is_symlink(const path& p) {return is_symlink(detail::symlink_status(p));} inline bool is_symlink(const path& p, system::error_code& ec) {return is_symlink(detail::symlink_status(p, &ec));} # ifndef BOOST_FILESYSTEM_NO_DEPRECATED inline bool is_regular(const path& p) {return is_regular(detail::status(p));} inline bool is_regular(const path& p, system::error_code& ec) {return is_regular(detail::status(p, &ec));} # endif inline bool is_empty(const path& p) {return detail::is_empty(p);} inline bool is_empty(const path& p, system::error_code& ec) {return detail::is_empty(p, &ec);} //--------------------------------------------------------------------------------------// // // // operational functions // // in alphabetical order, unless otherwise noted // // // //--------------------------------------------------------------------------------------// // forward declarations path current_path(); // fwd declaration path initial_path(); BOOST_FILESYSTEM_DECL path absolute(const path& p, const path& base=current_path()); // If base.is_absolute(), throws nothing. Thus no need for ec argument inline path canonical(const path& p, const path& base=current_path()) {return detail::canonical(p, base);} inline path canonical(const path& p, system::error_code& ec) {return detail::canonical(p, current_path(), &ec);} inline path canonical(const path& p, const path& base, system::error_code& ec) {return detail::canonical(p, base, &ec);} # ifndef BOOST_FILESYSTEM_NO_DEPRECATED inline path complete(const path& p) { return absolute(p, initial_path()); } inline path complete(const path& p, const path& base) { return absolute(p, base); } # endif inline void copy(const path& from, const path& to) {detail::copy(from, to);} inline void copy(const path& from, const path& to, system::error_code& ec) BOOST_NOEXCEPT {detail::copy(from, to, &ec);} inline void copy_directory(const path& from, const path& to) {detail::copy_directory(from, to);} inline void copy_directory(const path& from, const path& to, system::error_code& ec) BOOST_NOEXCEPT {detail::copy_directory(from, to, &ec);} inline void copy_file(const path& from, const path& to, // See ticket #2925 BOOST_SCOPED_ENUM(copy_option) option) { detail::copy_file(from, to, static_cast<detail::copy_option>(option)); } inline void copy_file(const path& from, const path& to) { detail::copy_file(from, to, detail::fail_if_exists); } inline void copy_file(const path& from, const path& to, // See ticket #2925 BOOST_SCOPED_ENUM(copy_option) option, system::error_code& ec) BOOST_NOEXCEPT { detail::copy_file(from, to, static_cast<detail::copy_option>(option), &ec); } inline void copy_file(const path& from, const path& to, system::error_code& ec) BOOST_NOEXCEPT { detail::copy_file(from, to, detail::fail_if_exists, &ec); } inline void copy_symlink(const path& existing_symlink, const path& new_symlink) {detail::copy_symlink(existing_symlink, new_symlink);} inline void copy_symlink(const path& existing_symlink, const path& new_symlink, system::error_code& ec) BOOST_NOEXCEPT {detail::copy_symlink(existing_symlink, new_symlink, &ec);} inline bool create_directories(const path& p) {return detail::create_directories(p);} inline bool create_directories(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::create_directories(p, &ec);} inline bool create_directory(const path& p) {return detail::create_directory(p);} inline bool create_directory(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::create_directory(p, &ec);} inline void create_directory_symlink(const path& to, const path& from) {detail::create_directory_symlink(to, from);} inline void create_directory_symlink(const path& to, const path& from, system::error_code& ec) BOOST_NOEXCEPT {detail::create_directory_symlink(to, from, &ec);} inline void create_hard_link(const path& to, const path& new_hard_link) {detail::create_hard_link(to, new_hard_link);} inline void create_hard_link(const path& to, const path& new_hard_link, system::error_code& ec) BOOST_NOEXCEPT {detail::create_hard_link(to, new_hard_link, &ec);} inline void create_symlink(const path& to, const path& new_symlink) {detail::create_symlink(to, new_symlink);} inline void create_symlink(const path& to, const path& new_symlink, system::error_code& ec) BOOST_NOEXCEPT {detail::create_symlink(to, new_symlink, &ec);} inline path current_path() {return detail::current_path();} inline path current_path(system::error_code& ec) BOOST_NOEXCEPT {return detail::current_path(&ec);} inline void current_path(const path& p) {detail::current_path(p);} inline void current_path(const path& p, system::error_code& ec) BOOST_NOEXCEPT {detail::current_path(p, &ec);} inline bool equivalent(const path& p1, const path& p2) {return detail::equivalent(p1, p2);} inline bool equivalent(const path& p1, const path& p2, system::error_code& ec) BOOST_NOEXCEPT {return detail::equivalent(p1, p2, &ec);} inline boost::uintmax_t file_size(const path& p) {return detail::file_size(p);} inline boost::uintmax_t file_size(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::file_size(p, &ec);} inline boost::uintmax_t hard_link_count(const path& p) {return detail::hard_link_count(p);} inline boost::uintmax_t hard_link_count(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::hard_link_count(p, &ec);} inline path initial_path() {return detail::initial_path();} inline path initial_path(system::error_code& ec) {return detail::initial_path(&ec);} template <class Path> path initial_path() {return initial_path();} template <class Path> path initial_path(system::error_code& ec) {return detail::initial_path(&ec);} inline std::time_t last_write_time(const path& p) {return detail::last_write_time(p);} inline std::time_t last_write_time(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::last_write_time(p, &ec);} inline void last_write_time(const path& p, const std::time_t new_time) {detail::last_write_time(p, new_time);} inline void last_write_time(const path& p, const std::time_t new_time, system::error_code& ec) BOOST_NOEXCEPT {detail::last_write_time(p, new_time, &ec);} inline void permissions(const path& p, perms prms) {detail::permissions(p, prms);} inline void permissions(const path& p, perms prms, system::error_code& ec) BOOST_NOEXCEPT {detail::permissions(p, prms, &ec);} inline path read_symlink(const path& p) {return detail::read_symlink(p);} inline path read_symlink(const path& p, system::error_code& ec) {return detail::read_symlink(p, &ec);} inline // For standardization, if the committee doesn't like "remove", consider "eliminate" bool remove(const path& p) {return detail::remove(p);} inline bool remove(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::remove(p, &ec);} inline boost::uintmax_t remove_all(const path& p) {return detail::remove_all(p);} inline boost::uintmax_t remove_all(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::remove_all(p, &ec);} inline void rename(const path& old_p, const path& new_p) {detail::rename(old_p, new_p);} inline void rename(const path& old_p, const path& new_p, system::error_code& ec) BOOST_NOEXCEPT {detail::rename(old_p, new_p, &ec);} inline // name suggested by Scott McMurray void resize_file(const path& p, uintmax_t size) {detail::resize_file(p, size);} inline void resize_file(const path& p, uintmax_t size, system::error_code& ec) BOOST_NOEXCEPT {detail::resize_file(p, size, &ec);} inline path relative(const path& p, const path& base=current_path()) {return detail::relative(p, base);} inline path relative(const path& p, system::error_code& ec) {return detail::relative(p, current_path(), &ec);} inline path relative(const path& p, const path& base, system::error_code& ec) {return detail::relative(p, base, &ec);} inline space_info space(const path& p) {return detail::space(p);} inline space_info space(const path& p, system::error_code& ec) BOOST_NOEXCEPT {return detail::space(p, &ec);} # ifndef BOOST_FILESYSTEM_NO_DEPRECATED inline bool symbolic_link_exists(const path& p) { return is_symlink(symlink_status(p)); } # endif inline path system_complete(const path& p) {return detail::system_complete(p);} inline path system_complete(const path& p, system::error_code& ec) {return detail::system_complete(p, &ec);} inline path temp_directory_path() {return detail::temp_directory_path();} inline path temp_directory_path(system::error_code& ec) {return detail::temp_directory_path(&ec);} inline path unique_path(const path& p="%%%%-%%%%-%%%%-%%%%") {return detail::unique_path(p);} inline path unique_path(const path& p, system::error_code& ec) {return detail::unique_path(p, &ec);} inline path weakly_canonical(const path& p) {return detail::weakly_canonical(p);} inline path weakly_canonical(const path& p, system::error_code& ec) {return detail::weakly_canonical(p, &ec);} //--------------------------------------------------------------------------------------// // // // directory_entry // // // //--------------------------------------------------------------------------------------// // GCC has a problem with a member function named path within a namespace or // sub-namespace that also has a class named path. The workaround is to always // fully qualify the name path when it refers to the class name. class BOOST_FILESYSTEM_DECL directory_entry { public: typedef boost::filesystem::path::value_type value_type; // enables class path ctor taking directory_entry directory_entry() BOOST_NOEXCEPT {} explicit directory_entry(const boost::filesystem::path& p) : m_path(p), m_status(file_status()), m_symlink_status(file_status()) {} directory_entry(const boost::filesystem::path& p, file_status st, file_status symlink_st = file_status()) : m_path(p), m_status(st), m_symlink_status(symlink_st) {} directory_entry(const directory_entry& rhs) : m_path(rhs.m_path), m_status(rhs.m_status), m_symlink_status(rhs.m_symlink_status){} directory_entry& operator=(const directory_entry& rhs) { m_path = rhs.m_path; m_status = rhs.m_status; m_symlink_status = rhs.m_symlink_status; return *this; } // As of October 2015 the interaction between noexcept and =default is so troublesome // for VC++, GCC, and probably other compilers, that =default is not used with noexcept // functions. GCC is not even consistent for the same release on different platforms. #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) directory_entry(directory_entry&& rhs) BOOST_NOEXCEPT { m_path = std::move(rhs.m_path); m_status = std::move(rhs.m_status); m_symlink_status = std::move(rhs.m_symlink_status); } directory_entry& operator=(directory_entry&& rhs) BOOST_NOEXCEPT { m_path = std::move(rhs.m_path); m_status = std::move(rhs.m_status); m_symlink_status = std::move(rhs.m_symlink_status); return *this; } #endif void assign(const boost::filesystem::path& p, file_status st = file_status(), file_status symlink_st = file_status()) { m_path = p; m_status = st; m_symlink_status = symlink_st; } void replace_filename(const boost::filesystem::path& p, file_status st = file_status(), file_status symlink_st = file_status()) { m_path.remove_filename(); m_path /= p; m_status = st; m_symlink_status = symlink_st; } # ifndef BOOST_FILESYSTEM_NO_DEPRECATED void replace_leaf(const boost::filesystem::path& p, file_status st, file_status symlink_st) { replace_filename(p, st, symlink_st); } # endif const boost::filesystem::path& path() const BOOST_NOEXCEPT {return m_path;} operator const boost::filesystem::path&() const BOOST_NOEXCEPT {return m_path;} file_status status() const {return m_get_status();} file_status status(system::error_code& ec) const BOOST_NOEXCEPT {return m_get_status(&ec); } file_status symlink_status() const {return m_get_symlink_status();} file_status symlink_status(system::error_code& ec) const BOOST_NOEXCEPT {return m_get_symlink_status(&ec); } bool operator==(const directory_entry& rhs) const BOOST_NOEXCEPT {return m_path == rhs.m_path; } bool operator!=(const directory_entry& rhs) const BOOST_NOEXCEPT {return m_path != rhs.m_path;} bool operator< (const directory_entry& rhs) const BOOST_NOEXCEPT {return m_path < rhs.m_path;} bool operator<=(const directory_entry& rhs) const BOOST_NOEXCEPT {return m_path <= rhs.m_path;} bool operator> (const directory_entry& rhs) const BOOST_NOEXCEPT {return m_path > rhs.m_path;} bool operator>=(const directory_entry& rhs) const BOOST_NOEXCEPT {return m_path >= rhs.m_path;} private: boost::filesystem::path m_path; mutable file_status m_status; // stat()-like mutable file_status m_symlink_status; // lstat()-like file_status m_get_status(system::error_code* ec=0) const; file_status m_get_symlink_status(system::error_code* ec=0) const; }; // directory_entry //--------------------------------------------------------------------------------------// // // // directory_iterator helpers // // // //--------------------------------------------------------------------------------------// class directory_iterator; namespace detail { BOOST_FILESYSTEM_DECL system::error_code dir_itr_close(// never throws() void *& handle # if defined(BOOST_POSIX_API) , void *& buffer # endif ); struct dir_itr_imp { directory_entry dir_entry; void* handle; # ifdef BOOST_POSIX_API void* buffer; // see dir_itr_increment implementation # endif dir_itr_imp() : handle(0) # ifdef BOOST_POSIX_API , buffer(0) # endif {} ~dir_itr_imp() // never throws { dir_itr_close(handle # if defined(BOOST_POSIX_API) , buffer # endif ); } }; // see path::iterator: comment below BOOST_FILESYSTEM_DECL void directory_iterator_construct(directory_iterator& it, const path& p, system::error_code* ec); BOOST_FILESYSTEM_DECL void directory_iterator_increment(directory_iterator& it, system::error_code* ec); } // namespace detail //--------------------------------------------------------------------------------------// // // // directory_iterator // // // //--------------------------------------------------------------------------------------// class directory_iterator : public boost::iterator_facade< directory_iterator, directory_entry, boost::single_pass_traversal_tag > { public: directory_iterator() BOOST_NOEXCEPT {} // creates the "end" iterator // iterator_facade derived classes don't seem to like implementations in // separate translation unit dll's, so forward to detail functions explicit directory_iterator(const path& p) : m_imp(new detail::dir_itr_imp) { detail::directory_iterator_construct(*this, p, 0); } directory_iterator(const path& p, system::error_code& ec) BOOST_NOEXCEPT : m_imp(new detail::dir_itr_imp) { detail::directory_iterator_construct(*this, p, &ec); } ~directory_iterator() {} directory_iterator& increment(system::error_code& ec) BOOST_NOEXCEPT { detail::directory_iterator_increment(*this, &ec); return *this; } private: friend struct detail::dir_itr_imp; friend BOOST_FILESYSTEM_DECL void detail::directory_iterator_construct(directory_iterator& it, const path& p, system::error_code* ec); friend BOOST_FILESYSTEM_DECL void detail::directory_iterator_increment(directory_iterator& it, system::error_code* ec); // shared_ptr provides shallow-copy semantics required for InputIterators. // m_imp.get()==0 indicates the end iterator. boost::shared_ptr< detail::dir_itr_imp > m_imp; friend class boost::iterator_core_access; boost::iterator_facade< directory_iterator, directory_entry, boost::single_pass_traversal_tag >::reference dereference() const { BOOST_ASSERT_MSG(m_imp.get(), "attempt to dereference end iterator"); return m_imp->dir_entry; } void increment() { detail::directory_iterator_increment(*this, 0); } bool equal(const directory_iterator& rhs) const { return m_imp == rhs.m_imp; } }; // directory_iterator // enable directory_iterator C++11 range-base for statement use --------------------// // begin() and end() are only used by a range-based for statement in the context of // auto - thus the top-level const is stripped - so returning const is harmless and // emphasizes begin() is just a pass through. inline const directory_iterator& begin(const directory_iterator& iter) BOOST_NOEXCEPT {return iter;} inline directory_iterator end(const directory_iterator&) BOOST_NOEXCEPT {return directory_iterator();} // enable directory_iterator BOOST_FOREACH -----------------------------------------// inline directory_iterator& range_begin(directory_iterator& iter) BOOST_NOEXCEPT {return iter;} inline directory_iterator range_begin(const directory_iterator& iter) BOOST_NOEXCEPT {return iter;} inline directory_iterator range_end(const directory_iterator&) BOOST_NOEXCEPT {return directory_iterator();} } // namespace filesystem // namespace boost template specializations template<> struct range_mutable_iterator<boost::filesystem::directory_iterator> { typedef boost::filesystem::directory_iterator type; }; template<> struct range_const_iterator <boost::filesystem::directory_iterator> { typedef boost::filesystem::directory_iterator type; }; namespace filesystem { //--------------------------------------------------------------------------------------// // // // recursive_directory_iterator helpers // // // //--------------------------------------------------------------------------------------// BOOST_SCOPED_ENUM_START(symlink_option) { none, no_recurse = none, // don't follow directory symlinks (default behavior) recurse, // follow directory symlinks _detail_no_push = recurse << 1 // internal use only }; BOOST_SCOPED_ENUM_END BOOST_BITMASK(BOOST_SCOPED_ENUM(symlink_option)) namespace detail { struct recur_dir_itr_imp { typedef directory_iterator element_type; std::stack< element_type, std::vector< element_type > > m_stack; int m_level; BOOST_SCOPED_ENUM(symlink_option) m_options; recur_dir_itr_imp() : m_level(0), m_options(symlink_option::none) {} void increment(system::error_code* ec); // ec == 0 means throw on error bool push_directory(system::error_code& ec) BOOST_NOEXCEPT; void pop(); }; // Implementation is inline to avoid dynamic linking difficulties with m_stack: // Microsoft warning C4251, m_stack needs to have dll-interface to be used by // clients of struct 'boost::filesystem::detail::recur_dir_itr_imp' inline bool recur_dir_itr_imp::push_directory(system::error_code& ec) BOOST_NOEXCEPT // Returns: true if push occurs, otherwise false. Always returns false on error. { ec.clear(); // Discover if the iterator is for a directory that needs to be recursed into, // taking symlinks and options into account. if ((m_options & symlink_option::_detail_no_push) == symlink_option::_detail_no_push) m_options &= ~symlink_option::_detail_no_push; else { // Logic for following predicate was contributed by Daniel Aarno to handle cyclic // symlinks correctly and efficiently, fixing ticket #5652. // if (((m_options & symlink_option::recurse) == symlink_option::recurse // || !is_symlink(m_stack.top()->symlink_status())) // && is_directory(m_stack.top()->status())) ... // The predicate code has since been rewritten to pass error_code arguments, // per ticket #5653. file_status symlink_stat; if ((m_options & symlink_option::recurse) != symlink_option::recurse) { symlink_stat = m_stack.top()->symlink_status(ec); if (ec) return false; } if ((m_options & symlink_option::recurse) == symlink_option::recurse || !is_symlink(symlink_stat)) { file_status stat = m_stack.top()->status(ec); if (ec || !is_directory(stat)) return false; directory_iterator next(m_stack.top()->path(), ec); if (!ec && next != directory_iterator()) { m_stack.push(next); ++m_level; return true; } } } return false; } inline void recur_dir_itr_imp::increment(system::error_code* ec) // ec == 0 means throw on error // // Invariant: On return, the top of the iterator stack is the next valid (possibly // end) iterator, regardless of whether or not an error is reported, and regardless of // whether any error is reported by exception or error code. In other words, progress // is always made so a loop on the iterator will always eventually terminate // regardless of errors. { system::error_code ec_push_directory; // if various conditions are met, push a directory_iterator into the iterator stack if (push_directory(ec_push_directory)) { if (ec) ec->clear(); return; } // Do the actual increment operation on the top iterator in the iterator // stack, popping the stack if necessary, until either the stack is empty or a // non-end iterator is reached. while (!m_stack.empty() && ++m_stack.top() == directory_iterator()) { m_stack.pop(); --m_level; } // report errors if any if (ec_push_directory) { if (ec) *ec = ec_push_directory; else { BOOST_FILESYSTEM_THROW(filesystem_error( "filesystem::recursive_directory_iterator directory error", ec_push_directory)); } } else if (ec) ec->clear(); } inline void recur_dir_itr_imp::pop() { BOOST_ASSERT_MSG(m_level > 0, "pop() on recursive_directory_iterator with level < 1"); do { m_stack.pop(); --m_level; } while (!m_stack.empty() && ++m_stack.top() == directory_iterator()); } } // namespace detail //--------------------------------------------------------------------------------------// // // // recursive_directory_iterator // // // //--------------------------------------------------------------------------------------// class recursive_directory_iterator : public boost::iterator_facade< recursive_directory_iterator, directory_entry, boost::single_pass_traversal_tag > { public: recursive_directory_iterator() BOOST_NOEXCEPT {} // creates the "end" iterator explicit recursive_directory_iterator(const path& dir_path) // throws if !exists() : m_imp(new detail::recur_dir_itr_imp) { m_imp->m_options = symlink_option::none; m_imp->m_stack.push(directory_iterator(dir_path)); if (m_imp->m_stack.top() == directory_iterator()) { m_imp.reset(); } } recursive_directory_iterator(const path& dir_path, BOOST_SCOPED_ENUM(symlink_option) opt) // throws if !exists() : m_imp(new detail::recur_dir_itr_imp) { m_imp->m_options = opt; m_imp->m_stack.push(directory_iterator(dir_path)); if (m_imp->m_stack.top() == directory_iterator()) { m_imp.reset (); } } recursive_directory_iterator(const path& dir_path, BOOST_SCOPED_ENUM(symlink_option) opt, system::error_code & ec) BOOST_NOEXCEPT : m_imp(new detail::recur_dir_itr_imp) { m_imp->m_options = opt; m_imp->m_stack.push(directory_iterator(dir_path, ec)); if (m_imp->m_stack.top() == directory_iterator()) { m_imp.reset (); } } recursive_directory_iterator(const path& dir_path, system::error_code & ec) BOOST_NOEXCEPT : m_imp(new detail::recur_dir_itr_imp) { m_imp->m_options = symlink_option::none; m_imp->m_stack.push(directory_iterator(dir_path, ec)); if (m_imp->m_stack.top() == directory_iterator()) { m_imp.reset (); } } recursive_directory_iterator& increment(system::error_code& ec) BOOST_NOEXCEPT { BOOST_ASSERT_MSG(m_imp.get(), "increment() on end recursive_directory_iterator"); m_imp->increment(&ec); if (m_imp->m_stack.empty()) m_imp.reset(); // done, so make end iterator return *this; } int depth() const BOOST_NOEXCEPT { BOOST_ASSERT_MSG(m_imp.get(), "depth() on end recursive_directory_iterator"); return m_imp->m_level; } int level() const BOOST_NOEXCEPT { return depth(); } bool recursion_pending() const BOOST_NOEXCEPT { BOOST_ASSERT_MSG(m_imp.get(), "is_no_push_requested() on end recursive_directory_iterator"); return (m_imp->m_options & symlink_option::_detail_no_push) == symlink_option::_detail_no_push; } bool no_push_pending() const BOOST_NOEXCEPT { return recursion_pending(); } # ifndef BOOST_FILESYSTEM_NO_DEPRECATED bool no_push_request() const BOOST_NOEXCEPT { return no_push_pending(); } # endif void pop() { BOOST_ASSERT_MSG(m_imp.get(), "pop() on end recursive_directory_iterator"); m_imp->pop(); if (m_imp->m_stack.empty()) m_imp.reset(); // done, so make end iterator } void disable_recursion_pending(bool value=true) BOOST_NOEXCEPT { BOOST_ASSERT_MSG(m_imp.get(), "no_push() on end recursive_directory_iterator"); if (value) m_imp->m_options |= symlink_option::_detail_no_push; else m_imp->m_options &= ~symlink_option::_detail_no_push; } void no_push(bool value=true) BOOST_NOEXCEPT { disable_recursion_pending(value); } file_status status() const { BOOST_ASSERT_MSG(m_imp.get(), "status() on end recursive_directory_iterator"); return m_imp->m_stack.top()->status(); } file_status symlink_status() const { BOOST_ASSERT_MSG(m_imp.get(), "symlink_status() on end recursive_directory_iterator"); return m_imp->m_stack.top()->symlink_status(); } private: // shared_ptr provides shallow-copy semantics required for InputIterators. // m_imp.get()==0 indicates the end iterator. boost::shared_ptr< detail::recur_dir_itr_imp > m_imp; friend class boost::iterator_core_access; boost::iterator_facade< recursive_directory_iterator, directory_entry, boost::single_pass_traversal_tag >::reference dereference() const { BOOST_ASSERT_MSG(m_imp.get(), "dereference of end recursive_directory_iterator"); return *m_imp->m_stack.top(); } void increment() { BOOST_ASSERT_MSG(m_imp.get(), "increment of end recursive_directory_iterator"); m_imp->increment(0); if (m_imp->m_stack.empty()) m_imp.reset(); // done, so make end iterator } bool equal(const recursive_directory_iterator& rhs) const { return m_imp == rhs.m_imp; } }; // recursive directory iterator // enable recursive directory iterator C++11 range-base for statement use ----------// // begin() and end() are only used by a range-based for statement in the context of // auto - thus the top-level const is stripped - so returning const is harmless and // emphasizes begin() is just a pass through. inline const recursive_directory_iterator& begin(const recursive_directory_iterator& iter) BOOST_NOEXCEPT {return iter;} inline recursive_directory_iterator end(const recursive_directory_iterator&) BOOST_NOEXCEPT {return recursive_directory_iterator();} // enable recursive directory iterator BOOST_FOREACH -------------------------------// inline recursive_directory_iterator& range_begin(recursive_directory_iterator& iter) BOOST_NOEXCEPT {return iter;} inline recursive_directory_iterator range_begin(const recursive_directory_iterator& iter) BOOST_NOEXCEPT {return iter;} inline recursive_directory_iterator range_end(const recursive_directory_iterator&) BOOST_NOEXCEPT {return recursive_directory_iterator();} } // namespace filesystem // namespace boost template specializations template<> struct range_mutable_iterator<boost::filesystem::recursive_directory_iterator> { typedef boost::filesystem::recursive_directory_iterator type; }; template<> struct range_const_iterator <boost::filesystem::recursive_directory_iterator> { typedef boost::filesystem::recursive_directory_iterator type; }; namespace filesystem { # if !defined(BOOST_FILESYSTEM_NO_DEPRECATED) typedef recursive_directory_iterator wrecursive_directory_iterator; # endif // test helper -----------------------------------------------------------------------// // Not part of the documented interface since false positives are possible; // there is no law that says that an OS that has large stat.st_size // actually supports large file sizes. namespace detail { BOOST_FILESYSTEM_DECL bool possible_large_file_size_support(); } } // namespace filesystem } // namespace boost #include <boost/config/abi_suffix.hpp> // pops abi_prefix.hpp pragmas #endif // BOOST_FILESYSTEM3_OPERATIONS_HPP
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # Copyright 2007-2020 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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. # # HyperSpy 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 HyperSpy. If not, see <http://www.gnu.org/licenses/>. from hyperspy.drawing.marker import MarkerBase class HorizontalLine(MarkerBase): """Horizontal line marker that can be added to the signal figure Parameters --------- y : array or float The position of the line. If float, the marker is fixed. If array, the marker will be updated when navigating. The array should have the same dimensions in the navigation axes. kwargs : Keywords argument of axvline valid properties (i.e. recognized by mpl.plot). Example ------- >>> s = hs.signals.Signal1D(np.random.random([10, 100])) * 10 >>> m = hs.plot.markers.horizontal_line(y=range(10), color='green') >>> s.add_marker(m) Adding a marker permanently to a signal >>> s = hs.signals.Signal1D(np.random.random([10, 100])) >>> m = hs.plot.markers.horizontal_line(y=5, color='green') >>> s.add_marker(m, permanent=True) """ def __init__(self, y, **kwargs): MarkerBase.__init__(self) lp = {'linewidth': 1, 'color': 'black'} self.marker_properties = lp self.set_data(y1=y) self.set_marker_properties(**kwargs) self.name = 'horizontal_line' def __repr__(self): string = "<marker.{}, {} (y={},color={})>".format( self.__class__.__name__, self.name, self.get_data_position('y1'), self.marker_properties['color'], self.get_data_position('size'), ) return(string) def update(self): if self.auto_update is False: return self.marker.set_ydata(self.get_data_position('y1')) def _plot_marker(self): self.marker = self.ax.axhline(self.get_data_position('y1'), **self.marker_properties)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- You may freely edit this file. See commented blocks below for --> <!-- some examples of how to customize the build. --> <!-- (If you delete it and reopen the project it will be recreated.) --> <!-- By default, only the Clean and Build commands use this build script. --> <!-- Commands such as Run, Debug, and Test only use this build script if --> <!-- the Compile on Save feature is turned off for the project. --> <!-- You can turn off the Compile on Save (or Deploy on Save) setting --> <!-- in the project's Project Properties dialog box.--> <project name="Catalano.Android.Image" default="default" basedir="."> <description>Builds, tests, and runs the project Catalano.Android.Image.</description> <import file="nbproject/build-impl.xml"/> <!-- There exist several targets which are by default empty and which can be used for execution of your tasks. These targets are usually executed before and after some main targets. They are: -pre-init: called before initialization of project properties -post-init: called after initialization of project properties -pre-compile: called before javac compilation -post-compile: called after javac compilation -pre-compile-single: called before javac compilation of single file -post-compile-single: called after javac compilation of single file -pre-compile-test: called before javac compilation of JUnit tests -post-compile-test: called after javac compilation of JUnit tests -pre-compile-test-single: called before javac compilation of single JUnit test -post-compile-test-single: called after javac compilation of single JUunit test -pre-jar: called before JAR building -post-jar: called after JAR building -post-clean: called after cleaning build products (Targets beginning with '-' are not intended to be called on their own.) Example of inserting an obfuscator after compilation could look like this: <target name="-post-compile"> <obfuscate> <fileset dir="${build.classes.dir}"/> </obfuscate> </target> For list of available properties check the imported nbproject/build-impl.xml file. Another way to customize the build is by overriding existing main targets. The targets of interest are: -init-macrodef-javac: defines macro for javac compilation -init-macrodef-junit: defines macro for junit execution -init-macrodef-debug: defines macro for class debugging -init-macrodef-java: defines macro for class execution -do-jar: JAR building run: execution of project -javadoc-build: Javadoc generation test-report: JUnit report generation An example of overriding the target for project execution could look like this: <target name="run" depends="Catalano.Android.Image-impl.jar"> <exec dir="bin" executable="launcher.exe"> <arg file="${dist.jar}"/> </exec> </target> Notice that the overridden target depends on the jar target and not only on the compile target as the regular run target does. Again, for a list of available properties which you can use, check the target you are overriding in the nbproject/build-impl.xml file. --> </project>
{ "pile_set_name": "Github" }
#standardSQL # 11_04e: % manifests preferring native apps CREATE TEMPORARY FUNCTION prefersNative(manifest STRING) RETURNS BOOLEAN LANGUAGE js AS ''' try { var $ = JSON.parse(manifest); return $.prefer_related_applications == true && $.related_applications.length > 0; } catch (e) { return null; } '''; SELECT client, prefersNative(body) AS prefers_native, COUNT(0) AS freq, SUM(COUNT(0)) OVER (PARTITION BY client) AS total, ROUND(COUNT(0) * 100 / SUM(COUNT(0)) OVER (PARTITION BY client), 2) AS pct FROM `httparchive.almanac.manifests` WHERE date = '2019-07-01' GROUP BY client, prefers_native HAVING prefers_native IS NOT NULL ORDER BY freq / total DESC
{ "pile_set_name": "Github" }
using System.IO; using JSIL.Meta; using JSIL.Proxy; namespace JSIL.Proxies.Bcl { [JSProxy(typeof(File), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_File { } [JSProxy(typeof (Path), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared,JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_Path { } [JSProxy(typeof(Stream), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_Stream { } [JSProxy(typeof(FileStream), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_FileStream { } [JSProxy(typeof(MemoryStream), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_MemoryStream { } [JSProxy(typeof(BinaryWriter), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_BinaryWriter { } [JSProxy(typeof(BinaryReader), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_BinaryReader { } [JSProxy(typeof(StreamReader), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_StreamReader { } [JSProxy(typeof(TextReader), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_TextReader { } [JSProxy(typeof(FileSystemInfo), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_FileSystemInfo { } [JSProxy(typeof(DirectoryInfo), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_DirectoryInfo { } [JSProxy(typeof(FileInfo), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_FileInfo { } [JSProxy(typeof(Directory), JSProxyMemberPolicy.ReplaceNone, JSProxyAttributePolicy.ReplaceDeclared, JSProxyInterfacePolicy.ReplaceNone, false)] [JSStubOnly] public class System_IO_Directory { } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Tue Sep 30 00:12:27 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.glyptodon.guacamole.protocol.GuacamoleConfiguration (guacamole-common 0.9.3 API)</title> <meta name="date" content="2014-09-30"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.glyptodon.guacamole.protocol.GuacamoleConfiguration (guacamole-common 0.9.3 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/glyptodon/guacamole/protocol/class-use/GuacamoleConfiguration.html" target="_top">Frames</a></li> <li><a href="GuacamoleConfiguration.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.glyptodon.guacamole.protocol.GuacamoleConfiguration" class="title">Uses of Class<br>org.glyptodon.guacamole.protocol.GuacamoleConfiguration</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleConfiguration</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.glyptodon.guacamole.protocol">org.glyptodon.guacamole.protocol</a></td> <td class="colLast"> <div class="block">Classes relating directly to the Guacamole protocol.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.glyptodon.guacamole.protocol"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleConfiguration</a> in <a href="../../../../../org/glyptodon/guacamole/protocol/package-summary.html">org.glyptodon.guacamole.protocol</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/glyptodon/guacamole/protocol/package-summary.html">org.glyptodon.guacamole.protocol</a> that return <a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleConfiguration</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleConfiguration</a></code></td> <td class="colLast"><span class="strong">ConfiguredGuacamoleSocket.</span><code><strong><a href="../../../../../org/glyptodon/guacamole/protocol/ConfiguredGuacamoleSocket.html#getConfiguration()">getConfiguration</a></strong>()</code> <div class="block">Returns the GuacamoleConfiguration used to configure this ConfiguredGuacamoleSocket.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../org/glyptodon/guacamole/protocol/package-summary.html">org.glyptodon.guacamole.protocol</a> with parameters of type <a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleConfiguration</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../org/glyptodon/guacamole/protocol/ConfiguredGuacamoleSocket.html#ConfiguredGuacamoleSocket(org.glyptodon.guacamole.net.GuacamoleSocket,%20org.glyptodon.guacamole.protocol.GuacamoleConfiguration)">ConfiguredGuacamoleSocket</a></strong>(<a href="../../../../../org/glyptodon/guacamole/net/GuacamoleSocket.html" title="interface in org.glyptodon.guacamole.net">GuacamoleSocket</a>&nbsp;socket, <a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleConfiguration</a>&nbsp;config)</code> <div class="block">Creates a new ConfiguredGuacamoleSocket which uses the given GuacamoleConfiguration to complete the initial protocol handshake over the given GuacamoleSocket.</div> </td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../org/glyptodon/guacamole/protocol/ConfiguredGuacamoleSocket.html#ConfiguredGuacamoleSocket(org.glyptodon.guacamole.net.GuacamoleSocket,%20org.glyptodon.guacamole.protocol.GuacamoleConfiguration,%20org.glyptodon.guacamole.protocol.GuacamoleClientInformation)">ConfiguredGuacamoleSocket</a></strong>(<a href="../../../../../org/glyptodon/guacamole/net/GuacamoleSocket.html" title="interface in org.glyptodon.guacamole.net">GuacamoleSocket</a>&nbsp;socket, <a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleConfiguration</a>&nbsp;config, <a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleClientInformation.html" title="class in org.glyptodon.guacamole.protocol">GuacamoleClientInformation</a>&nbsp;info)</code> <div class="block">Creates a new ConfiguredGuacamoleSocket which uses the given GuacamoleConfiguration and GuacamoleClientInformation to complete the initial protocol handshake over the given GuacamoleSocket.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/glyptodon/guacamole/protocol/GuacamoleConfiguration.html" title="class in org.glyptodon.guacamole.protocol">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/glyptodon/guacamole/protocol/class-use/GuacamoleConfiguration.html" target="_top">Frames</a></li> <li><a href="GuacamoleConfiguration.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014. All rights reserved.</small></p> <!-- Google Analytics --> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-75289145-1', 'auto'); ga('send', 'pageview'); </script> <!-- End Google Analytics --> </body> </html>
{ "pile_set_name": "Github" }
/*! * Bootstrap v3.1.1 (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ .btn-default, .btn-primary, .btn-success, .btn-info, .btn-warning, .btn-danger { text-shadow: 0 -1px 0 rgba(0, 0, 0, .2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075); } .btn-default:active, .btn-primary:active, .btn-success:active, .btn-info:active, .btn-warning:active, .btn-danger:active, .btn-default.active, .btn-primary.active, .btn-success.active, .btn-info.active, .btn-warning.active, .btn-danger.active { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); } .btn:active, .btn.active { background-image: none; } .btn-default { text-shadow: 0 1px 0 #fff; background-image: -webkit-linear-gradient(top, #fff 0%, #e0e0e0 100%); background-image: linear-gradient(to bottom, #fff 0%, #e0e0e0 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #dbdbdb; border-color: #ccc; } .btn-default:hover, .btn-default:focus { background-color: #e0e0e0; background-position: 0 -15px; } .btn-default:active, .btn-default.active { background-color: #e0e0e0; border-color: #dbdbdb; } .btn-primary { background-image: -webkit-linear-gradient(top, #428bca 0%, #2d6ca2 100%); background-image: linear-gradient(to bottom, #428bca 0%, #2d6ca2 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff2d6ca2', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #2b669a; } .btn-primary:hover, .btn-primary:focus { background-color: #2d6ca2; background-position: 0 -15px; } .btn-primary:active, .btn-primary.active { background-color: #2d6ca2; border-color: #2b669a; } .btn-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%); background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #3e8f3e; } .btn-success:hover, .btn-success:focus { background-color: #419641; background-position: 0 -15px; } .btn-success:active, .btn-success.active { background-color: #419641; border-color: #3e8f3e; } .btn-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #28a4c9; } .btn-info:hover, .btn-info:focus { background-color: #2aabd2; background-position: 0 -15px; } .btn-info:active, .btn-info.active { background-color: #2aabd2; border-color: #28a4c9; } .btn-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #e38d13; } .btn-warning:hover, .btn-warning:focus { background-color: #eb9316; background-position: 0 -15px; } .btn-warning:active, .btn-warning.active { background-color: #eb9316; border-color: #e38d13; } .btn-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%); background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #b92c28; } .btn-danger:hover, .btn-danger:focus { background-color: #c12e2a; background-position: 0 -15px; } .btn-danger:active, .btn-danger.active { background-color: #c12e2a; border-color: #b92c28; } .thumbnail, .img-thumbnail { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075); box-shadow: 0 1px 2px rgba(0, 0, 0, .075); } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { background-color: #e8e8e8; background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); background-repeat: repeat-x; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { background-color: #357ebd; background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%); background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0); background-repeat: repeat-x; } .navbar-default { background-image: -webkit-linear-gradient(top, #fff 0%, #f8f8f8 100%); background-image: linear-gradient(to bottom, #fff 0%, #f8f8f8 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-radius: 4px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075); } .navbar-default .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f3f3f3 100%); background-image: linear-gradient(to bottom, #ebebeb 0%, #f3f3f3 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff3f3f3', GradientType=0); background-repeat: repeat-x; -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075); box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075); } .navbar-brand, .navbar-nav > li > a { text-shadow: 0 1px 0 rgba(255, 255, 255, .25); } .navbar-inverse { background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222 100%); background-image: linear-gradient(to bottom, #3c3c3c 0%, #222 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; } .navbar-inverse .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #222 0%, #282828 100%); background-image: linear-gradient(to bottom, #222 0%, #282828 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff282828', GradientType=0); background-repeat: repeat-x; -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25); box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25); } .navbar-inverse .navbar-brand, .navbar-inverse .navbar-nav > li > a { text-shadow: 0 -1px 0 rgba(0, 0, 0, .25); } .navbar-static-top, .navbar-fixed-top, .navbar-fixed-bottom { border-radius: 0; } .alert { text-shadow: 0 1px 0 rgba(255, 255, 255, .2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05); } .alert-success { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0); background-repeat: repeat-x; border-color: #b2dba1; } .alert-info { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%); background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0); background-repeat: repeat-x; border-color: #9acfea; } .alert-warning { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0); background-repeat: repeat-x; border-color: #f5e79e; } .alert-danger { background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0); background-repeat: repeat-x; border-color: #dca7a7; } .progress { background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0); background-repeat: repeat-x; } .progress-bar { background-image: -webkit-linear-gradient(top, #428bca 0%, #3071a9 100%); background-image: linear-gradient(to bottom, #428bca 0%, #3071a9 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3071a9', GradientType=0); background-repeat: repeat-x; } .progress-bar-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%); background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0); background-repeat: repeat-x; } .progress-bar-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0); background-repeat: repeat-x; } .progress-bar-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0); background-repeat: repeat-x; } .progress-bar-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%); background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0); background-repeat: repeat-x; } .list-group { border-radius: 4px; -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075); box-shadow: 0 1px 2px rgba(0, 0, 0, .075); } .list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus { text-shadow: 0 -1px 0 #3071a9; background-image: -webkit-linear-gradient(top, #428bca 0%, #3278b3 100%); background-image: linear-gradient(to bottom, #428bca 0%, #3278b3 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3278b3', GradientType=0); background-repeat: repeat-x; border-color: #3278b3; } .panel { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .05); box-shadow: 0 1px 2px rgba(0, 0, 0, .05); } .panel-default > .panel-heading { background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); background-repeat: repeat-x; } .panel-primary > .panel-heading { background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%); background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0); background-repeat: repeat-x; } .panel-success > .panel-heading { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0); background-repeat: repeat-x; } .panel-info > .panel-heading { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0); background-repeat: repeat-x; } .panel-warning > .panel-heading { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0); background-repeat: repeat-x; } .panel-danger > .panel-heading { background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%); background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0); background-repeat: repeat-x; } .well { background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0); background-repeat: repeat-x; border-color: #dcdcdc; -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1); box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1); } /*# sourceMappingURL=bootstrap-theme.css.map */
{ "pile_set_name": "Github" }
from unittest.mock import MagicMock import pytest from requests import exceptions as requests_exceptions from briefcase.exceptions import MissingToolError, NetworkFailure from briefcase.integrations.linuxdeploy import LinuxDeploy @pytest.fixture def mock_command(tmp_path): command = MagicMock() command.host_arch = 'wonky' command.tools_path = tmp_path / 'tools' command.tools_path.mkdir() return command def test_verify_exists(mock_command, tmp_path): "If linuxdeploy already exists, verification doesn't download" appimage_path = tmp_path / 'tools' / 'linuxdeploy-wonky.AppImage' # Mock the existence of an install appimage_path.touch() # Create a linuxdeploy wrapper by verification linuxdeploy = LinuxDeploy.verify(mock_command) # No download occured assert mock_command.download_url.call_count == 0 assert mock_command.os.chmod.call_count == 0 # The build command retains the path to the downloaded file. assert linuxdeploy.appimage_path == appimage_path def test_verify_does_not_exist_dont_install(mock_command, tmp_path): "If linuxdeploy doesn't exist, and install=False, it is *not* downloaded" # Mock a successful download mock_command.download_url.return_value = 'new-downloaded-file' # True to create a linuxdeploy wrapper by verification. # This will fail because it doesn't exist, but installation was disabled. with pytest.raises(MissingToolError): LinuxDeploy.verify(mock_command, install=False) # No download occured assert mock_command.download_url.call_count == 0 assert mock_command.os.chmod.call_count == 0 def test_verify_does_not_exist(mock_command, tmp_path): "If linuxdeploy doesn't exist, it is downloaded" appimage_path = tmp_path / 'tools' / 'linuxdeploy-wonky.AppImage' # Mock a successful download mock_command.download_url.return_value = 'new-downloaded-file' # Create a linuxdeploy wrapper by verification linuxdeploy = LinuxDeploy.verify(mock_command) # A download is invoked mock_command.download_url.assert_called_with( url='https://github.com/linuxdeploy/linuxdeploy/' 'releases/download/continuous/linuxdeploy-wonky.AppImage', download_path=tmp_path / 'tools' ) # The downloaded file will be made executable mock_command.os.chmod.assert_called_with('new-downloaded-file', 0o755) # The build command retains the path to the downloaded file. assert linuxdeploy.appimage_path == appimage_path def test_verify_linuxdeploy_download_failure(mock_command, tmp_path): "If linuxdeploy doesn't exist, but a download failure occurs, an error is raised" mock_command.download_url.side_effect = requests_exceptions.ConnectionError with pytest.raises(NetworkFailure): LinuxDeploy.verify(mock_command) # A download was invoked mock_command.download_url.assert_called_with( url='https://github.com/linuxdeploy/linuxdeploy/' 'releases/download/continuous/linuxdeploy-wonky.AppImage', download_path=tmp_path / 'tools' )
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1beta2 type ControllerRevisionExpansion interface{} type DaemonSetExpansion interface{} type DeploymentExpansion interface{} type ReplicaSetExpansion interface{} type StatefulSetExpansion interface{}
{ "pile_set_name": "Github" }
require "helper" module Nokogiri module XML class TestEntityReference < Nokogiri::TestCase def setup super @xml = Nokogiri::XML(File.open(XML_FILE), XML_FILE) end def test_new assert ref = EntityReference.new(@xml, 'ent4') assert_instance_of EntityReference, ref end def test_many_references 100.times { EntityReference.new(@xml, 'foo') } end def test_newline_node # issue 719 xml = <<EOF <?xml version="1.0" ?> <item></item> EOF doc = Nokogiri::XML xml lf_node = Nokogiri::XML::EntityReference.new(doc, "#xa") doc.xpath('/item').first.add_child(lf_node) assert_match doc.to_xml, /&#xa;/ end end module Common PATH = 'test/files/test_document_url/' attr_accessor :path, :parser def xml_document File.join path, 'document.xml' end def self.included base def base.test_relative_and_absolute_path method_name, &block test_relative_path method_name, &block test_absolute_path method_name, &block end def base.test_absolute_path method_name, &block define_method "#{method_name}_with_absolute_path" do self.path = "#{File.expand_path PATH}/" instance_eval(&block) end end def base.test_relative_path method_name, &block define_method method_name do self.path = PATH instance_eval(&block) end end end end class TestDOMEntityReference < Nokogiri::TestCase include Common def setup super @parser = Nokogiri::XML::Document end test_relative_and_absolute_path :test_dom_entity_reference_with_dtdloda do # Make sure that we can parse entity references and include them in the document html = File.read xml_document doc = @parser.parse html, path do |cfg| cfg.default_xml cfg.dtdload cfg.noent end assert_equal [], doc.errors assert_equal "foobar", doc.xpath('//blah').text end test_relative_and_absolute_path :test_dom_entity_reference_with_dtdvalid do # Make sure that we can parse entity references and include them in the document html = File.read xml_document doc = @parser.parse html, path do |cfg| cfg.default_xml cfg.dtdvalid cfg.noent end assert_equal [], doc.errors assert_equal "foobar", doc.xpath('//blah').text end test_absolute_path :test_dom_dtd_loading_with_absolute_path do # Make sure that we can parse entity references and include them in the document html = %Q[<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE document SYSTEM "#{path}/document.dtd"> <document> <body>&bar;</body> </document> ] doc = @parser.parse html, xml_document do |cfg| cfg.default_xml cfg.dtdvalid cfg.noent end assert_equal [], doc.errors assert_equal "foobar", doc.xpath('//blah').text end test_relative_and_absolute_path :test_dom_entity_reference_with_io do # Make sure that we can parse entity references and include them in the document html = File.open xml_document doc = @parser.parse html, nil do |cfg| cfg.default_xml cfg.dtdload cfg.noent end assert_equal [], doc.errors assert_equal "foobar", doc.xpath('//blah').text end test_relative_and_absolute_path :test_dom_entity_reference_without_noent do # Make sure that we don't include entity references unless NOENT is set to true html = File.read xml_document doc = @parser.parse html, path do |cfg| cfg.default_xml cfg.dtdload end assert_equal [], doc.errors assert_kind_of Nokogiri::XML::EntityReference, doc.xpath('//body').first.children.first end test_relative_and_absolute_path :test_dom_entity_reference_without_dtdload do # Make sure that we don't include entity references unless NOENT is set to true html = File.read xml_document doc = @parser.parse html, path do |cfg| cfg.default_xml end assert_kind_of Nokogiri::XML::EntityReference, doc.xpath('//body').first.children.first if Nokogiri.uses_libxml? assert_equal ["Entity 'bar' not defined"], doc.errors.map(&:to_s) end end test_relative_and_absolute_path :test_document_dtd_loading_with_nonet do # Make sure that we don't include remote entities unless NOENT is set to true html = %Q[<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE document SYSTEM "http://foo.bar.com/"> <document> <body>&bar;</body> </document> ] doc = @parser.parse html, path do |cfg| cfg.default_xml cfg.dtdload end assert_kind_of Nokogiri::XML::EntityReference, doc.xpath('//body').first.children.first if Nokogiri.uses_libxml? assert_equal ["Attempt to load network entity http://foo.bar.com/", "Entity 'bar' not defined"], doc.errors.map(&:to_s) else assert_equal ["Attempt to load network entity http://foo.bar.com/"], doc.errors.map(&:to_s) end end # TODO: can we retreive a resource pointing to localhost when NONET is set to true ? end class TestSaxEntityReference < Nokogiri::SAX::TestCase include Common def setup super @parser = XML::SAX::Parser.new(Doc.new) do |ctx| ctx.replace_entities = true end end test_relative_and_absolute_path :test_sax_entity_reference do # Make sure that we can parse entity references and include them in the document html = File.read xml_document @parser.parse html refute_nil @parser.document.errors assert_equal ["Entity 'bar' not defined"], @parser.document.errors.map(&:to_s).map(&:strip) end test_relative_and_absolute_path :test_more_sax_entity_reference do # Make sure that we don't include entity references unless NOENT is set to true html = %Q[<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE document SYSTEM "http://foo.bar.com/"> <document> <body>&bar;</body> </document> ] @parser.parse html refute_nil @parser.document.errors assert_equal ["Entity 'bar' not defined"], @parser.document.errors.map(&:to_s).map(&:strip) end end class TestReaderEntityReference < Nokogiri::TestCase include Common def setup super end test_relative_and_absolute_path :test_reader_entity_reference do # Make sure that we can parse entity references and include them in the document html = File.read xml_document reader = Nokogiri::XML::Reader html, path do |cfg| cfg.default_xml cfg.dtdload cfg.noent end nodes = [] reader.each { |n| nodes << n.value } assert_equal ['foobar'], nodes.compact.map(&:strip).reject(&:empty?) end test_relative_and_absolute_path :test_reader_entity_reference_without_noent do # Make sure that we can parse entity references and include them in the document html = File.read xml_document reader = Nokogiri::XML::Reader html, path do |cfg| cfg.default_xml cfg.dtdload end nodes = [] reader.each { |n| nodes << n.value } assert_equal [], nodes.compact.map(&:strip).reject(&:empty?) end test_relative_and_absolute_path :test_reader_entity_reference_without_dtdload do html = File.read xml_document assert_raises(Nokogiri::XML::SyntaxError) do reader = Nokogiri::XML::Reader html, path do |cfg| cfg.default_xml end reader.each { |n| n } end end end end end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ColorDialog</class> <widget class="QDialog" name="ColorDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>400</width> <height>300</height> </rect> </property> <property name="windowTitle"> <string>Customize Colors</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTreeWidget" name="treeWidget"> <attribute name="headerDefaultSectionSize"> <number>100</number> </attribute> <column> <property name="text"> <string>Item Type</string> </property> </column> <column> <property name="text"> <string>Color</string> </property> </column> <column> <property name="text"> <string>Sample</string> </property> </column> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QPushButton" name="push_getcolor"> <property name="text"> <string>Select Color</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> <item> <widget class="QPushButton" name="push_cancel"> <property name="text"> <string>Cancel</string> </property> </widget> </item> <item> <widget class="QPushButton" name="push_apply"> <property name="text"> <string>Apply</string> </property> </widget> </item> </layout> </item> </layout> </widget> <resources/> <connections/> </ui>
{ "pile_set_name": "Github" }
--- title: ListGallery.Application Property (Word) keywords: vbawd10.chm160695272 f1_keywords: - vbawd10.chm160695272 ms.prod: word api_name: - Word.ListGallery.Application ms.assetid: 09766d0b-19d3-f75a-2847-6da44fc2aa7b ms.date: 06/08/2017 --- # ListGallery.Application Property (Word) Returns an **[Application](application-object-word.md)** object that represents the Microsoft Word application. ## Syntax _expression_ . **Application** _expression_ Required. A variable that represents a **[ListGallery](listgallery-object-word.md)** object. ## Remarks Visual Basic's **CreateObject** and **GetObject** functions give you access to an OLE Automation object from a Visual Basic for Applications project. ## See also #### Concepts [ListGallery Object](listgallery-object-word.md)
{ "pile_set_name": "Github" }
package com.gorylenko.writer /** * Remove all lines start with # and end with LF (\n) */ class SkipPropertiesCommentsOutputStream extends FilterOutputStream { private static int START_COMMENT_CHAR1 = '#' private static int START_COMMENT_CHAR2 = '!' private static int LINE_END_CHAR = '\n' private boolean commentFound = false private int lastChar = LINE_END_CHAR public SkipPropertiesCommentsOutputStream(OutputStream out) { super(out) } @Override public void write(int b) throws IOException { if (!commentFound && (b == START_COMMENT_CHAR1 || b == START_COMMENT_CHAR2) && lastChar == LINE_END_CHAR) { commentFound = true } else if (commentFound && b == LINE_END_CHAR) { commentFound = false } else if (!commentFound) { super.write(b) } lastChar = b } }
{ "pile_set_name": "Github" }
name=Tajuru Archer image=https://magiccards.info/scans/en/zen/185.jpg value=2.138 rarity=U type=Creature subtype=Elf,Archer,Ally cost={2}{G} pt=1/2 ability=Whenever SN or another Ally enters the battlefield under your control, \ you may have SN deal damage to target creature with flying equal to the number of Allies you control. timing=main oracle=Whenever Tajuru Archer or another Ally enters the battlefield under your control, you may have Tajuru Archer deal damage to target creature with flying equal to the number of Allies you control.
{ "pile_set_name": "Github" }
--- http_client_port: 18026 http_public_port: 17026 udp_server_port: 16026 database: host=localhost port=5432 dbname=ubot_t26 node_number: 26 public_host: localhost node_name: ubot_26 ip: - 127.0.0.1
{ "pile_set_name": "Github" }
package net.sourceforge.vrapper.plugin.surround.state; /** * Holds a pair of delimiters which need to be added or used to replace a previous pair of * delimiters in the editor. * * @author Bert Jacobs */ public interface DelimiterHolder { public String getLeft(); public String getRight(); }
{ "pile_set_name": "Github" }
//===- unittest/ADT/IntrusiveRefCntPtrTest.cpp ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "gtest/gtest.h" namespace llvm { namespace { struct SimpleRefCounted : public RefCountedBase<SimpleRefCounted> { SimpleRefCounted() { ++NumInstances; } SimpleRefCounted(const SimpleRefCounted &) : RefCountedBase() { ++NumInstances; } ~SimpleRefCounted() { --NumInstances; } static int NumInstances; }; int SimpleRefCounted::NumInstances = 0; } // anonymous namespace TEST(IntrusiveRefCntPtr, RefCountedBaseCopyDoesNotLeak) { EXPECT_EQ(0, SimpleRefCounted::NumInstances); { SimpleRefCounted *S1 = new SimpleRefCounted; IntrusiveRefCntPtr<SimpleRefCounted> R1 = S1; SimpleRefCounted *S2 = new SimpleRefCounted(*S1); IntrusiveRefCntPtr<SimpleRefCounted> R2 = S2; EXPECT_EQ(2, SimpleRefCounted::NumInstances); } EXPECT_EQ(0, SimpleRefCounted::NumInstances); } struct InterceptRefCounted : public RefCountedBase<InterceptRefCounted> { InterceptRefCounted(bool *Released, bool *Retained) : Released(Released), Retained(Retained) {} bool * const Released; bool * const Retained; }; template <> struct IntrusiveRefCntPtrInfo<InterceptRefCounted> { static void retain(InterceptRefCounted *I) { *I->Retained = true; I->Retain(); } static void release(InterceptRefCounted *I) { *I->Released = true; I->Release(); } }; TEST(IntrusiveRefCntPtr, UsesTraitsToRetainAndRelease) { bool Released = false; bool Retained = false; { InterceptRefCounted *I = new InterceptRefCounted(&Released, &Retained); IntrusiveRefCntPtr<InterceptRefCounted> R = I; } EXPECT_TRUE(Released); EXPECT_TRUE(Retained); } } // end namespace llvm
{ "pile_set_name": "Github" }
/* * Copyright 2017 BlazingDB, Inc. * Copyright 2018 Percy Camilo Triveño Aucahuasi <[email protected]> */ #include "FileSystemRepository.h" #include "private/FileSystemRepository_p.h" FileSystemRepository::FileSystemRepository(const Path & dataFile, bool encrypted) : pimpl(new FileSystemRepository::Private(dataFile, encrypted)) {} FileSystemRepository::~FileSystemRepository() {} const Path FileSystemRepository::getDataFile() const noexcept { return this->pimpl->dataFile; } bool FileSystemRepository::isEncrypted() const noexcept { return this->pimpl->encrypted; } std::vector<FileSystemEntity> FileSystemRepository::findAll() const { return this->pimpl->findAll(); } bool FileSystemRepository::add(const FileSystemEntity & fileSystemEntity) const { return this->pimpl->add(fileSystemEntity); } bool FileSystemRepository::deleteByAuthority(const std::string & authority) const { return this->pimpl->deleteByAuthority(authority); }
{ "pile_set_name": "Github" }
# Word Break > Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. > For example, given s = "leetcode", dict = ["leet", "code"]. > Return true because "leetcode" can be segmented as "leet code". 这题的意思是给出一本词典以及一个字符串,能否切分这个字符串使得每个字串都在字典里面存在。 假设dp(i)表示长度为i的字串能否别切分,dp方程如下: `dp(i) = dp(j) && s[j, i) in dict, 0 <= j < i` 代码如下 ```c++ class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { int len = (int)s.size(); vector<bool> dp(len + 1, false); dp[0] = true; for(int i = 1; i <= len; i++) { for(int j = i - 1; j >= 0; j--) { if(dp[j] && dict.find(s.substr(j, i - j)) != dict.end()) { dp[i] = true; break; } } } return dp[len]; } }; ``` # World Break II > Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. > Return all such possible sentences. > For example, given s = "catsanddog", dict = ["cat", "cats", "and", "sand", "dog"]. > A solution is ["cats and dog", "cat sand dog"]. 这道题不同于上一题,需要我们得到所有能切分的解。这道题难度很大,我们需要采用dp + dfs的方式求解,首先根据dp得到该字符串能否被切分,同时在dp的过程中记录属于字典的子串信息,供后续dfs使用。 首先我们使用dp[i][j]表示起始索引为i,长度为j的子串能否被切分,它有三种状态: 1. dp[i][j] = true && dp[i][j] in dict,这种情况是这个子串直接在字典中 2. dp[i][j] = true && dp[i][j] not in dict,这种情况是这个子串不在字典中,但是它能切分成更小的子串,而这些子串在字典中 3. dp[i][j] = false,子串不能被切分 根据题意,我们需要求出所有切分的解,所以在进行dp的时候需要处理1和2这两种情况,因为对于2来说,dp[i][j]是要继续被切分的,也就是说我们只需要关注第1种情况的子串。 当dp完成之后,我们就需要使用dfs来得到整个的解。在dp[i][j] = 1的情况下面,我们只需要dfs递归处理后面i + j开始的子串就可以了。 代码如下: ```c++ class Solution { public: vector<vector<char> >dp; vector<string> vals; string val; vector<string> wordBreak(string s, unordered_set<string> &dict) { int len = (int)s.size(); dp.resize(len); for(int i = 0; i < len; i++) { dp[i].resize(len + 1, 0); } for(int i = 1; i <= len; i++) { for(int j = 0; j < len -i + 1; j++) { //直接存在于字典中,是第1种情况 if(dict.find(s.substr(j, i)) != dict.end()) { dp[j][i] = 1; continue; } //如果不存在,则看子串是不是能被切分,这是第2中情况 for(int k = 1; k < i && k < len -j; k++) { if(dp[j][k] && dp[j + k][i - k]) { dp[j][i] = 2; break; } } } } //不能切分,不用dfs了 if(dp[0][len] == 0) { return vals; } dfs(s, 0); return vals; } void dfs(const string& s, int start) { int len = (int)s.size(); if(start == len) { vals.push_back(val); return; } for(int i = 1; i <= len - start;i++) { if(dp[start][i] == 1) { int oldLen = (int)val.size(); if(oldLen != 0) { val.append(" "); } val.append(s.substr(start, i)); //我们从start + i开始继续dfs dfs(s, start + i); val.erase(oldLen, string::npos); } } } }; ```
{ "pile_set_name": "Github" }
/** * Marlin 3D Printer Firmware * Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(MARLIN_INVADERS) #include "game.h" #define CANNON_W 11 #define CANNON_H 8 #define CANNON_VEL 4 #define CANNON_Y (LCD_PIXEL_HEIGHT - 1 - CANNON_H) #define INVADER_VEL 3 #define INVADER_TOP MENU_FONT_ASCENT #define INVADERS_WIDE ((INVADER_COL_W) * (INVADER_COLS)) #define INVADERS_HIGH ((INVADER_ROW_H) * (INVADER_ROWS)) #define UFO_H 5 #define UFO_W 13 #define LASER_H 4 #define SHOT_H 3 #define EXPL_W 11 #define LIFE_W 8 #define LIFE_H 5 #define INVADER_RIGHT ((INVADER_COLS) * (INVADER_COL_W)) // 11x8 const unsigned char invader[3][2][16] PROGMEM = { { { B00000110,B00000000, B00001111,B00000000, B00011111,B10000000, B00110110,B11000000, B00111111,B11000000, B00001001,B00000000, B00010110,B10000000, B00101001,B01000000 }, { B00000110,B00000000, B00001111,B00000000, B00011111,B10000000, B00110110,B11000000, B00111111,B11000000, B00010110,B10000000, B00100000,B01000000, B00010000,B10000000 } }, { { B00010000,B01000000, B00001000,B10000000, B00011111,B11000000, B00110111,B01100000, B01111111,B11110000, B01011111,B11010000, B01010000,B01010000, B00001101,B10000000 }, { B00010000,B01000000, B01001000,B10010000, B01011111,B11010000, B01110111,B01110000, B01111111,B11110000, B00011111,B11000000, B00010000,B01000000, B00100000,B00100000 } }, { { B00001111,B00000000, B01111111,B11100000, B11111111,B11110000, B11100110,B01110000, B11111111,B11110000, B00011001,B10000000, B00110110,B11000000, B11000000,B00110000 }, { B00001111,B00000000, B01111111,B11100000, B11111111,B11110000, B11100110,B01110000, B11111111,B11110000, B00011001,B10000000, B00110110,B11000000, B00011001,B10000000 } } }; const unsigned char cannon[] PROGMEM = { B00000100,B00000000, B00001110,B00000000, B00001110,B00000000, B01111111,B11000000, B11111111,B11100000, B11111111,B11100000, B11111111,B11100000, B11111111,B11100000 }; const unsigned char life[] PROGMEM = { B00010000, B01111100, B11111110, B11111110, B11111110 }; const unsigned char explosion[] PROGMEM = { B01000100,B01000000, B00100100,B10000000, B00000000,B00000000, B00110001,B10000000, B00000000,B00000000, B00100100,B10000000, B01000100,B01000000 }; const unsigned char ufo[] PROGMEM = { B00011111,B11000000, B01111111,B11110000, B11011101,B11011000, B11111111,B11111000, B01111111,B11110000 }; constexpr uint8_t inv_type[] = { #if INVADER_ROWS == 5 0, 1, 1, 2, 2 #elif INVADER_ROWS == 4 0, 1, 1, 2 #elif INVADER_ROWS == 3 0, 1, 2 #else #error "INVASION_SIZE must be 3, 4, or 5." #endif }; invaders_data_t &idat = marlin_game_data.invaders; #define INV_X_LEFT(C,T) (idat.pos.x + (C) * (INVADER_COL_W) + inv_off[T]) #define INV_X_CTR(C,T) (INV_X_LEFT(C,T) + inv_wide[T] / 2) #define INV_Y_BOT(R) (idat.pos.y + (R + 1) * (INVADER_ROW_H) - 2) constexpr uint8_t inv_off[] = { 2, 1, 0 }, inv_wide[] = { 8, 11, 12 }; inline void update_invader_data() { uint8_t inv_mask = 0; // Get a list of all active invaders uint8_t sc = 0; LOOP_L_N(y, INVADER_ROWS) { uint8_t m = idat.bugs[y]; if (m) idat.botmost = y + 1; inv_mask |= m; for (uint8_t x = 0; x < INVADER_COLS; ++x) if (TEST(m, x)) idat.shooters[sc++] = (y << 4) | x; } idat.leftmost = 0; LOOP_L_N(i, INVADER_COLS) { if (TEST(inv_mask, i)) break; idat.leftmost -= INVADER_COL_W; } idat.rightmost = LCD_PIXEL_WIDTH - (INVADERS_WIDE); for (uint8_t i = INVADER_COLS; i--;) { if (TEST(inv_mask, i)) break; idat.rightmost += INVADER_COL_W; } if (idat.count == 2) idat.dir = idat.dir > 0 ? INVADER_VEL + 1 : -(INVADER_VEL + 1); } inline void reset_bullets() { LOOP_L_N(i, COUNT(idat.bullet)) idat.bullet[i].v = 0; } inline void reset_invaders() { idat.pos.x = 0; idat.pos.y = INVADER_TOP; idat.dir = INVADER_VEL; idat.count = (INVADER_COLS) * (INVADER_ROWS); LOOP_L_N(i, INVADER_ROWS) idat.bugs[i] = _BV(INVADER_COLS) - 1; update_invader_data(); reset_bullets(); } inline void spawn_ufo() { idat.ufov = random(0, 2) ? 1 : -1; idat.ufox = idat.ufov > 0 ? -(UFO_W) : LCD_PIXEL_WIDTH - 1; } inline void reset_player() { idat.cannon_x = 0; ui.encoderPosition = 0; } inline void fire_cannon() { idat.laser.x = idat.cannon_x + CANNON_W / 2; idat.laser.y = LCD_PIXEL_HEIGHT - CANNON_H - (LASER_H); idat.laser.v = -(LASER_H); } inline void explode(const int8_t x, const int8_t y, const int8_t v=4) { idat.explod.x = x - (EXPL_W) / 2; idat.explod.y = y; idat.explod.v = v; } inline void kill_cannon(uint8_t &game_state, const uint8_t st) { reset_bullets(); explode(idat.cannon_x + (CANNON_W) / 2, CANNON_Y, 6); _BUZZ(1000, 10); if (--idat.cannons_left) { idat.laser.v = 0; game_state = st; reset_player(); } else game_state = 0; } void InvadersGame::game_screen() { ui.refresh(LCDVIEW_CALL_NO_REDRAW); // Call as often as possible // Run game logic once per full screen if (ui.first_page) { // Update Cannon Position int16_t ep = constrain(int16_t(ui.encoderPosition), 0, (LCD_PIXEL_WIDTH - (CANNON_W)) / (CANNON_VEL)); ui.encoderPosition = ep; ep *= (CANNON_VEL); if (ep > idat.cannon_x) { idat.cannon_x += CANNON_VEL - 1; if (ep - idat.cannon_x < 2) idat.cannon_x = ep; } if (ep < idat.cannon_x) { idat.cannon_x -= CANNON_VEL - 1; if (idat.cannon_x - ep < 2) idat.cannon_x = ep; } // Run the game logic if (game_state) do { // Move the UFO, if any if (idat.ufov) { idat.ufox += idat.ufov; if (!WITHIN(idat.ufox, -(UFO_W), LCD_PIXEL_WIDTH - 1)) idat.ufov = 0; } if (game_state > 1) { if (--game_state == 2) { reset_invaders(); } else if (game_state == 100) { game_state = 1; } break; } const bool did_blink = (++idat.blink_count > idat.count >> 1); if (did_blink) { idat.game_blink = !idat.game_blink; idat.blink_count = 0; } if (idat.count && did_blink) { const int8_t newx = idat.pos.x + idat.dir; if (!WITHIN(newx, idat.leftmost, idat.rightmost)) { // Invaders reached the edge? idat.dir *= -1; // Invaders change direction idat.pos.y += (INVADER_ROW_H) / 2; // Invaders move down idat.pos.x -= idat.dir; // ...and only move down this time. if (idat.pos.y + idat.botmost * (INVADER_ROW_H) - 2 >= CANNON_Y) // Invaders reached the bottom? kill_cannon(game_state, 20); // Kill the cannon. Reset invaders. } idat.pos.x += idat.dir; // Invaders take one step left/right // Randomly shoot if invaders are listed if (idat.count && !random(0, 20)) { // Find a free bullet laser_t *b = nullptr; LOOP_L_N(i, COUNT(idat.bullet)) if (!idat.bullet[i].v) { b = &idat.bullet[i]; break; } if (b) { // Pick a random shooter and update the bullet //SERIAL_ECHOLNPGM("free bullet found"); const uint8_t inv = idat.shooters[random(0, idat.count + 1)], col = inv & 0x0F, row = inv >> 4, type = inv_type[row]; b->x = INV_X_CTR(col, type); b->y = INV_Y_BOT(row); b->v = 2 + random(0, 2); } } } // Update the laser position if (idat.laser.v) { idat.laser.y += idat.laser.v; if (idat.laser.y < 0) idat.laser.v = 0; } // Did the laser collide with an invader? if (idat.laser.v && WITHIN(idat.laser.y, idat.pos.y, idat.pos.y + INVADERS_HIGH - 1)) { const int8_t col = idat.laser_col(); if (WITHIN(col, 0, INVADER_COLS - 1)) { const int8_t row = idat.laser_row(); if (WITHIN(row, 0, INVADER_ROWS - 1)) { const uint8_t mask = _BV(col); if (idat.bugs[row] & mask) { const uint8_t type = inv_type[row]; const int8_t invx = INV_X_LEFT(col, type); if (WITHIN(idat.laser.x, invx, invx + inv_wide[type] - 1)) { // Turn off laser idat.laser.v = 0; // Remove the invader! idat.bugs[row] &= ~mask; // Score! score += INVADER_ROWS - row; // Explode sound! _BUZZ(40, 10); // Explosion bitmap! explode(invx + inv_wide[type] / 2, idat.pos.y + row * (INVADER_ROW_H)); // If invaders are gone, go to reset invaders state if (--idat.count) update_invader_data(); else { game_state = 20; reset_bullets(); } } // laser x hit } // invader exists } // good row } // good col } // laser in invader zone // Handle alien bullets LOOP_L_N(s, COUNT(idat.bullet)) { laser_t *b = &idat.bullet[s]; if (b->v) { // Update alien bullet position b->y += b->v; if (b->y >= LCD_PIXEL_HEIGHT) b->v = 0; // Offscreen else if (b->y >= CANNON_Y && WITHIN(b->x, idat.cannon_x, idat.cannon_x + CANNON_W - 1)) kill_cannon(game_state, 120); // Hit the cannon } } // Randomly spawn a UFO if (!idat.ufov && !random(0,500)) spawn_ufo(); // Did the laser hit a ufo? if (idat.laser.v && idat.ufov && idat.laser.y < UFO_H + 2 && WITHIN(idat.laser.x, idat.ufox, idat.ufox + UFO_W - 1)) { // Turn off laser and UFO idat.laser.v = idat.ufov = 0; // Score! score += 10; // Explode! _BUZZ(40, 10); // Explosion bitmap explode(idat.ufox + (UFO_W) / 2, 1); } } while (false); } // Click-and-hold to abort if (ui.button_pressed()) --idat.quit_count; else idat.quit_count = 10; // Click to fire or exit if (ui.use_click()) { if (!game_state) idat.quit_count = 0; else if (game_state == 1 && !idat.laser.v) fire_cannon(); } if (!idat.quit_count) exit_game(); u8g.setColorIndex(1); // Draw invaders if (PAGE_CONTAINS(idat.pos.y, idat.pos.y + idat.botmost * (INVADER_ROW_H) - 2 - 1)) { int8_t yy = idat.pos.y; for (uint8_t y = 0; y < INVADER_ROWS; ++y) { const uint8_t type = inv_type[y]; if (PAGE_CONTAINS(yy, yy + INVADER_H - 1)) { int8_t xx = idat.pos.x; for (uint8_t x = 0; x < INVADER_COLS; ++x) { if (TEST(idat.bugs[y], x)) u8g.drawBitmapP(xx, yy, 2, INVADER_H, invader[type][idat.game_blink]); xx += INVADER_COL_W; } } yy += INVADER_ROW_H; } } // Draw UFO if (idat.ufov && PAGE_UNDER(UFO_H + 2)) u8g.drawBitmapP(idat.ufox, 2, 2, UFO_H, ufo); // Draw cannon if (game_state && PAGE_CONTAINS(CANNON_Y, CANNON_Y + CANNON_H - 1) && (game_state < 2 || (game_state & 0x02))) u8g.drawBitmapP(idat.cannon_x, CANNON_Y, 2, CANNON_H, cannon); // Draw laser if (idat.laser.v && PAGE_CONTAINS(idat.laser.y, idat.laser.y + LASER_H - 1)) u8g.drawVLine(idat.laser.x, idat.laser.y, LASER_H); // Draw invader bullets LOOP_L_N (i, COUNT(idat.bullet)) { if (idat.bullet[i].v && PAGE_CONTAINS(idat.bullet[i].y - (SHOT_H - 1), idat.bullet[i].y)) u8g.drawVLine(idat.bullet[i].x, idat.bullet[i].y - (SHOT_H - 1), SHOT_H); } // Draw explosion if (idat.explod.v && PAGE_CONTAINS(idat.explod.y, idat.explod.y + 7 - 1)) { u8g.drawBitmapP(idat.explod.x, idat.explod.y, 2, 7, explosion); --idat.explod.v; } // Blink GAME OVER when game is over if (!game_state) draw_game_over(); if (PAGE_UNDER(MENU_FONT_ASCENT - 1)) { // Draw Score //const uint8_t sx = (LCD_PIXEL_WIDTH - (score >= 10 ? score >= 100 ? score >= 1000 ? 4 : 3 : 2 : 1) * MENU_FONT_WIDTH) / 2; constexpr uint8_t sx = 0; lcd_put_int(sx, MENU_FONT_ASCENT - 1, score); // Draw lives if (idat.cannons_left) for (uint8_t i = 1; i <= idat.cannons_left; ++i) u8g.drawBitmapP(LCD_PIXEL_WIDTH - i * (LIFE_W), 6 - (LIFE_H), 1, LIFE_H, life); } } void InvadersGame::enter_game() { init_game(20, game_screen); // countdown to reset invaders idat.cannons_left = 3; idat.quit_count = 10; idat.laser.v = 0; reset_invaders(); reset_player(); } #endif // MARLIN_INVADERS
{ "pile_set_name": "Github" }
<?php namespace Zeeshan\GitProfile\Commands; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Zeeshan Ahmed <[email protected]> * @copyright 2016 Zeeshan Ahmed * @license http://www.opensource.org/licenses/mit-license.html MIT License */ class CurrentGitProfileCommand extends BaseCommand { /** * Configure the command. */ public function configure() { $this->setName('current') ->setDescription('Get the current profile.') ->addOption('global', null, InputOption::VALUE_NONE, 'Set git profile global.'); } /** * Execute the command. * * @param InputInterface $input * @param OutputInterface $output */ public function execute(InputInterface $input, OutputInterface $output) { if ($input->getOption('global')) { $currentProfile = $this->retrieveCurrentProfile(true); } else { $currentProfile = $this->retrieveCurrentProfile(); } if (!empty($currentProfile) && $this->doesProfileExists($currentProfile)) { $email = $this->runCommand(sprintf('git config --global profile.%s.email', $currentProfile)); $name = $this->runCommand(sprintf('git config --global profile.%s.name', $currentProfile)); $signingkey = $this->runCommand(sprintf('git config --global profile.%s.signingkey', $currentProfile)); $output->writeln(''); $output->writeln('[+] Current Profile: ' . $currentProfile); $output->writeln('[+] Name: ' . $name); $output->writeln('[+] Email: ' . $email); $output->writeln('[+] Signingkey: ' . $signingkey); return; } $output->writeln(''); $output->writeln('[+] Profile is not set. Standard settings are used.'); $output->writeln(sprintf('[+] Name: %s', $this->runCommand(sprintf('git config user.name')))); $output->writeln(sprintf('[+] Email: %s', $this->runCommand(sprintf('git config user.email')))); $output->writeln(sprintf('[+] Signingkey: %s', $this->runCommand(sprintf('git config user.signingkey')))); } }
{ "pile_set_name": "Github" }
/*************************************************************************** Copyright 2015 Ufora 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. ****************************************************************************/ #include "../UnitTest.hpp" #include "../Logging.hpp" #include "../Clock.hpp" #include "CPPMLThreadSafety.hppml" #include "MemoizeByTagAndHash.hppml" namespace { @type List = Node of int, List -| Empty of (); int sum(const List& l) { @match List(l) -| Node(i, l) ->> { return i + sum(l); } -| Empty() ->> { return 0; } ; } List doubleList(const List& l) { @match List(l) -| Node(i, l) ->> { return List::Node(i * 2, doubleList(l)); } -| Empty() ->> { return List::Empty(); } ; } BOOST_AUTO_TEST_CASE( test_CppmlBasicFunctionality ) { List l1 = List::Empty(); l1 = List::Node(10, l1); l1 = List::Node(20, l1); BOOST_CHECK_EQUAL(sum(l1), 30); BOOST_CHECK_EQUAL(sum(doubleList(l1)), 60); } static int sCount = 0; class DeletionMarker { public: DeletionMarker() { sCount++; } DeletionMarker(const DeletionMarker& in) { sCount++; } ~DeletionMarker() { sCount--; } }; @type Elt = Leaf of DeletionMarker marker -| Node of Elt elt, Elt elt2 with DeletionMarker aMarker = (this->computeDeletionMarker()) { public: DeletionMarker computeDeletionMarker() const { return DeletionMarker(); } }; BOOST_AUTO_TEST_CASE( test_CppmlDeletionWorks ) { BOOST_CHECK_EQUAL(sCount, 0); { Elt e1 = Elt::Leaf(DeletionMarker()); e1.aMarker(); Elt e2 = Elt::Leaf(DeletionMarker()); e2.aMarker(); Elt e3 = Elt::Node(e1, e2); e3.aMarker(); } BOOST_CHECK_EQUAL(sCount, 0); } } class AnAlternativeForCppmlTesting; macro_memoizeCppmlClassByTagAndHash(AnAlternativeForCppmlTesting) @type AnAlternativeForCppmlTesting = AnEmptyAlternative of () -| ANonemptyAlternative of int i ; BOOST_AUTO_TEST_CASE( test_CppmlMemoizeByTagAndHash ) { long timesOK = 0; for (long tries = 0; tries < 4; tries++) { double t0 = curClock(); for (long k = 0; k < 1000000;k++) AnAlternativeForCppmlTesting::AnEmptyAlternative(); double emptyElapsed = curClock() - t0; t0 = curClock(); for (long k = 0; k < 1000000;k++) AnAlternativeForCppmlTesting::ANonemptyAlternative(1); double nonemptyElapsed = curClock() - t0; //verify that memoizing an empty type is _much_ faster if (nonemptyElapsed > emptyElapsed * 10) timesOK++; } BOOST_CHECK(timesOK > 2); }
{ "pile_set_name": "Github" }
module github.com/aws/aws-sdk-go-v2/service/marketplaceentitlementservice go 1.15 require ( github.com/aws/aws-sdk-go-v2 v0.0.0-20200928200900-9b4f334f82b2 github.com/awslabs/smithy-go v0.1.0 ) replace github.com/aws/aws-sdk-go-v2 => ../../
{ "pile_set_name": "Github" }
package org.knowm.xchange.btcmarkets; import java.io.IOException; import java.util.List; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import org.knowm.xchange.btcmarkets.dto.BTCMarketsException; import org.knowm.xchange.btcmarkets.dto.account.BTCMarketsBalance; import org.knowm.xchange.btcmarkets.dto.account.BTCMarketsFundtransferHistoryResponse; import org.knowm.xchange.btcmarkets.dto.trade.*; import org.knowm.xchange.btcmarkets.service.BTCMarketsDigest; import si.mazi.rescu.SynchronizedValueFactory; @Path("/") @Produces(MediaType.APPLICATION_JSON) public interface BTCMarketsAuthenticated { @GET @Path("account/balance") List<BTCMarketsBalance> getBalance( @HeaderParam("apikey") String publicKey, @HeaderParam("timestamp") SynchronizedValueFactory<Long> nonceFactory, @HeaderParam("signature") BTCMarketsDigest signer) throws BTCMarketsException, IOException; @POST @Path("order/cancel") @Consumes(MediaType.APPLICATION_JSON) BTCMarketsCancelOrderResponse cancelOrder( @HeaderParam("apikey") String publicKey, @HeaderParam("timestamp") SynchronizedValueFactory<Long> nonceFactory, @HeaderParam("signature") BTCMarketsDigest signer, BTCMarketsCancelOrderRequest request) throws BTCMarketsException, IOException; @POST @Path("order/open") @Consumes(MediaType.APPLICATION_JSON) BTCMarketsOrders getOpenOrders( @HeaderParam("apikey") String publicKey, @HeaderParam("timestamp") SynchronizedValueFactory<Long> nonceFactory, @HeaderParam("signature") BTCMarketsDigest signer, BTCMarketsOpenOrdersRequest request) throws BTCMarketsException, IOException; @POST @Path("order/history") @Consumes(MediaType.APPLICATION_JSON) BTCMarketsOrders getOrderHistory( @HeaderParam("apikey") String publicKey, @HeaderParam("timestamp") SynchronizedValueFactory<Long> nonceFactory, @HeaderParam("signature") BTCMarketsDigest signer, BTCMarketsOpenOrdersRequest request) throws BTCMarketsException, IOException; @POST @Path("order/detail") @Consumes(MediaType.APPLICATION_JSON) BTCMarketsOrders getOrderDetails( @HeaderParam("apikey") String publicKey, @HeaderParam("timestamp") SynchronizedValueFactory<Long> nonceFactory, @HeaderParam("signature") BTCMarketsDigest signer, BTCMarketsOrderDetailsRequest request) throws BTCMarketsException, IOException; @POST @Path("fundtransfer/withdrawCrypto") @Consumes(MediaType.APPLICATION_JSON) BTCMarketsWithdrawCryptoResponse withdrawCrypto( @HeaderParam("apikey") String publicKey, @HeaderParam("timestamp") SynchronizedValueFactory<Long> nonceFactory, @HeaderParam("signature") BTCMarketsDigest signer, BTCMarketsWithdrawCryptoRequest request) throws BTCMarketsException, IOException; @GET @Path("fundtransfer/history") BTCMarketsFundtransferHistoryResponse fundtransferHistory( @HeaderParam("apikey") String publicKey, @HeaderParam("timestamp") SynchronizedValueFactory<Long> nonceFactory, @HeaderParam("signature") BTCMarketsDigest signer) throws BTCMarketsException, IOException; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist>
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math4.ml.clustering.evaluation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.apache.commons.math4.ml.clustering.Cluster; import org.apache.commons.math4.ml.clustering.DoublePoint; import org.apache.commons.math4.ml.clustering.ClusterEvaluator; import org.apache.commons.math4.ml.distance.EuclideanDistance; import org.junit.Before; import org.junit.Test; public class SumOfClusterVariancesTest { private ClusterEvaluator evaluator; @Before public void setUp() { evaluator = new SumOfClusterVariances(new EuclideanDistance()); } @Test public void testScore() { final DoublePoint[] points1 = new DoublePoint[] { new DoublePoint(new double[] { 1 }), new DoublePoint(new double[] { 2 }), new DoublePoint(new double[] { 3 }) }; final DoublePoint[] points2 = new DoublePoint[] { new DoublePoint(new double[] { 1 }), new DoublePoint(new double[] { 5 }), new DoublePoint(new double[] { 10 }) }; final List<Cluster<DoublePoint>> clusters = new ArrayList<>(); final Cluster<DoublePoint> cluster1 = new Cluster<>(); for (DoublePoint p : points1) { cluster1.addPoint(p); } clusters.add(cluster1); assertEquals(1.0/3.0, evaluator.score(clusters), 1e-6); final Cluster<DoublePoint> cluster2 = new Cluster<>(); for (DoublePoint p : points2) { cluster2.addPoint(p); } clusters.add(cluster2); assertEquals(6.148148148, evaluator.score(clusters), 1e-6); } @Test public void testOrdering() { assertTrue(evaluator.isBetterScore(10, 20)); assertFalse(evaluator.isBetterScore(20, 1)); } }
{ "pile_set_name": "Github" }
package test import ( "bytes" "encoding/json" "fmt" "strings" "testing" "github.com/davecgh/go-spew/spew" fuzz "github.com/google/gofuzz" jsoniter "github.com/json-iterator/go" ) func Test_Roundtrip(t *testing.T) { fz := fuzz.New().MaxDepth(10).NilChance(0.3) for i := 0; i < 100; i++ { var before typeForTest fz.Fuzz(&before) jbStd, err := json.Marshal(before) if err != nil { t.Fatalf("failed to marshal with stdlib: %v", err) } if len(strings.TrimSpace(string(jbStd))) == 0 { t.Fatal("stdlib marshal produced empty result and no error") } jbIter, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(before) if err != nil { t.Fatalf("failed to marshal with jsoniter: %v", err) } if len(strings.TrimSpace(string(jbIter))) == 0 { t.Fatal("jsoniter marshal produced empty result and no error") } if string(jbStd) != string(jbIter) { t.Fatalf("marshal expected:\n %s\ngot:\n %s\nobj:\n %s", indent(jbStd, " "), indent(jbIter, " "), dump(before)) } var afterStd typeForTest err = json.Unmarshal(jbIter, &afterStd) if err != nil { t.Fatalf("failed to unmarshal with stdlib: %v\nvia:\n %s", err, indent(jbIter, " ")) } var afterIter typeForTest err = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(jbIter, &afterIter) if err != nil { t.Fatalf("failed to unmarshal with jsoniter: %v\nvia:\n %s", err, indent(jbIter, " ")) } if fingerprint(afterStd) != fingerprint(afterIter) { t.Fatalf("unmarshal expected:\n %s\ngot:\n %s\nvia:\n %s", dump(afterStd), dump(afterIter), indent(jbIter, " ")) } } } const indentStr = "> " func fingerprint(obj interface{}) string { c := spew.ConfigState{ SortKeys: true, SpewKeys: true, } return c.Sprintf("%v", obj) } func dump(obj interface{}) string { cfg := spew.ConfigState{ Indent: indentStr, } return cfg.Sdump(obj) } func indent(src []byte, prefix string) string { var buf bytes.Buffer err := json.Indent(&buf, src, prefix, indentStr) if err != nil { return fmt.Sprintf("!!! %v", err) } return buf.String() } func benchmarkMarshal(t *testing.B, name string, fn func(interface{}) ([]byte, error)) { t.ReportAllocs() t.ResetTimer() var obj typeForTest fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3) fz.Fuzz(&obj) for i := 0; i < t.N; i++ { jb, err := fn(obj) if err != nil { t.Fatalf("%s failed to marshal:\n input: %s\n error: %v", name, dump(obj), err) } _ = jb } } func benchmarkUnmarshal(t *testing.B, name string, fn func(data []byte, v interface{}) error) { t.ReportAllocs() t.ResetTimer() var before typeForTest fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3) fz.Fuzz(&before) jb, err := json.Marshal(before) if err != nil { t.Fatalf("failed to marshal: %v", err) } for i := 0; i < t.N; i++ { var after typeForTest err = fn(jb, &after) if err != nil { t.Fatalf("%s failed to unmarshal:\n input: %q\n error: %v", name, string(jb), err) } } } func BenchmarkStandardMarshal(t *testing.B) { benchmarkMarshal(t, "stdlib", json.Marshal) } func BenchmarkStandardUnmarshal(t *testing.B) { benchmarkUnmarshal(t, "stdlib", json.Unmarshal) } func BenchmarkJSONIterMarshalFastest(t *testing.B) { benchmarkMarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Marshal) } func BenchmarkJSONIterUnmarshalFastest(t *testing.B) { benchmarkUnmarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Unmarshal) } func BenchmarkJSONIterMarshalDefault(t *testing.B) { benchmarkMarshal(t, "jsoniter-default", jsoniter.Marshal) } func BenchmarkJSONIterUnmarshalDefault(t *testing.B) { benchmarkUnmarshal(t, "jsoniter-default", jsoniter.Unmarshal) } func BenchmarkJSONIterMarshalCompatible(t *testing.B) { benchmarkMarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Marshal) } func BenchmarkJSONIterUnmarshalCompatible(t *testing.B) { benchmarkUnmarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal) }
{ "pile_set_name": "Github" }
package com.android.internal.telephony; public class ATParseEx extends RuntimeException { public ATParseEx() { } public ATParseEx(String s) { super(s); } }
{ "pile_set_name": "Github" }
#!python # -*- coding: utf-8 -*- """Example of qdarkstyle use for Python and Qt applications. This module a main window with every item that could be created with Qt Design (common ones) in the basic states (enabled/disabled), and (checked/unchecked) for those who has this attribute. Requirements: - Python 2 or Python 3 - QtPy - PyQt5 or PyQt4 or PySide2 or PySide - PyQtGraph or Qt.Py (if choosen) To run this example using PyQt5, simple do .. code-block:: python python example.py or .. code-block:: python python example.py --qt_from=pyqt5 Other options for qt_from are: pyqt5, pyside2, pyqt, pyside, qtpy, pyqtgraph, and qt.py. Also, you can run the example without dark theme (no_dark), to check for problems. .. code-block:: python python example.py --qt_from=pyqt5 --no_dark Note: qdarkstyle does not have to be installed to run the example. """ # Standard library imports import argparse import logging import os import sys import platform import time # Make the example runnable without the need to install and include ui sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/..')) sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/ui')) # Must be in this place, after setting path, to not need to install import qdarkstyle # noqa: E402 # Set log for debug logging.basicConfig(level=logging.DEBUG) _logger = logging.getLogger(__name__) # Constants SCREENSHOTS_PATH = qdarkstyle.IMAGES_PATH def main(): """Execute QDarkStyle example.""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--qt_from', default='qtpy', type=str, choices=['pyqt5', 'pyqt', 'pyside2', 'pyside', 'qtpy', 'pyqtgraph', 'qt.py'], help="Choose which binding and/or abstraction is to be used to run the example.") parser.add_argument('--no_dark', action='store_true', help="Exihibts the original window (without qdarkstyle).") parser.add_argument('--test', action='store_true', help="Auto close window after 2s.") parser.add_argument('--reset', action='store_true', help="Reset GUI settings (position, size) then opens.") parser.add_argument('--screenshots', action='store_true', help="Generate screenshots on images folder.") # Parsing arguments from command line args = parser.parse_args() # To avoid problems when testing without screen if args.test or args.screenshots: os.environ['QT_QPA_PLATFORM'] = 'offscreen' # Set QT_API variable before importing QtPy if args.qt_from in ['pyqt', 'pyqt5', 'pyside', 'pyside2']: os.environ['QT_API'] = args.qt_from elif args.qt_from == 'pyqtgraph': os.environ['QT_API'] = os.environ['PYQTGRAPH_QT_LIB'] elif args.qt_from in ['qt.py', 'qt']: try: import Qt except ImportError: print('Could not import Qt (Qt.Py)') else: os.environ['QT_API'] = Qt.__binding__ # QtPy imports from qtpy import API_NAME, QT_VERSION, PYQT_VERSION, PYSIDE_VERSION from qtpy import __version__ as QTPY_VERSION from qtpy.QtWidgets import (QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QPushButton, QMenu) from qtpy.QtCore import QTimer, Qt, QSettings # Set API_VERSION variable API_VERSION = '' if PYQT_VERSION: API_VERSION = PYQT_VERSION elif PYSIDE_VERSION: API_VERSION = PYSIDE_VERSION else: API_VERSION = 'Not found' # Import examples UI from mw_menus_ui import Ui_MainWindow as ui_main from dw_buttons_ui import Ui_DockWidget as ui_buttons from dw_displays_ui import Ui_DockWidget as ui_displays from dw_inputs_fields_ui import Ui_DockWidget as ui_inputs_fields from dw_inputs_no_fields_ui import Ui_DockWidget as ui_inputs_no_fields from dw_widgets_ui import Ui_DockWidget as ui_widgets from dw_views_ui import Ui_DockWidget as ui_views from dw_containers_tabs_ui import Ui_DockWidget as ui_containers_tabs from dw_containers_no_tabs_ui import Ui_DockWidget as ui_containers_no_tabs # create the application app = QApplication(sys.argv) app.setOrganizationName('QDarkStyle') app.setApplicationName('QDarkStyle Example') style = '' if not args.no_dark: style = qdarkstyle.load_stylesheet() app.setStyleSheet(style) # create main window window = QMainWindow() window.setObjectName('mainwindow') ui = ui_main() ui.setupUi(window) title = ("QDarkStyle Example - " + "(QDarkStyle=v" + qdarkstyle.__version__ + ", QtPy=v" + QTPY_VERSION + ", " + API_NAME + "=v" + API_VERSION + ", Qt=v" + QT_VERSION + ", Python=v" + platform.python_version() + ")") _logger.info(title) window.setWindowTitle(title) # Create docks for buttons dw_buttons = QDockWidget() dw_buttons.setObjectName('buttons') ui_buttons = ui_buttons() ui_buttons.setupUi(dw_buttons) window.addDockWidget(Qt.RightDockWidgetArea, dw_buttons) # Add actions on popup toolbuttons menu = QMenu() for action in ['Action A', 'Action B', 'Action C']: menu.addAction(action) ui_buttons.toolButtonDelayedPopup.setMenu(menu) ui_buttons.toolButtonInstantPopup.setMenu(menu) ui_buttons.toolButtonMenuButtonPopup.setMenu(menu) # Create docks for buttons dw_displays = QDockWidget() dw_displays.setObjectName('displays') ui_displays = ui_displays() ui_displays.setupUi(dw_displays) window.addDockWidget(Qt.RightDockWidgetArea, dw_displays) # Create docks for inputs - no fields dw_inputs_no_fields = QDockWidget() dw_inputs_no_fields.setObjectName('inputs_no_fields') ui_inputs_no_fields = ui_inputs_no_fields() ui_inputs_no_fields.setupUi(dw_inputs_no_fields) window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_no_fields) # Create docks for inputs - fields dw_inputs_fields = QDockWidget() dw_inputs_fields.setObjectName('inputs_fields') ui_inputs_fields = ui_inputs_fields() ui_inputs_fields.setupUi(dw_inputs_fields) window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_fields) # Create docks for widgets dw_widgets = QDockWidget() dw_widgets.setObjectName('widgets') ui_widgets = ui_widgets() ui_widgets.setupUi(dw_widgets) window.addDockWidget(Qt.LeftDockWidgetArea, dw_widgets) # Create docks for views dw_views = QDockWidget() dw_views.setObjectName('views') ui_views = ui_views() ui_views.setupUi(dw_views) window.addDockWidget(Qt.LeftDockWidgetArea, dw_views) # Create docks for containers - no tabs dw_containers_no_tabs = QDockWidget() dw_containers_no_tabs.setObjectName('containers_no_tabs') ui_containers_no_tabs = ui_containers_no_tabs() ui_containers_no_tabs.setupUi(dw_containers_no_tabs) window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_no_tabs) # Create docks for containters - tabs dw_containers_tabs = QDockWidget() dw_containers_tabs.setObjectName('containers_tabs') ui_containers_tabs = ui_containers_tabs() ui_containers_tabs.setupUi(dw_containers_tabs) window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_tabs) # Tabify right docks window.tabifyDockWidget(dw_buttons, dw_displays) window.tabifyDockWidget(dw_displays, dw_inputs_fields) window.tabifyDockWidget(dw_inputs_fields, dw_inputs_no_fields) # Tabify left docks window.tabifyDockWidget(dw_containers_no_tabs, dw_containers_tabs) window.tabifyDockWidget(dw_containers_tabs, dw_widgets) window.tabifyDockWidget(dw_widgets, dw_views) # Issues #9120, #9121 on Spyder qstatusbar = QStatusBar() qstatusbar.addWidget(QLabel('Issue Spyder #9120, #9121 - background not matching.')) qstatusbar.addWidget(QPushButton('OK')) # Add info also in status bar for screenshots get it qstatusbar.addWidget(QLabel('INFO: ' + title)) window.setStatusBar(qstatusbar) # Todo: add report info and other info in HELP graphical # Auto quit after 2s when in test mode if args.test: QTimer.singleShot(2000, app.exit) # Save screenshots for different displays and quit if args.screenshots: window.showFullScreen() create_screenshots(app, window, args.no_dark) # Do not read settings when taking screenshots - like reset else: _read_settings(window, args.reset, QSettings) window.showMaximized() app.exec_() _write_settings(window, QSettings) def _write_settings(window, QSettings): """Get window settings and write it into a file.""" settings = QSettings('QDarkStyle', 'QDarkStyle Example') settings.setValue('pos', window.pos()) settings.setValue('size', window.size()) settings.setValue('state', window.saveState()) def _read_settings(window, reset, QSettings): """Read and set window settings from a file.""" settings = QSettings('QDarkStyle', 'QDarkStyle Example') try: pos = settings.value('pos', window.pos()) size = settings.value('size', window.size()) state = settings.value('state', window.saveState()) except Exception: pos = settings.value('pos', window.pos(), type='QPoint') size = settings.value('size', window.size(), type='QSize') state = settings.value('state', window.saveState(), type='QByteArray') if not reset: window.restoreState(state) window.resize(size) window.move(pos) def create_screenshots(app, window, no_dark): """Save screenshots for different application views and quit.""" from qtpy.QtCore import QCoreApplication from qtpy.QtGui import QGuiApplication from qtpy.QtWidgets import QDockWidget, QTabWidget theme = 'no_dark' if no_dark else 'dark' print('\nCreating {} screenshots'.format(theme)) docks = window.findChildren(QDockWidget) tabs = window.findChildren(QTabWidget) widget_data = { 'containers_no_tabs_buttons.png': [ 'Containers - No Tabs', 'Buttons', ], 'containers_tabs_displays.png': [ 'Containers - Tabs', 'Displays', ], 'widgets_inputs_fields.png': [ 'Widgets', 'Inputs - Fields', ], 'views_inputs_no_fields.png': [ 'Views', 'Inputs - No Fields', ] } # Central widget tabs of with examples, reset positions tab = [tab for tab in tabs if tab.count() >= 12][0] tab.setCurrentIndex(0) QCoreApplication.processEvents() for fname_suffix, dw_titles in widget_data.items(): png_path = os.path.join(SCREENSHOTS_PATH, theme + '_' + fname_suffix) print('\t' + png_path) for dw in docks: if dw.windowTitle() in dw_titles: print('Evidencing : ', dw.windowTitle()) dw.raise_() dw.show() QCoreApplication.processEvents() # Attention: any change in update, processEvent and sleep calls # make those screenshots not working, specially the first one. # It seems that processEvents are not working properly window.update() window.showFullScreen() QCoreApplication.processEvents() time.sleep(0.5) QCoreApplication.processEvents() screen = QGuiApplication.primaryScreen() QCoreApplication.processEvents() pixmap = screen.grabWindow(window.winId()) # Yeah, this is duplicated to avoid screenshot problems screen = QGuiApplication.primaryScreen() QCoreApplication.processEvents() pixmap = screen.grabWindow(window.winId()) img = pixmap.toImage() img.save(png_path) QCoreApplication.processEvents() QCoreApplication.processEvents() window.close() print('\n') app.exit(sys.exit()) if __name__ == "__main__": sys.exit(main())
{ "pile_set_name": "Github" }
#X-Generator: crowdin.com requester.desc=Requester Addon requester.panel.mnemonic=w requester.panel.title=Requester requester.rightclickmenu.label=Open in Requester tab... requester.toolsmenu.label=Open message in Requester tab... requester.optionspanel.name=Requester requester.optionspanel.option.autoFocus.label=Set focus on Requester after adding a new tab
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause */ /* Copyright(c) 2018-2019 Realtek Corporation */ #ifndef __RTW8822C_TABLE_H__ #define __RTW8822C_TABLE_H__ extern const struct rtw_table rtw8822c_mac_tbl; extern const struct rtw_table rtw8822c_agc_tbl; extern const struct rtw_table rtw8822c_bb_tbl; extern const struct rtw_table rtw8822c_bb_pg_type0_tbl; extern const struct rtw_table rtw8822c_rf_a_tbl; extern const struct rtw_table rtw8822c_rf_b_tbl; extern const struct rtw_table rtw8822c_txpwr_lmt_type0_tbl; extern const struct rtw_table rtw8822c_txpwr_lmt_type5_tbl; extern const struct rtw_table rtw8822c_dpk_afe_no_dpk_tbl; extern const struct rtw_table rtw8822c_dpk_afe_is_dpk_tbl; extern const struct rtw_table rtw8822c_dpk_mac_bb_tbl; extern const struct rtw_table rtw8822c_array_mp_cal_init_tbl; #endif
{ "pile_set_name": "Github" }
CREAT DATABASE `icloud` USE `icloud` CREATE TABLE `file` ( `id` int(10) unsigned NOT NULL auto_increment, `filename` varchar(255) NOT NULL COMMENT '文件名', `filepath` varchar(600) NOT NULL COMMENT '文件路径', `filesize` varchar(255) NOT NULL COMMENT '文件大小', `createtime` date default NULL COMMENT '创建日期', `canshare` int(2) NOT NULL COMMENT '0表示私有 1表示共享', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL auto_increment, `username` varchar(255) NOT NULL, `password` varchar(16) NOT NULL, `comment` varchar(255) default NULL COMMENT '注释', `isvip` int(11) NOT NULL COMMENT '1是vip 0不是', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
{ "pile_set_name": "Github" }
<?php /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright 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. * */ namespace FacebookAds\Enum; abstract class AbstractEnum implements EnumInstanceInterface { /** * @var array|null */ protected $map = null; /** * @var array|null */ protected $names = null; /** * @var array|null */ protected $values = null; /** * @var array|null */ protected $valuesMap = null; /** * @var AbstractEnum[] */ protected static $instances = array(); /** * @return string */ static function className() { return get_called_class(); } /** * @return AbstractEnum */ public static function getInstance() { $fqn = get_called_class(); if (!array_key_exists($fqn, static::$instances)) { static::$instances[$fqn] = new static(); } return static::$instances[$fqn]; } /** * @return array */ public function getArrayCopy() { if ($this->map === null) { $this->map = (new \ReflectionClass(get_called_class())) ->getConstants(); } return $this->map; } /** * @return array */ public function getNames() { if ($this->names === null) { $this->names = array_keys($this->getArrayCopy()); } return $this->names; } /** * @return array */ public function getValues() { if ($this->values === null) { $this->values = array_values($this->getArrayCopy()); } return $this->values; } /** * @return array */ public function getValuesMap() { if ($this->valuesMap === null) { $this->valuesMap = array_fill_keys($this->getValues(), null); } return $this->valuesMap; } /** * @param string|int|float $name * @return mixed */ public function getValueForName($name) { $copy = $this->getArrayCopy(); return array_key_exists($name, $copy) ? $copy[$name] : null; } /** * @param string|int|float $name * @return mixed * @throws \InvalidArgumentException */ public function assureValueForName($name) { $value = $this->getValueForName($name); if ($value === null) { throw new \InvalidArgumentException( 'Unknown name "'.$name.'" in '.static::className()); } return $value; } /** * @param string|int|float $name * @return bool */ public function isValid($name) { return array_key_exists($name, $this->getArrayCopy()); } /** * @param string|int|float $name * @throws \InvalidArgumentException */ public function assureIsValid($name) { if (!array_key_exists($name, $this->getArrayCopy())) { throw new \InvalidArgumentException( 'Unknown name "'.$name.'" in '.static::className()); } } /** * @param string|int|float $value * @return bool */ public function isValidValue($value) { return array_key_exists($value, $this->getValuesMap()); } /** * @param mixed $value * @throws \InvalidArgumentException */ public function assureIsValidValue($value) { if (!$this->isValidValue($value)) { throw new \InvalidArgumentException( '"'.$value.'", not a valid value in '.static::className()); } } }
{ "pile_set_name": "Github" }
//logs.js const util = require('../../utils/util.js') Page({ data: { logs: [] }, onLoad: function () { this.setData({ logs: (wx.getStorageSync('logs') || []).map(log => { return util.formatTime(new Date(log)) }) }) } })
{ "pile_set_name": "Github" }
# /etc/ipsec.conf - Libreswan IPsec configuration file version 2.0 config setup # put the logs in /tmp for the UMLs, so that we can operate # without syslogd, which seems to break on UMLs plutodebug=all logfile=/tmp/pluto.log logtime=no logappend=no conn westnet-eastnet-camellia also=westnet-eastnet-ipv4-psk #ike=camellia-sha1 esp=camellia-sha1 include /testing/baseconfigs/all/etc/ipsec.d/ipsec.conf.common
{ "pile_set_name": "Github" }
namespace ClassLib009 { public class Class033 { public static string Property => "ClassLib009"; } }
{ "pile_set_name": "Github" }
// Copyright (C) 2009 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_TYPE_SAFE_UNIOn_h_ #define DLIB_TYPE_SAFE_UNIOn_h_ #include "type_safe_union_kernel_abstract.h" #include "../algs.h" #include "../noncopyable.h" #include "../serialize.h" #include <new> #include <iostream> namespace dlib { // ---------------------------------------------------------------------------------------- struct _void{}; inline void serialize( const _void&, std::ostream&){} inline void deserialize( _void&, std::istream&){} // ---------------------------------------------------------------------------------------- template < typename T1, typename T2 = _void, typename T3 = _void, typename T4 = _void, typename T5 = _void, typename T6 = _void, typename T7 = _void, typename T8 = _void, typename T9 = _void, typename T10 = _void, typename T11 = _void, typename T12 = _void, typename T13 = _void, typename T14 = _void, typename T15 = _void, typename T16 = _void, typename T17 = _void, typename T18 = _void, typename T19 = _void, typename T20 = _void > class type_safe_union : noncopyable { /*! CONVENTION - is_empty() == (type_identity == 0) - contains<T>() == (type_identity == get_type_id<T>()) - mem.get() == the block of memory on the stack which is where objects in the union are stored !*/ private: template <typename T, typename U> void invoke_on ( T& obj, U& item ) const { obj(item); } template <typename T> void invoke_on ( T& , _void ) const { } const static size_t max_size = tmax<tmax<tmax<tmax<tmax<tmax<tmax<tmax<tmax<tmax< tmax<tmax<tmax<tmax<tmax<tmax<tmax<tmax<tmax<sizeof(T1), sizeof(T2)>::value, sizeof(T3)>::value, sizeof(T4)>::value, sizeof(T5)>::value, sizeof(T6)>::value, sizeof(T7)>::value, sizeof(T8)>::value, sizeof(T9)>::value, sizeof(T10)>::value, sizeof(T11)>::value, sizeof(T12)>::value, sizeof(T13)>::value, sizeof(T14)>::value, sizeof(T15)>::value, sizeof(T16)>::value, sizeof(T17)>::value, sizeof(T18)>::value, sizeof(T19)>::value, sizeof(T20)>::value; // -------------------------------------------- // member data stack_based_memory_block<max_size> mem; int type_identity; // -------------------------------------------- template <typename T> void validate_type() { // ERROR: You are trying to get a type of object that isn't // representable by this type_safe_union. I.e. The given // type T isn't one of the ones given to this object's template // arguments. COMPILE_TIME_ASSERT(( is_same_type<T,T1>::value || is_same_type<T,T2>::value || is_same_type<T,T3>::value || is_same_type<T,T4>::value || is_same_type<T,T5>::value || is_same_type<T,T6>::value || is_same_type<T,T7>::value || is_same_type<T,T8>::value || is_same_type<T,T9>::value || is_same_type<T,T10>::value || is_same_type<T,T11>::value || is_same_type<T,T12>::value || is_same_type<T,T13>::value || is_same_type<T,T14>::value || is_same_type<T,T15>::value || is_same_type<T,T16>::value || is_same_type<T,T17>::value || is_same_type<T,T18>::value || is_same_type<T,T19>::value || is_same_type<T,T20>::value )); } struct destruct_helper { template <typename T> void operator() (T& item) const { item.~T(); } }; void destruct ( ) /*! ensures - #is_empty() == true !*/ { // destruct whatever is in this object apply_to_contents(destruct_helper()); // mark this object as being empty type_identity = 0; } template <typename T> void construct ( ) { if (type_identity != get_type_id<T>()) { destruct(); new(mem.get()) T(); type_identity = get_type_id<T>(); } } template <typename T> void construct ( const T& item ) { if (type_identity != get_type_id<T>()) { destruct(); new(mem.get()) T(item); type_identity = get_type_id<T>(); } } template <typename T> T& unchecked_get( ) /*! requires - contains<T>() == true ensures - returns a non-const reference to the T object !*/ { return *static_cast<T*>(mem.get()); } template <typename T> const T& unchecked_get( ) const /*! requires - contains<T>() == true ensures - returns a const reference to the T object !*/ { return *static_cast<const T*>(mem.get()); } template <typename T> void operator() (T& item) /* This function is used by the swap function of this class. See that function to see how this works. */ { exchange(get<T>(), item); } public: typedef T1 type1; typedef T2 type2; typedef T3 type3; typedef T4 type4; typedef T5 type5; typedef T6 type6; typedef T7 type7; typedef T8 type8; typedef T9 type9; typedef T10 type10; typedef T11 type11; typedef T12 type12; typedef T13 type13; typedef T14 type14; typedef T15 type15; typedef T16 type16; typedef T17 type17; typedef T18 type18; typedef T19 type19; typedef T20 type20; type_safe_union() : type_identity(0) { } template <typename T> type_safe_union ( const T& item ) : type_identity(0) { validate_type<T>(); construct(item); } ~type_safe_union() { destruct(); } template <typename T> static int get_type_id ( ) { if (is_same_type<T,T1>::value) return 1; if (is_same_type<T,T2>::value) return 2; if (is_same_type<T,T3>::value) return 3; if (is_same_type<T,T4>::value) return 4; if (is_same_type<T,T5>::value) return 5; if (is_same_type<T,T6>::value) return 6; if (is_same_type<T,T7>::value) return 7; if (is_same_type<T,T8>::value) return 8; if (is_same_type<T,T9>::value) return 9; if (is_same_type<T,T10>::value) return 10; if (is_same_type<T,T11>::value) return 11; if (is_same_type<T,T12>::value) return 12; if (is_same_type<T,T13>::value) return 13; if (is_same_type<T,T14>::value) return 14; if (is_same_type<T,T15>::value) return 15; if (is_same_type<T,T16>::value) return 16; if (is_same_type<T,T17>::value) return 17; if (is_same_type<T,T18>::value) return 18; if (is_same_type<T,T19>::value) return 19; if (is_same_type<T,T20>::value) return 20; // return a number that doesn't match any of the // valid states of type_identity return -1; } template <typename T> bool contains ( ) const { return type_identity == get_type_id<T>(); } bool is_empty ( ) const { return type_identity == 0; } public: template < typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7, typename t8, typename t9, typename t10, typename t11, typename t12, typename t13, typename t14, typename t15, typename t16, typename t17, typename t18, typename t19, typename t20 > friend void serialize ( const type_safe_union<t1,t2,t3,t4,t5,t6,t7,t8,t9,t10, t11,t12,t13,t14,t15,t16,t17,t18,t19,t20>& item, std::ostream& out ); template < typename T > void apply_to_contents ( T& obj ) { switch (type_identity) { // do nothing because we are empty case 0: break; case 1: invoke_on(obj,unchecked_get<T1>()); break; case 2: invoke_on(obj,unchecked_get<T2>()); break; case 3: invoke_on(obj,unchecked_get<T3>()); break; case 4: invoke_on(obj,unchecked_get<T4>()); break; case 5: invoke_on(obj,unchecked_get<T5>()); break; case 6: invoke_on(obj,unchecked_get<T6>()); break; case 7: invoke_on(obj,unchecked_get<T7>()); break; case 8: invoke_on(obj,unchecked_get<T8>()); break; case 9: invoke_on(obj,unchecked_get<T9>()); break; case 10: invoke_on(obj,unchecked_get<T10>()); break; case 11: invoke_on(obj,unchecked_get<T11>()); break; case 12: invoke_on(obj,unchecked_get<T12>()); break; case 13: invoke_on(obj,unchecked_get<T13>()); break; case 14: invoke_on(obj,unchecked_get<T14>()); break; case 15: invoke_on(obj,unchecked_get<T15>()); break; case 16: invoke_on(obj,unchecked_get<T16>()); break; case 17: invoke_on(obj,unchecked_get<T17>()); break; case 18: invoke_on(obj,unchecked_get<T18>()); break; case 19: invoke_on(obj,unchecked_get<T19>()); break; case 20: invoke_on(obj,unchecked_get<T20>()); break; } } template < typename T > void apply_to_contents ( const T& obj ) { switch (type_identity) { // do nothing because we are empty case 0: break; case 1: invoke_on(obj,unchecked_get<T1>()); break; case 2: invoke_on(obj,unchecked_get<T2>()); break; case 3: invoke_on(obj,unchecked_get<T3>()); break; case 4: invoke_on(obj,unchecked_get<T4>()); break; case 5: invoke_on(obj,unchecked_get<T5>()); break; case 6: invoke_on(obj,unchecked_get<T6>()); break; case 7: invoke_on(obj,unchecked_get<T7>()); break; case 8: invoke_on(obj,unchecked_get<T8>()); break; case 9: invoke_on(obj,unchecked_get<T9>()); break; case 10: invoke_on(obj,unchecked_get<T10>()); break; case 11: invoke_on(obj,unchecked_get<T11>()); break; case 12: invoke_on(obj,unchecked_get<T12>()); break; case 13: invoke_on(obj,unchecked_get<T13>()); break; case 14: invoke_on(obj,unchecked_get<T14>()); break; case 15: invoke_on(obj,unchecked_get<T15>()); break; case 16: invoke_on(obj,unchecked_get<T16>()); break; case 17: invoke_on(obj,unchecked_get<T17>()); break; case 18: invoke_on(obj,unchecked_get<T18>()); break; case 19: invoke_on(obj,unchecked_get<T19>()); break; case 20: invoke_on(obj,unchecked_get<T20>()); break; } } template < typename T > void apply_to_contents ( T& obj ) const { switch (type_identity) { // do nothing because we are empty case 0: break; case 1: invoke_on(obj,unchecked_get<T1>()); break; case 2: invoke_on(obj,unchecked_get<T2>()); break; case 3: invoke_on(obj,unchecked_get<T3>()); break; case 4: invoke_on(obj,unchecked_get<T4>()); break; case 5: invoke_on(obj,unchecked_get<T5>()); break; case 6: invoke_on(obj,unchecked_get<T6>()); break; case 7: invoke_on(obj,unchecked_get<T7>()); break; case 8: invoke_on(obj,unchecked_get<T8>()); break; case 9: invoke_on(obj,unchecked_get<T9>()); break; case 10: invoke_on(obj,unchecked_get<T10>()); break; case 11: invoke_on(obj,unchecked_get<T11>()); break; case 12: invoke_on(obj,unchecked_get<T12>()); break; case 13: invoke_on(obj,unchecked_get<T13>()); break; case 14: invoke_on(obj,unchecked_get<T14>()); break; case 15: invoke_on(obj,unchecked_get<T15>()); break; case 16: invoke_on(obj,unchecked_get<T16>()); break; case 17: invoke_on(obj,unchecked_get<T17>()); break; case 18: invoke_on(obj,unchecked_get<T18>()); break; case 19: invoke_on(obj,unchecked_get<T19>()); break; case 20: invoke_on(obj,unchecked_get<T20>()); break; } } template < typename T > void apply_to_contents ( const T& obj ) const { switch (type_identity) { // do nothing because we are empty case 0: break; case 1: invoke_on(obj,unchecked_get<T1>()); break; case 2: invoke_on(obj,unchecked_get<T2>()); break; case 3: invoke_on(obj,unchecked_get<T3>()); break; case 4: invoke_on(obj,unchecked_get<T4>()); break; case 5: invoke_on(obj,unchecked_get<T5>()); break; case 6: invoke_on(obj,unchecked_get<T6>()); break; case 7: invoke_on(obj,unchecked_get<T7>()); break; case 8: invoke_on(obj,unchecked_get<T8>()); break; case 9: invoke_on(obj,unchecked_get<T9>()); break; case 10: invoke_on(obj,unchecked_get<T10>()); break; case 11: invoke_on(obj,unchecked_get<T11>()); break; case 12: invoke_on(obj,unchecked_get<T12>()); break; case 13: invoke_on(obj,unchecked_get<T13>()); break; case 14: invoke_on(obj,unchecked_get<T14>()); break; case 15: invoke_on(obj,unchecked_get<T15>()); break; case 16: invoke_on(obj,unchecked_get<T16>()); break; case 17: invoke_on(obj,unchecked_get<T17>()); break; case 18: invoke_on(obj,unchecked_get<T18>()); break; case 19: invoke_on(obj,unchecked_get<T19>()); break; case 20: invoke_on(obj,unchecked_get<T20>()); break; } } void swap ( type_safe_union& item ) { // if both *this and item contain the same type of thing if (type_identity == item.type_identity) { // swap the things in this and item. item.apply_to_contents(*this); } else if (type_identity == 0) { // *this doesn't contain anything. So swap this and item and // then destruct item. item.apply_to_contents(*this); item.destruct(); } else if (item.type_identity == 0) { // *this doesn't contain anything. So swap this and item and // then destruct this. apply_to_contents(item); destruct(); } else { type_safe_union temp; // swap *this into temp apply_to_contents(temp); // swap item into *this item.apply_to_contents(*this); // swap temp into item temp.apply_to_contents(item); } } template <typename T> T& get( ) { validate_type<T>(); construct<T>(); return *static_cast<T*>(mem.get()); } template <typename T> type_safe_union& operator= ( const T& item) { get<T>() = item; return *this; } }; // ---------------------------------------------------------------------------------------- template < typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20 > inline void swap ( type_safe_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11,T12,T13,T14,T15,T16,T17,T18,T19,T20>& a, type_safe_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11,T12,T13,T14,T15,T16,T17,T18,T19,T20>& b ) { a.swap(b); } // ---------------------------------------------------------------------------------------- template < typename from, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20 > struct is_convertible<from, type_safe_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11,T12,T13,T14,T15,T16,T17,T18,T19,T20> > { const static bool value = is_convertible<from,T1>::value || is_convertible<from,T2>::value || is_convertible<from,T3>::value || is_convertible<from,T4>::value || is_convertible<from,T5>::value || is_convertible<from,T6>::value || is_convertible<from,T7>::value || is_convertible<from,T8>::value || is_convertible<from,T9>::value || is_convertible<from,T10>::value || is_convertible<from,T11>::value || is_convertible<from,T12>::value || is_convertible<from,T13>::value || is_convertible<from,T14>::value || is_convertible<from,T15>::value || is_convertible<from,T16>::value || is_convertible<from,T17>::value || is_convertible<from,T18>::value || is_convertible<from,T19>::value || is_convertible<from,T20>::value; }; // ---------------------------------------------------------------------------------------- namespace impl_tsu { struct serialize_helper { /* This is a function object to help us serialize type_safe_unions */ std::ostream& out; serialize_helper(std::ostream& out_): out(out_) {} template <typename T> void operator() (const T& item) const { serialize(item, out); } }; } template < typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20 > void serialize ( const type_safe_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11,T12,T13,T14,T15,T16,T17,T18,T19,T20>& item, std::ostream& out ) { try { // save the type_identity serialize(item.type_identity, out); item.apply_to_contents(dlib::impl_tsu::serialize_helper(out)); } catch (serialization_error& e) { throw serialization_error(e.info + "\n while serializing an object of type type_safe_union"); } } // ---------------------------------------------------------------------------------------- template < typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20 > void deserialize ( type_safe_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11,T12,T13,T14,T15,T16,T17,T18,T19,T20>& item, std::istream& in ) { try { typedef type_safe_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11,T12,T13,T14,T15,T16,T17,T18,T19,T20> tsu_type; int type_identity; deserialize(type_identity, in); switch (type_identity) { // swap an empty type_safe_union into item since it should be in the empty state case 0: tsu_type().swap(item); break; case 1: deserialize(item.template get<T1>(), in); break; case 2: deserialize(item.template get<T2>(), in); break; case 3: deserialize(item.template get<T3>(), in); break; case 4: deserialize(item.template get<T4>(), in); break; case 5: deserialize(item.template get<T5>(), in); break; case 6: deserialize(item.template get<T6>(), in); break; case 7: deserialize(item.template get<T7>(), in); break; case 8: deserialize(item.template get<T8>(), in); break; case 9: deserialize(item.template get<T9>(), in); break; case 10: deserialize(item.template get<T10>(), in); break; case 11: deserialize(item.template get<T11>(), in); break; case 12: deserialize(item.template get<T12>(), in); break; case 13: deserialize(item.template get<T13>(), in); break; case 14: deserialize(item.template get<T14>(), in); break; case 15: deserialize(item.template get<T15>(), in); break; case 16: deserialize(item.template get<T16>(), in); break; case 17: deserialize(item.template get<T17>(), in); break; case 18: deserialize(item.template get<T18>(), in); break; case 19: deserialize(item.template get<T19>(), in); break; case 20: deserialize(item.template get<T20>(), in); break; default: throw serialization_error("Corrupt data detected while deserializing type_safe_union"); } } catch (serialization_error& e) { throw serialization_error(e.info + "\n while deserializing an object of type type_safe_union"); } } // ---------------------------------------------------------------------------------------- } #endif // DLIB_TYPE_SAFE_UNIOn_h_
{ "pile_set_name": "Github" }
"""Tests for mongodbstore plugin.""" import unittest from unittest import mock from pymongo import errors from cloudmarker.stores import mongodbstore class MongoDBStoreTest(unittest.TestCase): """Tests for mongodbstore plugin.""" @mock.patch('cloudmarker.stores.mongodbstore.MongoClient') def test_write_without_flush(self, mock_client): # Set buffer size of 3. store = mongodbstore.MongoDBStore(buffer_size=3) # But insert only 2 records. for i in range(2): record = {'record_type': 'foo', 'i': i} store.write(record) # Verify that buffer is not being flushed via client. mock_method = mock_client()['fake_db']['fake_record_type'].insert_many mock_method.assert_not_called() @mock.patch('cloudmarker.stores.mongodbstore.MongoClient') def test_write_with_flush(self, mock_client): # Set buffer size of 3. store = mongodbstore.MongoDBStore(buffer_size=3) # Then insert 3 records. for i in range(3): record = {'record_type': 'foo', 'i': i} store.write(record) # Verify that buffer is being flushed via client. mock_method = mock_client()['fake_db']['fake_record_type'].insert_many mock_method.assert_called_once_with(mock.ANY, ordered=mock.ANY) @mock.patch('cloudmarker.stores.mongodbstore.MongoClient') def test_done(self, mock_client): # Write only one record to store with default buffer size. store = mongodbstore.MongoDBStore() store.write({'record_type': 'foo', 'i': 0}) # Call store's done(), so that it flushes the pending buffer. store.done() # Verify that the pending buffer is flushed via client. mock_method = mock_client()['fake_db']['fake_record_type'].insert_many mock_method.assert_called_once_with(mock.ANY, ordered=mock.ANY) # Verify that client is being closed. mock_method = mock_client().close mock_method.assert_called_once_with() @mock.patch('cloudmarker.stores.mongodbstore.MongoClient') def test_bulk_write_error(self, mock_client): # Configure the mock client such that it raises BulkWriteError # on insertion of records. mock_method = mock.Mock(side_effect=errors.BulkWriteError(None)) mock_client()['fake_db']['fake_record_type'].insert_many = mock_method # Ensure that the error is handled gracefully without a crash. store = mongodbstore.MongoDBStore() store.write({'record_type': 'foo', 'i': 0}) store.done()
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Spaghetti: Web Server Security Scanner # # @url: https://github.com/m4ll0k/Spaghetti # @author: Momo Outaadi (M4ll0k) # @license: See the file 'doc/LICENSE' from lib.net import http from lib.utils import printer import re class HtmlObject(): def __init__(self,url,agent,proxy,redirect): self.url = url self.printer = printer.Printer() self.http = http.Http(agent=agent,proxy=proxy,redirect=redirect) def Run(self): info = { 'name' : 'HtmlObject', 'author' : 'Momo Outaadi (@M4ll0k)', 'description' : 'HTML Object' } try: resp = self.http.Send(self.url) if re.search(r'<object.*?>.*?<\/object>',resp._content,re.I): self.printer.plus('Found HTML Object. Logs the existence of HTML object tags.') except Exception: pass
{ "pile_set_name": "Github" }
// boost heap: concepts // // Copyright (C) 2010 Tim Blechmann // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_HEAP_CONCEPTS_HPP #define BOOST_HEAP_CONCEPTS_HPP #include <boost/concept_check.hpp> namespace boost { namespace heap { template <class C> struct PriorityQueue: boost::ForwardContainer<C> { typedef typename C::iterator iterator; typedef typename C::const_iterator const_iterator; typedef typename C::allocator_type allocator_type; typedef typename C::value_compare value_compare; typedef typename C::value_type value_type; typedef typename C::const_reference const_reference; BOOST_CONCEPT_USAGE(PriorityQueue) { BOOST_CONCEPT_ASSERT((boost::Assignable<value_type>)); BOOST_CONCEPT_ASSERT((boost::Container<C>)); BOOST_CONCEPT_ASSERT((boost::EqualityComparable<C>)); BOOST_CONCEPT_ASSERT((boost::Comparable<C>)); BOOST_CONCEPT_ASSERT((boost::Const_BinaryPredicate<value_compare, value_type, value_type>)); c.swap(c2); c.clear(); a = c.get_allocator(); typename PriorityQueue::value_type v; c.push(v); v = c.top(); c.pop(); cmp = c.value_comp(); // verify tags has_ordered_iterators = C::has_ordered_iterators; is_mergable = C::is_mergable; is_stable = C::is_stable; } private: C c, c2; allocator_type a; typename C::value_type v; value_compare cmp; bool has_ordered_iterators, is_mergable, is_stable; }; template <class C> struct MergablePriorityQueue: PriorityQueue<C> { BOOST_CONCEPT_USAGE(MergablePriorityQueue) { C c, c2; c.merge(c2); } }; template <class C> struct MutablePriorityQueue: PriorityQueue<C> { typedef typename C::handle_type handle_type; BOOST_CONCEPT_USAGE(MutablePriorityQueue) { BOOST_CONCEPT_ASSERT((boost::Assignable<typename MutablePriorityQueue::handle_type>)); typename MutablePriorityQueue::value_type v; typename MutablePriorityQueue::handle_type h = c.push(v); typename MutablePriorityQueue::handle_type h2 = c.push(v); c.update(h, v); c.increase(h, v); c.decrease(h, v); c.update(h); c.increase(h); c.decrease(h); equal = (h == h2); not_equal = (h != h2); h2 = h; } C c; bool equal, not_equal; }; }} #endif /* BOOST_HEAP_CONCEPTS_HPP */
{ "pile_set_name": "Github" }
namespace ClassLib078 { public class Class040 { public static string Property => "ClassLib078"; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 1.3 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">1.3</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1">this is my long string</data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> [base64 mime encoded serialized .NET Framework object] </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> [base64 mime encoded string representing a byte array form of the .NET Framework object] </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>1.3</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> </root>
{ "pile_set_name": "Github" }
package main //comment import () <warning descr="Empty declaration 'import ()'">import ()<caret></warning> func _() { }
{ "pile_set_name": "Github" }
/* * Some or all of this work - Copyright (c) 2006 - 2020, Intel Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ Include ("../../../../runtime/collections/functional/name/name.asl") Include ("../../../../runtime/collections/functional/name/package.asl") /* Excluded until the bug 182 is fixed */ Include ("../../../../runtime/collections/functional/name/method.asl") Include ("../../../../runtime/collections/functional/name/function.asl")
{ "pile_set_name": "Github" }
# Copyright (C) Christopher Currie 2003. Permission to copy, use, # modify, sell and distribute this software is granted provided this # copyright notice appears in all copies. This software is provided # "as is" without express or implied warranty, and with no claim as to # its suitability for any purpose. # Please see http://article.gmane.org/gmane.comp.lib.boost.build/3389/ # for explanation why it's a separate toolset. import common, gcc, builtin from b2.build import feature, toolset, type, action, generators from b2.util.utility import * toolset.register ('darwin') toolset.inherit_generators ('darwin', [], 'gcc') toolset.inherit_flags ('darwin', 'gcc') toolset.inherit_rules ('darwin', 'gcc') def init (version = None, command = None, options = None): options = to_seq (options) condition = common.check_init_parameters ('darwin', None, ('version', version)) command = common.get_invocation_command ('darwin', 'g++', command) common.handle_options ('darwin', condition, command, options) gcc.init_link_flags ('darwin', 'darwin', condition) # Darwin has a different shared library suffix type.set_generated_target_suffix ('SHARED_LIB', ['<toolset>darwin'], 'dylib') # we need to be able to tell the type of .dylib files type.register_suffixes ('dylib', 'SHARED_LIB') feature.feature ('framework', [], ['free']) toolset.flags ('darwin.compile', 'OPTIONS', '<link>shared', ['-dynamic']) toolset.flags ('darwin.compile', 'OPTIONS', None, ['-Wno-long-double', '-no-cpp-precomp']) toolset.flags ('darwin.compile.c++', 'OPTIONS', None, ['-fcoalesce-templates']) toolset.flags ('darwin.link', 'FRAMEWORK', '<framework>') # This is flag is useful for debugging the link step # uncomment to see what libtool is doing under the hood # toolset.flags ('darwin.link.dll', 'OPTIONS', None, '[-Wl,-v']) action.register ('darwin.compile.cpp', None, ['$(CONFIG_COMMAND) $(ST_OPTIONS) -L"$(LINKPATH)" -o "$(<)" "$(>)" "$(LIBRARIES)" -l$(FINDLIBS-SA) -l$(FINDLIBS-ST) -framework$(_)$(FRAMEWORK) $(OPTIONS)']) # TODO: how to set 'bind LIBRARIES'? action.register ('darwin.link.dll', None, ['$(CONFIG_COMMAND) -dynamiclib -L"$(LINKPATH)" -o "$(<)" "$(>)" "$(LIBRARIES)" -l$(FINDLIBS-SA) -l$(FINDLIBS-ST) -framework$(_)$(FRAMEWORK) $(OPTIONS)']) def darwin_archive (manager, targets, sources, properties): pass action.register ('darwin.archive', darwin_archive, ['ar -c -r -s $(ARFLAGS) "$(<:T)" "$(>:T)"'])
{ "pile_set_name": "Github" }
<!DOCTYPE xsl:stylesheet [ <!-- External DTD defines entities: components :- QNames of component-level elements blocks :- QNames of block-level elements metadata-content :- XPath expression matching metadata styles author-content :- XPath expression matching author styles admonition :- XPath expression matching admonition styles admonition-title :- XPath expression matching admonition title styles --> <!ENTITY % ext SYSTEM "blocks2dbk.dtd"> %ext; ]> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dbk='http://docbook.org/ns/docbook' xmlns:rnd='http://docbook.org/ns/docbook/roundtrip' xmlns:xlink='http://www.w3.org/1999/xlink'> <!-- $Id: blocks2dbk.xsl 8137 2008-10-09 03:37:56Z balls $ --> <!-- Stylesheet to convert word processing docs to DocBook --> <!-- This stylesheet processes the output of sections2blocks.xsl --> <xsl:output indent="yes" method="xml" cdata-section-elements='dbk:programlisting dbk:literallayout'/> <!-- ================================================== --> <!-- Parameters --> <!-- ================================================== --> <xsl:param name='docbook5'>0</xsl:param> <xsl:param name="nest.sections">1</xsl:param> <xsl:strip-space elements='*'/> <xsl:preserve-space elements='dbk:para dbk:emphasis'/> <xsl:template match="&components; | &blocks;"> <xsl:choose> <xsl:when test='self::dbk:article and count(dbk:book) = 1 and count(dbk:info|dbk:book) &lt;= 2'> <xsl:apply-templates select='dbk:book'/> </xsl:when> <xsl:when test='self::dbk:article and *[1][self::dbk:para] and *[1]/@rnd:style != "article-title" and contains(*[1]/@rnd:style, "-title")'> <xsl:variable name='element-name' select='substring-before(*[1]/@rnd:style, "-title")'/> <xsl:element name='{$element-name}' namespace='http://docbook.org/ns/docbook'> <dbk:info> <xsl:apply-templates select='*[1]' mode='rnd:metadata'/> </dbk:info> <xsl:apply-templates/> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:copy> <xsl:call-template name='rnd:attributes'/> <xsl:variable name='metadata'> <xsl:apply-templates select='*[1]' mode='rnd:metadata'/> </xsl:variable> <xsl:if test='$metadata'> <dbk:info> <xsl:copy-of select='$metadata'/> </dbk:info> </xsl:if> <xsl:apply-templates/> </xsl:copy> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:book-component'> <xsl:variable name='element-name' select='substring-before(*[1]/@rnd:style, "-title")'/> <xsl:element name='{$element-name}' namespace='http://docbook.org/ns/docbook'> <dbk:info> <xsl:apply-templates select='*[1]' mode='rnd:metadata'/> </dbk:info> <xsl:apply-templates/> </xsl:element> </xsl:template> <xsl:template match="dbk:para" name='rnd:para'> <!-- Some elements are normally suppressed, since they are processed in a different context. If this parameter is false then the element will be processed normally. --> <xsl:param name='suppress' select='true()'/> <!-- This paragraph may be in a sidebar --> <xsl:variable name='sidebar' select='preceding-sibling::*[self::dbk:para and @rnd:style = "sidebar-title"][1]'/> <!-- This paragraph may be in the textobject of a table or figure --> <xsl:variable name='table' select='preceding-sibling::dbk:informaltable[1]'/> <xsl:variable name='figure' select='preceding-sibling::dbk:para[@rnd:style = "informalfigure-imagedata" or (dbk:inlinemediaobject and count(*) = 1 and normalize-space(.) = "")][1]'/> <xsl:variable name='caption' select='following-sibling::dbk:para[@rnd:style = "caption" or @rnd:style = "Caption"]'/> <xsl:choose> <!-- continue style paragraphs are handled in context --> <xsl:when test='$suppress and @rnd:style = "para-continue"'/> <!-- Certain elements gather the following paragraph --> <xsl:when test='$suppress and preceding-sibling::*[1][self::dbk:para and @rnd:style = "example-title"]'/> <xsl:when test='$suppress and $sidebar and not(preceding-sibling::dbk:para[(not(@rnd:style) or @rnd:style = "") and preceding-sibling::*[preceding-sibling::*[generate-id() = generate-id($sidebar)]]])'/> <!-- Separate processing is performed for table/figure titles and captions --> <xsl:when test='$suppress and @rnd:style = "table-title" and following-sibling::*[1][self::dbk:informaltable|self::dbk:para[@rnd:style = "informalfigure-imagedata"]|self::dbk:para[dbk:inlinemediaobject and count(*) = 1 and normalize-space() = ""]]'/> <xsl:when test='$suppress and @rnd:style = "figure-title" and following-sibling::*[1][self::dbk:para][@rnd:style = "informalfigure-imagedata" or (dbk:inlinemediaobject and count(*) = 1 and normalize-space(.) = "")]'/> <xsl:when test='$suppress and (@rnd:style = "caption" or @rnd:style = "Caption") and (preceding-sibling::*[self::dbk:informaltable] or preceding-sibling::*[self::dbk:para][@rnd:style = "informalfigure-imagedata" or (dbk:inlinemediaobject and count(*) = 1 and normalize-space(.) = "")])'/> <xsl:when test='$suppress and $table and $caption and generate-id($caption/preceding-sibling::dbk:informaltable[1]) = generate-id($table)'/> <xsl:when test='$suppress and $figure and $caption and generate-id($caption/preceding-sibling::dbk:para[@rnd:style = "informalfigure-imagedata" or (dbk:inlinemediaobject and count(*) = 1 and normalize-space(.) = "")][1]) = generate-id($figure)'/> <xsl:when test='@rnd:style = "imagedata-metadata" or @rnd:style = "table-metadata"'/> <!-- Ignore empty paragraphs --> <xsl:when test='(not(@rnd:style) or @rnd:style = "") and normalize-space(.) = "" and not(*)'/> <!-- Image inline or block? --> <xsl:when test='(not(@rnd:style) or @rnd:style = "") and normalize-space(.) = "" and count(*) = 1 and dbk:inlinemediaobject'> <xsl:apply-templates/> </xsl:when> <xsl:when test='not(@rnd:style) or @rnd:style = "" or @rnd:style = "para-continue"'> <dbk:para> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:para> </xsl:when> <xsl:when test='@rnd:style = "xinclude"' xmlns:xi='http://www.w3.org/2001/XInclude'> <xi:include> <xsl:attribute name='href'> <xsl:apply-templates mode='rnd:xinclude'/> </xsl:attribute> </xi:include> </xsl:when> <xsl:when test='$suppress and preceding-sibling::*[1]/self::dbk:para[&admonition-title;]'/> <xsl:when test='&admonition-title;'> <xsl:element name='{substring-before(@rnd:style, "-title")}' namespace='http://docbook.org/ns/docbook'> <xsl:call-template name='rnd:attributes'/> <dbk:title> <xsl:apply-templates/> </dbk:title> <xsl:apply-templates select='following-sibling::*[1]'> <xsl:with-param name='suppress' select='false()'/> </xsl:apply-templates> <xsl:apply-templates select='following-sibling::*[2]' mode='rnd:continue'/> </xsl:element> </xsl:when> <xsl:when test='starts-with(@rnd:style, "itemizedlist") or starts-with(@rnd:style, "orderedlist")'> <xsl:variable name='stop.node' select='following-sibling::dbk:para[not(@rnd:style) or (not(starts-with(@rnd:style, "itemizedlist") or starts-with(@rnd:style, "orderedlist")) and @rnd:style != "para-continue")][1]'/> <xsl:choose> <xsl:when test='translate(substring-after(@rnd:style, "list"), "0123456789", "") != "" or substring-after(@rnd:style, "list") = ""'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code' select='"list-bad-level"'/> <xsl:with-param name='message'>style "<xsl:value-of select='@rnd:style'/>" is not a valid list style</xsl:with-param> </xsl:call-template> </xsl:when> <!-- TODO: the previous para-continue may not be associated with a list --> <!-- NB. Look back at the previous paragraph. There may be intervening tables or images. --> <xsl:when test='preceding-sibling::dbk:para[1][starts-with(@rnd:style, "itemizedlist") or starts-with(@rnd:style, "orderedlist") or @rnd:style = "para-continue"]'/> <xsl:when test='substring-after(@rnd:style, "list") != 1'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>list-wrong-level</xsl:with-param> <xsl:with-param name='message'>list started at the wrong level</xsl:with-param> </xsl:call-template> </xsl:when> <xsl:when test='$stop.node'> <xsl:element name='{substring-before(@rnd:style, "1")}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates select='.|following-sibling::dbk:para[@rnd:style = current()/@rnd:style][following-sibling::*[generate-id() = generate-id($stop.node)]]' mode='rnd:listitem'/> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:element name='{substring-before(@rnd:style, "1")}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates select='.|following-sibling::dbk:para[@rnd:style = current()/@rnd:style]' mode='rnd:listitem'/> </xsl:element> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test='@rnd:style = "programlisting" and preceding-sibling::*[1][self::dbk:para and @rnd:style = "programlisting"]'/> <xsl:when test='@rnd:style = "literallayout" and preceding-sibling::*[1][self::dbk:para and @rnd:style = "literallayout"]'/> <xsl:when test='@rnd:style = "programlisting" or @rnd:style = "literallayout"'> <xsl:variable name='stop.node' select='following-sibling::dbk:para[@rnd:style != current()/@rnd:style][1]'/> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates/> <xsl:choose> <xsl:when test='$stop.node'> <xsl:apply-templates select='following-sibling::dbk:para[following-sibling::*[generate-id() = generate-id($stop.node)]]' mode='rnd:programlisting'/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='following-sibling::dbk:para' mode='rnd:programlisting'/> </xsl:otherwise> </xsl:choose> </xsl:element> </xsl:when> <xsl:when test='@rnd:style = "example-title"'> <xsl:element name='{substring-before(@rnd:style, "-title")}' namespace='http://docbook.org/ns/docbook'> <xsl:call-template name='rnd:attributes'/> <dbk:title> <xsl:apply-templates/> </dbk:title> <xsl:apply-templates select='following-sibling::*[1]'> <xsl:with-param name='suppress' select='false()'/> </xsl:apply-templates> </xsl:element> </xsl:when> <xsl:when test='@rnd:style = "sidebar-title"'> <!-- TODO: next sidebar should stop this sidebar --> <xsl:variable name='stop.node' select='following-sibling::dbk:para[(not(@rnd:style) or @rnd:style = "") and normalize-space(.) = ""][1]'/> <dbk:sidebar> <xsl:call-template name='rnd:attributes'/> <dbk:info> <dbk:title> <xsl:apply-templates/> </dbk:title> </dbk:info> <xsl:choose> <xsl:when test='$stop.node'> <xsl:apply-templates select='following-sibling::*[following-sibling::*[generate-id() = generate-id($stop.node)]]' mode='rnd:sidebar'/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='following-sibling::*' mode='rnd:sidebar'/> </xsl:otherwise> </xsl:choose> </dbk:sidebar> </xsl:when> <xsl:when test='&admonition;'> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:call-template name='rnd:attributes'/> <dbk:para> <xsl:apply-templates/> </dbk:para> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:continue'/> </xsl:element> </xsl:when> <!-- TODO: make sure this is in a bibliography. If not, create a bibliolist. --> <xsl:when test='@rnd:style = "bibliomixed"'> <dbk:bibliomixed> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:bibliomixed> </xsl:when> <xsl:when test='@rnd:style = "biblioentry-title"'> <dbk:biblioentry> <xsl:call-template name='rnd:attributes'/> <dbk:title> <xsl:apply-templates/> </dbk:title> <xsl:if test='following-sibling::*[1][&metadata-content;]'> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:if> </dbk:biblioentry> </xsl:when> <xsl:when test='@rnd:style = "blockquote-attribution" and preceding-sibling::*[1][self::dbk:para][@rnd:style = "blockquote-title" or @rnd:style = "blockquote"]'/> <xsl:when test='@rnd:style = "blockquote-attribution"'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>improper-blockquote-attribution</xsl:with-param> <xsl:with-param name='message'>blockquote attribution must follow a blockquote title</xsl:with-param> </xsl:call-template> </xsl:when> <xsl:when test='@rnd:style = "blockquote" or @rnd:style = "blockquote-title"'> <xsl:choose> <xsl:when test='@rnd:style = "blockquote" and preceding-sibling::*[1][self::dbk:para][starts-with(@rnd:style, "blockquote")]'/> <xsl:otherwise> <xsl:variable name='stop.node' select='following-sibling::*[not(@rnd:style = "blockquote" or @rnd:style = "blockquote-attribution")][1]'/> <dbk:blockquote> <xsl:call-template name='rnd:attributes'/> <xsl:if test='@rnd:style = "blockquote-title"'> <dbk:info> <dbk:title> <xsl:apply-templates/> </dbk:title> </dbk:info> </xsl:if> <xsl:choose> <xsl:when test='$stop.node'> <xsl:apply-templates select='following-sibling::*[following-sibling::*[generate-id() = generate-id($stop.node)]][@rnd:style = "blockquote-attribution"]' mode='rnd:blockquote-attribution'/> <xsl:apply-templates select='self::*[@rnd:style = "blockquote"] | following-sibling::*[following-sibling::*[generate-id() = generate-id($stop.node)]]' mode='rnd:blockquote'/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='following-sibling::*[@rnd:style = "blockquote-attribution"]' mode='rnd:blockquote-attribution'/> <xsl:apply-templates select='self::*[@rnd:style = "blockquote"] | following-sibling::*' mode='rnd:blockquote'/> </xsl:otherwise> </xsl:choose> </dbk:blockquote> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test='@rnd:style = "bridgehead"'> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </xsl:element> </xsl:when> <xsl:when test='@rnd:style = "formalpara-title"'> <dbk:formalpara> <dbk:title> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:title> <xsl:choose> <xsl:when test='following-sibling::*[1][self::dbk:para][@rnd:style = "formalpara"]'> <dbk:para> <xsl:call-template name='rnd:attributes'> <xsl:with-param name='node' select='following-sibling::*[1]'/> </xsl:call-template> <xsl:apply-templates select='following-sibling::*[1]/node()'/> </dbk:para> </xsl:when> </xsl:choose> </dbk:formalpara> </xsl:when> <xsl:when test='@rnd:style = "formalpara" and preceding-sibling::*[1][self::dbk:para][@rnd:style = "formalpara-title"]'/> <xsl:when test='@rnd:style = "formalpara"'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>formalpara-notitle</xsl:with-param> <xsl:with-param name='message'>formalpara used without a title</xsl:with-param> </xsl:call-template> </xsl:when> <xsl:when test='@rnd:style = "informalfigure-imagedata"'> <xsl:variable name='caption.next' select='following-sibling::dbk:para[@rnd:style = "caption" or @rnd:style = "Caption"][1]'/> <xsl:variable name='metadata' select='preceding-sibling::*[1][self::dbk:para][@rnd:style = "imagedata-metadata"]'/> <xsl:choose> <xsl:when test='preceding-sibling::*[1][self::dbk:para][@rnd:style = "figure-title"] or ($metadata and preceding-sibling::*[2][self::dbk:para][@rnd:style = "figure-title"])'> <dbk:figure> <xsl:call-template name='rnd:attributes'/> <dbk:info> <dbk:title> <xsl:choose> <xsl:when test='$metadata'> <xsl:apply-templates select='preceding-sibling::*[2]/node()'/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='preceding-sibling::*[1]/node()'/> </xsl:otherwise> </xsl:choose> </dbk:title> </dbk:info> <dbk:mediaobject> <dbk:imageobject> <dbk:imagedata> <xsl:attribute name='fileref'> <xsl:choose> <xsl:when test='dbk:inlinemediaobject/dbk:imageobject/dbk:imagedata/@fileref != ""'> <xsl:value-of select='dbk:inlinemediaobject/dbk:imageobject/dbk:imagedata/@fileref'/> </xsl:when> <xsl:otherwise> <xsl:value-of select='.'/> </xsl:otherwise> </xsl:choose> </xsl:attribute> <xsl:call-template name='rnd:imagedata-attributes'> <xsl:with-param name='metadata' select='$metadata'/> </xsl:call-template> </dbk:imagedata> </dbk:imageobject> </dbk:mediaobject> <xsl:call-template name='rnd:figure-text-caption'> <xsl:with-param name='caption' select='$caption.next'/> </xsl:call-template> </dbk:figure> </xsl:when> <xsl:when test='preceding-sibling::*[1][self::dbk:para][@rnd:style = "table-title"] or ($metadata and preceding-sibling::*[2][self::dbk:para][@rnd:style = "table-title"])'> <dbk:table> <xsl:call-template name='rnd:attributes'/> <dbk:info> <dbk:title> <xsl:choose> <xsl:when test='$metadata'> <xsl:apply-templates select='preceding-sibling::*[2]/node()'/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='preceding-sibling::*[1]/node()'/> </xsl:otherwise> </xsl:choose> </dbk:title> </dbk:info> <dbk:mediaobject> <dbk:imageobject> <dbk:imagedata> <xsl:attribute name='fileref'> <xsl:choose> <xsl:when test='dbk:inlinemediaobject/dbk:imageobject/dbk:imagedata/@fileref != ""'> <xsl:value-of select='dbk:inlinemediaobject/dbk:imageobject/dbk:imagedata/@fileref'/> </xsl:when> <xsl:otherwise> <xsl:value-of select='.'/> </xsl:otherwise> </xsl:choose> </xsl:attribute> <xsl:call-template name='rnd:imagedata-attributes'> <xsl:with-param name='metadata' select='$metadata'/> </xsl:call-template> </dbk:imagedata> </dbk:imageobject> </dbk:mediaobject> <xsl:call-template name='rnd:figure-text-caption'> <xsl:with-param name='caption' select='$caption.next'/> </xsl:call-template> </dbk:table> </xsl:when> <xsl:otherwise> <dbk:informalfigure> <xsl:call-template name='rnd:attributes'/> <dbk:mediaobject> <dbk:imageobject> <dbk:imagedata> <xsl:attribute name='fileref'> <xsl:choose> <xsl:when test='dbk:inlinemediaobject/dbk:imageobject/dbk:imagedata/@fileref != ""'> <xsl:value-of select='dbk:inlinemediaobject/dbk:imageobject/dbk:imagedata/@fileref'/> </xsl:when> <xsl:otherwise> <xsl:value-of select='.'/> </xsl:otherwise> </xsl:choose> </xsl:attribute> <xsl:call-template name='rnd:imagedata-attributes'> <xsl:with-param name='metadata' select='$metadata'/> </xsl:call-template> </dbk:imagedata> </dbk:imageobject> </dbk:mediaobject> <xsl:call-template name='rnd:figure-text-caption'> <xsl:with-param name='caption' select='$caption.next'/> </xsl:call-template> </dbk:informalfigure> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test='(@rnd:style = "caption" or @rnd:style = "Caption") and preceding-sibling::*[(self::dbk:para and contains(@rnd:style, "imagedata")) or self::dbk:informaltable]'/> <xsl:when test='@rnd:style = "caption" or @rnd:style = "Caption"'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-caption</xsl:with-param> <xsl:with-param name='message'>caption does not follow table or figure</xsl:with-param> </xsl:call-template> </xsl:when> <xsl:when test='(contains(@rnd:style, "-title") or contains(@rnd:style, "-titleabbrev") or contains(@rnd:style, "-subtitle")) and not(starts-with(@rnd:style, "blockquote") or starts-with(@rnd:style, "formal"))'> <!-- TODO: check that no non-metadata elements occur before this paragraph --> </xsl:when> <!-- Metadata elements are handled in rnd:metadata mode --> <!-- TODO: check that no non-metadata elements occur before this paragraph --> <xsl:when test='&metadata-content;'/> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>unknown-style</xsl:with-param> <xsl:with-param name='message'>unknown paragraph style "<xsl:value-of select='@rnd:style'/>" encountered</xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Determine if the caption belongs to the current figure. If so, then process the textobject content and the caption. --> <xsl:template name='rnd:figure-text-caption'> <xsl:param name='caption' select='/..'/> <xsl:variable name='textobjs' select='following-sibling::*[following-sibling::*[generate-id() = generate-id($caption)]]'/> <xsl:choose> <xsl:when test='not($caption)'/> <!-- nothing to do --> <xsl:when test='$textobjs[self::dbk:informaltable | self::dbk:inlinemediaobject | self::dbk:para[@rnd:style = "informalfigure-imagedata" or @rnd:style = "mediaobject-imagedata"]]'/> <!-- caption belongs to something else --> <xsl:otherwise> <xsl:apply-templates select='$textobjs' mode='rnd:textobject'/> <xsl:apply-templates select='$caption' mode='rnd:caption'/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:para' mode='rnd:caption'> <dbk:caption> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:caption> </xsl:template> <xsl:template name='rnd:imagedata-attributes'> <xsl:param name='metadata' select='""'/> <xsl:choose> <xsl:when test='not($metadata)'/> <xsl:when test='contains($metadata, " ")'> <xsl:call-template name='rnd:imagedata-attributes'> <xsl:with-param name='metadata' select='substring-before($metadata, " ")'/> </xsl:call-template> <xsl:call-template name='rnd:imagedata-attributes'> <xsl:with-param name='metadata' select='substring-after($metadata, " ")'/> </xsl:call-template> </xsl:when> <xsl:when test='not(contains($metadata, "="))'> <xsl:call-template name='rnd:warning'> <xsl:with-param name='code' select='"imagedata-missing-value"'/> <xsl:with-param name='message'> <xsl:text>imagedata-metadata missing value for attribute "</xsl:text> <xsl:value-of select='$metadata'/> <xsl:text>"</xsl:text> </xsl:with-param> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:variable name='name' select='translate(normalize-space(substring-before($metadata, "=")), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")'/> <xsl:variable name='value' select='translate(normalize-space(substring-after($metadata, "=")), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")'/> <xsl:choose> <xsl:when test='$name = "scalefit"'> <xsl:attribute name='scalefit'> <xsl:choose> <xsl:when test='$value = "1" or $value = "yes" or $value = "true"'>1</xsl:when> <xsl:otherwise>0</xsl:otherwise> </xsl:choose> </xsl:attribute> </xsl:when> <xsl:when test='$name = "align" or $name = "contentdepth" or $name = "contentwidth" or $name = "depth" or $name = "scale" or $name = "valign" or $name = "width"'> <!-- TODO: check enumerate values--> <xsl:attribute name='{$name}'> <xsl:value-of select='$value'/> </xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code' select='"imagedata-unknown-attribute"'/> <xsl:with-param name='message'> <xsl:text>imagedata-metadata unknown attribute "</xsl:text> <xsl:value-of select='$name'/> <xsl:text>"</xsl:text> </xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:emphasis'> <xsl:choose> <xsl:when test='not(@rnd:style) and @role = "italic"'> <xsl:copy> <xsl:apply-templates mode='rnd:copy'/> </xsl:copy> </xsl:when> <xsl:when test='not(@rnd:style) or @role'> <xsl:copy> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates mode='rnd:copy'/> </xsl:copy> </xsl:when> <xsl:when test='@rnd:style = preceding-sibling::node()[1][self::dbk:emphasis]/@rnd:style'/> <xsl:when test='@rnd:style = "emphasis"'> <xsl:copy> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates mode='rnd:copy'/> <xsl:apply-templates select='following-sibling::node()[1]' mode='rnd:emphasis'/> </xsl:copy> </xsl:when> <xsl:when test='@rnd:style = "emphasis-bold" or @rnd:style = "emphasis-strong"'> <xsl:copy> <xsl:attribute name='role'>bold</xsl:attribute> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates mode='rnd:copy'/> <xsl:apply-templates select='following-sibling::node()[1]' mode='rnd:emphasis'/> </xsl:copy> </xsl:when> <xsl:when test='@rnd:style = "emphasis-underline"'> <xsl:copy> <xsl:attribute name='role'>underline</xsl:attribute> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates mode='rnd:copy'/> <xsl:apply-templates select='following-sibling::node()[1]' mode='rnd:emphasis'/> </xsl:copy> </xsl:when> <xsl:when test='@rnd:style = "citetitle" or @rnd:style = "literal" or @rnd:style = "sgmltag"'> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> <xsl:apply-templates select='following-sibling::node()[1]' mode='rnd:emphasis'/> </xsl:element> </xsl:when> <xsl:when test='@rnd:style = "Hyperlink" and parent::dbk:link'> <!-- This occurs in a hyperlink; parent should be dbk:link --> <xsl:apply-templates/> </xsl:when> <xsl:when test='@rnd:style = "Hyperlink"'> <!-- dbk:link is missing --> <dbk:link xlink:href='{.}'> <xsl:apply-templates/> </dbk:link> </xsl:when> <!-- In rare circumstances, Word inserts an empty element that appears to be something like a space in the editor --> <xsl:when test='(@rnd:style = "EndnoteReference" or @rnd:style = "FootnoteReference") and . = ""'> <xsl:text> </xsl:text> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>unknown-style</xsl:with-param> <xsl:with-param name='message'>unknown character span style "<xsl:value-of select='@rnd:style'/>" encountered</xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Coalesce emphasis elements into a single element --> <xsl:template match='dbk:emphasis' mode='rnd:emphasis'> <xsl:choose> <xsl:when test='@rnd:style = preceding-sibling::node()[self::dbk:emphasis]/@rnd:style'> <xsl:apply-templates/> <xsl:apply-templates select='following-sibling::node()[1]' mode='rnd:emphasis'/> </xsl:when> </xsl:choose> </xsl:template> <xsl:template match='*|text()' mode='rnd:emphasis'/> <xsl:template match='dbk:emphasis' mode='rnd:personname-emphasis'> <xsl:param name='style'/> <xsl:choose> <xsl:when test='@rnd:style = $style'> <xsl:apply-templates/> <xsl:apply-templates select='following-sibling::dbk:emphasis[1]' mode='rnd:personname-emphasis'> <xsl:with-param name='style' select='$style'/> </xsl:apply-templates> </xsl:when> </xsl:choose> </xsl:template> <xsl:template match='*|text()' mode='rnd:emphasis'/> <xsl:template match='dbk:subscript|dbk:superscript'> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates/> </xsl:copy> </xsl:template> <!-- Images --> <xsl:template match='dbk:inlinemediaobject'> <xsl:choose> <xsl:when test='not(preceding-sibling::*|following-sibling::*) and normalize-space(..) = ""'> <xsl:variable name='next.captioned' select='ancestor::dbk:para/following-sibling::*[self::dbk:informaltable or self::dbk:para[dbk:inlinemediaobject and count(*) = 1 and normalize-space() = ""]][1]'/> <xsl:variable name='caption' select='ancestor::dbk:para/following-sibling::dbk:para[@rnd:style = "caption" or @rnd:style = "Caption"]'/> <xsl:variable name='metadata'> <xsl:apply-templates select='ancestor::dbk:para/following-sibling::*[1]' mode='rnd:metadata'/> </xsl:variable> <dbk:figure> <xsl:if test='ancestor::dbk:para/preceding-sibling::*[1][self::dbk:para][@rnd:style = "figure-title"] or $metadata'> <dbk:info> <xsl:if test='ancestor::dbk:para/preceding-sibling::*[1][self::dbk:para][@rnd:style = "figure-title"]'> <dbk:title> <xsl:apply-templates select='ancestor::dbk:para/preceding-sibling::*[1]/node()'/> </dbk:title> </xsl:if> <xsl:copy-of select='$metadata'/> </dbk:info> </xsl:if> <dbk:mediaobject> <xsl:apply-templates mode='rnd:copy'/> </dbk:mediaobject> <xsl:choose> <xsl:when test='not($caption)'/> <xsl:when test='not($next.captioned)'> <xsl:apply-templates select='ancestor::dbk:para/following-sibling::*[following-sibling::*[generate-id() = generate-id($caption)]][not(&metadata-content;)]' mode='rnd:figure'/> <xsl:apply-templates select='$caption' mode='rnd:caption'/> </xsl:when> <!-- Does caption belong to this image or next.captioned? - Only if it belongs to this image do we process it here. --> <xsl:when test='$next.captioned[preceding-sibling::*[generate-id() = generate-id($caption)]]'> <xsl:apply-templates select='ancestor::dbk:para/following-sibling::*[following-sibling::*[generate-id() = generate-id($caption)]][not(&metadata-content;)]' mode='rnd:figure'/> <xsl:apply-templates select='$caption' mode='rnd:caption'/> </xsl:when> <!-- otherwise caption does not belong to this figure --> </xsl:choose> </dbk:figure> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:copy'/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:para[@rnd:style = "caption" or @rnd:style = "Caption"]' mode='rnd:caption'> <dbk:caption> <dbk:para> <xsl:apply-templates/> </dbk:para> </dbk:caption> </xsl:template> <xsl:template match='*' mode='rnd:caption'/> <xsl:template match='*' mode='rnd:figure'> <xsl:call-template name='rnd:para'> <xsl:with-param name='suppress' select='false()'/> </xsl:call-template> </xsl:template> <!-- Sidebars --> <xsl:template match='*' mode='rnd:sidebar'> <xsl:call-template name='rnd:para'> <xsl:with-param name='suppress' select='false()'/> </xsl:call-template> </xsl:template> <!-- Lists --> <xsl:template match='dbk:para' mode='rnd:listitem'> <dbk:listitem> <dbk:para> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:para> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:continue'/> <!-- Handle nested lists --> <xsl:variable name='list-type' select='concat(substring-before(@rnd:style, "list"), "list")'/> <xsl:variable name='list-level' select='substring-after(@rnd:style, $list-type)'/> <!-- Assuming only five levels of list nesting. - This is probably better done in a previous stage using grouping. --> <xsl:variable name='stop.node' select='following-sibling::dbk:para[@rnd:style != concat("itemizedlist", $list-level + 1) and @rnd:style != concat("orderedlist", $list-level + 1) and @rnd:style != concat("itemizedlist", $list-level + 2) and @rnd:style != concat("orderedlist", $list-level + 2) and @rnd:style != concat("itemizedlist", $list-level + 3) and @rnd:style != concat("orderedlist", $list-level + 3) and @rnd:style != "para-continue"][1]'/> <xsl:variable name='nested' select='following-sibling::dbk:para[@rnd:style = concat("itemizedlist", $list-level + 1) or @rnd:style = concat("orderedlist", $list-level + 1)][1]'/> <xsl:choose> <!-- Is there a nested list at all? --> <xsl:when test='following-sibling::*[self::dbk:para and @rnd:style != "para-continue"][1][@rnd:style != concat("itemizedlist", $list-level + 1) and @rnd:style != concat("orderedlist", $list-level + 1)]'/> <xsl:when test='following-sibling::dbk:para[@rnd:style = concat("itemizedlist", $list-level + 1) or @rnd:style = concat("orderedlist", $list-level + 1)] and $stop.node'> <xsl:element name='{concat(substring-before($nested/@rnd:style, "list"), "list")}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates select='following-sibling::dbk:para[@rnd:style = concat("itemizedlist", $list-level + 1) or @rnd:style = concat("orderedlist", $list-level + 1)][following-sibling::*[generate-id() = generate-id($stop.node)]]' mode='rnd:listitem'/> </xsl:element> </xsl:when> <xsl:when test='following-sibling::dbk:para[@rnd:style = concat("itemizedlist", $list-level + 1) or @rnd:style = concat("orderedlist", $list-level + 1)]'> <xsl:element name='{concat(substring-before($nested/@rnd:style, "list"), "list")}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates select='following-sibling::dbk:para[@rnd:style = concat("itemizedlist", $list-level + 1) or @rnd:style = concat("orderedlist", $list-level + 1)]' mode='rnd:listitem'/> </xsl:element> </xsl:when> </xsl:choose> </dbk:listitem> </xsl:template> <!-- Blockquotes --> <xsl:template match='dbk:para' mode='rnd:blockquote'> <xsl:choose> <xsl:when test='@rnd:style ="blockquote-attribution"'/> <xsl:when test='@rnd:style ="blockquote-title"'/> <xsl:otherwise> <dbk:para> <xsl:apply-templates/> </dbk:para> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:para' mode='rnd:blockquote-attribution'> <xsl:if test='@rnd:style ="blockquote-attribution"'> <dbk:attribution> <xsl:apply-templates/> </dbk:attribution> </xsl:if> </xsl:template> <!-- Metadata --> <xsl:template match='dbk:para' mode='rnd:metadata'> <xsl:choose> <xsl:when test='@rnd:style = "biblioentry-title" and parent::dbk:bibliography|parent::dbk:bibliodiv'/> <xsl:when test='@rnd:style = "biblioentry-title"'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-metadata</xsl:with-param> <xsl:with-param name='message'>style "<xsl:value-of select='@rnd:style'/>" must not be metadata for parent "<xsl:value-of select='local-name(..)'/>"</xsl:with-param> </xsl:call-template> </xsl:when> <xsl:when test='@rnd:style = "abstract-title" or @rnd:style = "abstract"'> <xsl:variable name='stop.node' select='following-sibling::dbk:para[@rnd:style != "abstract"][1]'/> <xsl:choose> <xsl:when test='$stop.node'> <dbk:abstract> <xsl:apply-templates select='.|following-sibling::dbk:para[@rnd:style = "abstract"][following-sibling::*[generate-id() = generate-id($stop.node)]]' mode='rnd:abstract'/> </dbk:abstract> <xsl:apply-templates select='$stop.node' mode='rnd:metadata'/> </xsl:when> <xsl:otherwise> <dbk:abstract> <xsl:apply-templates select='.|following-sibling::dbk:para[@rnd:style = "abstract"]' mode='rnd:abstract'/> </dbk:abstract> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test='@rnd:style = "legalnotice"'> <xsl:variable name='stop.node' select='following-sibling::dbk:para[@rnd:style != "legalnotice"][1]'/> <xsl:choose> <xsl:when test='$stop.node'> <dbk:legalnotice> <xsl:apply-templates select='.|following-sibling::dbk:para[@rnd:style = "legalnotice"][following-sibling::*[generate-id() = generate-id($stop.node)]]' mode='rnd:legalnotice'/> </dbk:legalnotice> <xsl:apply-templates select='$stop.node' mode='rnd:metadata'/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='.|following-sibling::dbk:para[@rnd:style = "legalnotice"]' mode='rnd:legalnotice'/> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test='@rnd:style = "keyword"'> <xsl:variable name='stop.node' select='following-sibling::*[not(self::dbk:para) or (self::dbk:para and @rnd:style != "keyword")][1]'/> <xsl:choose> <xsl:when test='$stop.node'> <dbk:keywordset> <xsl:call-template name='rnd:keyword'> <xsl:with-param name='nodes' select='.|following-sibling::dbk:para[@rnd:style = "keyword"][following-sibling::*[generate-id() = generate-id($stop.node)]]'/> </xsl:call-template> </dbk:keywordset> <xsl:apply-templates select='$stop.node' mode='rnd:metadata'/> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:keyword'> <xsl:with-param name='nodes' select='.|following-sibling::dbk:para[@rnd:style = "keyword"]'/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test='@rnd:style = "author"'> <dbk:author> <xsl:choose> <xsl:when test='dbk:emphasis[@rnd:style = "orgname"]'> <dbk:orgname> <xsl:apply-templates select='dbk:emphasis[@rnd:style = "orgname"]' mode='rnd:orgname'/> </dbk:orgname> <xsl:if test='*[not(@rnd:style = "orgname")]'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-author-orgname-combo</xsl:with-param> <xsl:with-param name='message'>character span "<xsl:value-of select='dbk:emphasis[@rnd:style != "orgname"][1]/@rnd:style'/>" not allowed in an author paragraph combined with orgname</xsl:with-param> </xsl:call-template> </xsl:if> </xsl:when> <xsl:otherwise> <dbk:personname> <!-- TODO: check style of author; mixed content or structured --> <xsl:apply-templates mode='rnd:personname'/> </dbk:personname> </xsl:otherwise> </xsl:choose> <xsl:apply-templates mode='rnd:author-personblurb'/> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:author'/> </dbk:author> <xsl:call-template name='rnd:resume-metadata'> <xsl:with-param name='node' select='following-sibling::*[1]'/> </xsl:call-template> </xsl:when> <xsl:when test='@rnd:style = "personblurb" or @rnd:style = "address" or @rnd:style = "affiliation" or @rnd:style = "contrib" or @rnd:style = "email"'/> <xsl:when test='@rnd:style = "releaseinfo" or @rnd:style = "date" or @rnd:style = "pubdate" or @rnd:style = "pagenums" or @rnd:style = "issuenum" or @rnd:style = "volumenum" or @rnd:style = "edition" or @rnd:style = "editor" or @rnd:style = "othercredit" or @rnd:style = "biblioid" or @rnd:style = "bibliosource" or @rnd:style = "bibliomisc" or @rnd:style = "revhistory" or @rnd:style = "revision"'> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates mode='rnd:metadata'/> </xsl:element> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> <xsl:when test='contains(@rnd:style, "-titleabbrev")'> <xsl:variable name='parent' select='substring-before(@rnd:style, "-titleabbrev")'/> <xsl:choose> <xsl:when test='$parent = local-name(..)'> <dbk:titleabbrev> <xsl:apply-templates mode='rnd:metadata'/> </dbk:titleabbrev> </xsl:when> <xsl:when test='(parent::dbk:article or parent::dbk:book-component) and preceding-sibling::dbk:para[@rnd:style = concat($parent, "-title")]'> <dbk:titleabbrev> <xsl:apply-templates mode='rnd:metadata'/> </dbk:titleabbrev> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-titleabbrev</xsl:with-param> <xsl:with-param name='message'>titleabbrev style "<xsl:value-of select='@rnd:style'/>" mismatches parent "<xsl:value-of select='local-name(..)'/>"</xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> <xsl:when test='contains(@rnd:style, "-title")'> <xsl:variable name='parent' select='substring-before(@rnd:style, "-title")'/> <xsl:choose> <xsl:when test='$parent = "table" or $parent = "figure"'> <dbk:title> <xsl:apply-templates mode='rnd:metadata'/> </dbk:title> </xsl:when> <xsl:when test='$parent = local-name(..)'> <dbk:title> <xsl:apply-templates mode='rnd:metadata'/> </dbk:title> </xsl:when> <xsl:when test='parent::dbk:book-component'> <dbk:title> <xsl:apply-templates mode='rnd:metadata'/> </dbk:title> </xsl:when> <xsl:when test='parent::dbk:article and not(../../..)'> <dbk:title> <xsl:apply-templates mode='rnd:metadata'/> </dbk:title> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-title</xsl:with-param> <xsl:with-param name='message'>title style "<xsl:value-of select='@rnd:style'/>" mismatches parent "<xsl:value-of select='local-name(..)'/>"</xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> <!-- Exception to normal subtitle handling is biblioentry-subtitle --> <xsl:when test='@rnd:style = "biblioentry-subtitle"'> <!-- TODO: check that this is in a biblioentry --> <dbk:subtitle> <xsl:apply-templates mode='rnd:metadata'/> </dbk:subtitle> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> <xsl:when test='contains(@rnd:style, "-subtitle")'> <xsl:variable name='parent' select='substring-before(@rnd:style, "-subtitle")'/> <xsl:choose> <xsl:when test='$parent = local-name(..)'> <dbk:subtitle> <xsl:apply-templates mode='rnd:metadata'/> </dbk:subtitle> </xsl:when> <xsl:when test='(parent::dbk:article or parent::dbk:book-component) and preceding-sibling::dbk:para[@rnd:style = concat($parent, "-title")]'> <dbk:subtitle> <xsl:apply-templates mode='rnd:metadata'/> </dbk:subtitle> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-subtitle</xsl:with-param> <xsl:with-param name='message'>subtitle style "<xsl:value-of select='@rnd:style'/>" mismatches parent "<xsl:value-of select='local-name(..)'/>"</xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> <xsl:when test='@rnd:style = "publisher-address" and preceding-sibling::*[1][not(self::dbk:para) or not(@rnd:style = "publisher")]'> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-publisher-address</xsl:with-param> <xsl:with-param name='message'>publisher-address must follow publisher</xsl:with-param> </xsl:call-template> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> <xsl:when test='@rnd:style = "publisher-address"'> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> <xsl:when test='@rnd:style = "publisher"'> <dbk:publisher> <dbk:publishername> <xsl:apply-templates/> </dbk:publishername> <xsl:if test='following-sibling::*[1][@rnd:style = "publisher-address"]'> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:publisher'/> </xsl:if> </dbk:publisher> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:metadata'/> </xsl:when> </xsl:choose> </xsl:template> <xsl:template name='rnd:keyword'> <xsl:param name='nodes' select='/..'/> <xsl:choose> <xsl:when test='not($nodes)'/> <xsl:otherwise> <xsl:call-template name='rnd:keyword-phrases'> <xsl:with-param name='text' select='$nodes[1]'/> </xsl:call-template> <xsl:call-template name='rnd:keyword'> <xsl:with-param name='nodes' select='$nodes[position() != 1]'/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name='rnd:keyword-phrases'> <xsl:param name='text'/> <xsl:choose> <xsl:when test='not($text)'/> <xsl:when test='contains($text, ",")'> <dbk:keyword> <xsl:value-of select='normalize-space(substring-before($text, ","))'/> </dbk:keyword> <xsl:call-template name='rnd:keyword-phrases'> <xsl:with-param name='text' select='substring-after($text, ",")'/> </xsl:call-template> </xsl:when> <xsl:otherwise> <dbk:keyword> <xsl:value-of select='normalize-space($text)'/> </dbk:keyword> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:emphasis' mode='rnd:metadata'> <xsl:choose> <xsl:when test='not(@rnd:style)'> <xsl:copy> <xsl:apply-templates mode='rnd:metadata'/> </xsl:copy> </xsl:when> <xsl:when test='@rnd:style = "Hyperlink" and parent::dbk:link'> <xsl:apply-templates mode='rnd:metadata'/> </xsl:when> <xsl:when test='@rnd:style = "Hyperlink"'> <dbk:link xlink:href='{.}'> <xsl:apply-templates mode='rnd:metadata'/> </dbk:link> </xsl:when> <xsl:otherwise> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates mode='rnd:metadata'/> </xsl:element> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:link' mode='rnd:metadata'> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates mode='rnd:metadata'/> </xsl:copy> </xsl:template> <xsl:template match='dbk:inlinemediaobject' mode='rnd:metadata'> <xsl:call-template name='rnd:copy'/> </xsl:template> <xsl:template match='*' mode='rnd:metadata'/> <xsl:template name='rnd:resume-metadata'> <xsl:param name='node' select='/..'/> <xsl:choose> <xsl:when test='$node[self::dbk:para][&author-content;]'> <xsl:call-template name='rnd:resume-metadata'> <xsl:with-param name='node' select='$node/following-sibling::*[1]'/> </xsl:call-template> </xsl:when> <xsl:when test='$node[self::dbk:para][&metadata-content;]'> <xsl:apply-templates select='$node' mode='rnd:metadata'/> </xsl:when> </xsl:choose> </xsl:template> <xsl:template match='dbk:para' mode='rnd:abstract'> <xsl:choose> <xsl:when test='@rnd:style = "abstract-title"'> <dbk:title> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:title> </xsl:when> <xsl:otherwise> <dbk:para> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:para> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:para' mode='rnd:legalnotice'> <dbk:para> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:para> </xsl:template> <xsl:template match='dbk:footnote' mode='rnd:personname'/> <xsl:template match='dbk:emphasis' mode='rnd:personname'> <!-- Need to check preceding emphasis for same style, but blocks pretty-prints and all text nodes are preserved in paragraph content. --> <xsl:variable name='previous' select='preceding-sibling::node()[not(self::text()) or (self::text() and normalize-space() != "")]'/> <!-- <xsl:comment> this style is <xsl:value-of select='@rnd:style'/>, previous style is <xsl:value-of select='$previous[last()]/@rnd:style'/> # previous <xsl:value-of select='count($previous)'/></xsl:comment> --> <xsl:choose> <!-- inlines are coalesced --> <xsl:when test='@rnd:style = $previous[last()][self::dbk:emphasis]/@rnd:style'/> <xsl:when test='@rnd:style = "honorific" or @rnd:style = "firstname" or @rnd:style = "lineage" or @rnd:style = "othername" or @rnd:style = "surname"'> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates/> <xsl:apply-templates select='following-sibling::dbk:emphasis[1]' mode='rnd:personname-emphasis'> <xsl:with-param name='style' select='@rnd:style'/> </xsl:apply-templates> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>bad-author-inline</xsl:with-param> <xsl:with-param name='message'>character span "<xsl:value-of select='@rnd:style'/>" not allowed in an author paragraph</xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='text()' mode='rnd:author-personblurb'/> <xsl:template match='dbk:emphasis' mode='rnd:author-personblurb'/> <xsl:template match='dbk:footnote' mode='rnd:author-personblurb'> <dbk:personblurb> <dbk:para> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates/> </xsl:copy> </dbk:para> </dbk:personblurb> </xsl:template> <xsl:template match='dbk:para' mode='rnd:author'> <xsl:choose> <xsl:when test='@rnd:style = "personblurb" and preceding-sibling::*[1][self::dbk:para and @rnd:style != "personblurb"]'> <dbk:personblurb> <xsl:apply-templates select='.' mode='rnd:personblurb'/> </dbk:personblurb> </xsl:when> <xsl:when test='@rnd:style = "personblurb"'> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:author'/> </xsl:when> <!-- Web and mail addresses may appear in a simplified form --> <xsl:when test='@rnd:style = "address"'> <xsl:choose> <xsl:when test='dbk:link and count(dbk:link) = count(*)'> <!-- simplified form --> <dbk:otheraddr> <xsl:apply-templates select='dbk:link' mode='rnd:otheraddr'/> </dbk:otheraddr> </xsl:when> <xsl:otherwise> <dbk:address> <xsl:apply-templates mode='rnd:author'/> </dbk:address> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:author'/> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test='@rnd:style = "affiliation"'> <dbk:affiliation> <xsl:choose> <xsl:when test='not(*)'> <dbk:jobtitle> <xsl:apply-templates mode='rnd:author'/> </dbk:jobtitle> </xsl:when> <xsl:otherwise> <xsl:apply-templates mode='rnd:author'/> </xsl:otherwise> </xsl:choose> </dbk:affiliation> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:author'/> </xsl:when> <xsl:when test='@rnd:style = "contrib" or @rnd:style = "email"'> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates mode='rnd:author'/> </xsl:element> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:author'/> </xsl:when> </xsl:choose> </xsl:template> <xsl:template match='dbk:link' mode='rnd:otheraddr'> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates mode='rnd:otheraddr'/> </xsl:copy> </xsl:template> <!-- TODO: not all of these inlines are allowed in all elements that are children of author. Need to further refine validation of inlines. --> <xsl:template match='dbk:emphasis' mode='rnd:author'> <xsl:choose> <xsl:when test='@rnd:style = "city" or @rnd:style = "country" or @rnd:style = "email" or @rnd:style = "fax" or @rnd:style = "jobtitle" or @rnd:style = "orgdiv" or @rnd:style = "orgname" or @rnd:style = "otheraddr" or @rnd:style = "phone" or @rnd:style = "pob" or @rnd:style = "postcode" or @rnd:style = "shortaffil" or @rnd:style = "state" or @rnd:style = "street"'> <xsl:element name='{@rnd:style}' namespace='http://docbook.org/ns/docbook'> <xsl:apply-templates/> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:call-template name='rnd:error'> <xsl:with-param name='code'>metadata-bad-inline</xsl:with-param> <xsl:with-param name='message'>character span "<xsl:value-of select='@rnd:style'/>" not allowed in author metadata</xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:para' mode='rnd:personblurb'> <xsl:if test='@rnd:style = "personblurb"'> <dbk:para> <xsl:apply-templates/> </dbk:para> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:personblurb'/> </xsl:if> </xsl:template> <xsl:template match='dbk:para' mode='rnd:publisher'> <xsl:if test='@rnd:style = "publisher-address"'> <dbk:address> <xsl:apply-templates/> </dbk:address> </xsl:if> </xsl:template> <xsl:template match='dbk:para' mode='rnd:programlisting'> <xsl:text>&#xa;</xsl:text> <xsl:apply-templates/> </xsl:template> <!-- Continuing paragraphs --> <xsl:template match='*' mode='rnd:continue'/> <xsl:template match='dbk:para' mode='rnd:continue'> <xsl:if test='@rnd:style = "para-continue"'> <dbk:para> <xsl:call-template name='rnd:attributes'/> <xsl:apply-templates/> </dbk:para> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:continue'/> </xsl:if> </xsl:template> <xsl:template match='dbk:informaltable' mode='rnd:continue'> <xsl:apply-templates select='.'> <xsl:with-param name='in-list' select='true()'/> </xsl:apply-templates> <xsl:apply-templates select='following-sibling::*[1]' mode='rnd:continue'/> </xsl:template> <!-- Tables --> <xsl:template match='dbk:informaltable'> <xsl:param name='in-list' select='false()'/> <xsl:choose> <xsl:when test='not($in-list) and preceding-sibling::dbk:para[1][starts-with(@rnd:style, "itemizedlist") or starts-with(@rnd:style, "orderedlist") or @rnd:style = "para-continue"]'/> <xsl:when test='preceding-sibling::*[1][self::dbk:para][@rnd:style ="table-title"]'> <dbk:table> <xsl:apply-templates select='@*' mode='rnd:copy'/> <dbk:info> <xsl:apply-templates select='preceding-sibling::dbk:para[1]' mode='rnd:table-title'/> </dbk:info> <xsl:call-template name='rnd:table-textobject'/> <xsl:apply-templates/> <xsl:call-template name='rnd:table-caption'/> </dbk:table> </xsl:when> <xsl:otherwise> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:call-template name='rnd:table-textobject'/> <xsl:apply-templates/> <xsl:call-template name='rnd:table-caption'/> </xsl:copy> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:tgroup'> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:if test='not(@cols)'> <xsl:attribute name='cols'> <xsl:call-template name='dbk:max-columns'> <xsl:with-param name='rows' select='*/dbk:row'/> </xsl:call-template> </xsl:attribute> </xsl:if> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template name='dbk:max-columns'> <xsl:param name='rows' select='/..'/> <xsl:param name='max' select='0'/> <!-- This is a tail-recursive algorithm. Could improve this with other algorithm(s), eg. divide-and-conquer. --> <xsl:choose> <xsl:when test='not($rows)'> <xsl:value-of select='$max'/> </xsl:when> <xsl:when test='count($rows[1]/dbk:entry) > $max'> <xsl:call-template name='dbk:max-columns'> <xsl:with-param name='rows' select='$rows[position() != 1]'/> <xsl:with-param name='max' select='count($rows[1]/dbk:entry)'/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name='dbk:max-columns'> <xsl:with-param name='rows' select='$rows[position() != 1]'/> <xsl:with-param name='max' select='$max'/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match='dbk:tbody|dbk:thead|dbk:tfoot|dbk:row|dbk:colspec'> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match='dbk:entry'> <dbk:entry> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates/> </dbk:entry> </xsl:template> <xsl:template match='dbk:para' mode='rnd:table-title'> <dbk:title> <xsl:apply-templates/> </dbk:title> </xsl:template> <!-- Find the caption associated with this table --> <xsl:template name='rnd:table-caption'> <xsl:variable name='candidate' select='following-sibling::dbk:para[@rnd:style = "caption" or @rnd:style = "Caption"][1]'/> <xsl:if test='$candidate != "" and generate-id($candidate/preceding-sibling::dbk:informaltable[1]) = generate-id(.)'> <dbk:caption> <dbk:para> <xsl:apply-templates select='$candidate/node()'/> </dbk:para> </dbk:caption> </xsl:if> </xsl:template> <!-- Find table associated text --> <xsl:template name='rnd:table-textobject'> <xsl:variable name='caption' select='following-sibling::dbk:para[@rnd:style = "caption" or @rnd:style = "Caption"][1]'/> <xsl:if test='generate-id($caption/preceding-sibling::dbk:informaltable[1]) = generate-id(.)'> <xsl:variable name='content' select='following-sibling::*[following-sibling::*[generate-id($caption) = generate-id()]]'/> <xsl:if test='$content'> <dbk:textobject> <xsl:apply-templates select='$content' mode='rnd:textobject'/> </dbk:textobject> </xsl:if> </xsl:if> </xsl:template> <xsl:template match='dbk:para' mode='rnd:textobject'> <xsl:call-template name='rnd:para'> <xsl:with-param name='suppress' select='false()'/> </xsl:call-template> </xsl:template> <!-- Footnotes --> <xsl:template match='dbk:footnote'> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates/> </xsl:copy> </xsl:template> <!-- utilities --> <!-- rnd:attributes reconstitutes an element's attributes --> <xsl:template name='rnd:attributes'> <xsl:param name='node' select='.'/> <xsl:apply-templates select='$node/@*[namespace-uri() != "http://docbook.org/ns/docbook/roundtrip"]' mode='rnd:copy'/> </xsl:template> <xsl:template match='*' name='rnd:copy' mode='rnd:copy'> <xsl:copy> <xsl:apply-templates select='@*' mode='rnd:copy'/> <xsl:apply-templates mode='rnd:copy'/> </xsl:copy> </xsl:template> <xsl:template match='@*' mode='rnd:copy'> <xsl:copy/> </xsl:template> <!-- These templates are invoked whenever an error condition is detected in the conversion of a document. --> <xsl:template name='rnd:error'> <xsl:param name='node' select='.'/> <xsl:param name='code'/> <xsl:param name='message'/> <xsl:comment><xsl:value-of select='$message'/></xsl:comment> <xsl:message>ERROR "<xsl:value-of select='$code'/>": <xsl:value-of select='$message'/></xsl:message> <rnd:error> <rnd:code> <xsl:value-of select='$code'/> </rnd:code> <rnd:message> <xsl:value-of select='$message'/> </rnd:message> </rnd:error> </xsl:template> <xsl:template name='rnd:warning'> <xsl:param name='node' select='.'/> <xsl:param name='code'/> <xsl:param name='message'/> <xsl:comment><xsl:value-of select='$message'/></xsl:comment> <xsl:message>WARNING "<xsl:value-of select='$code'/>": <xsl:value-of select='$message'/></xsl:message> <rnd:warning> <rnd:code> <xsl:value-of select='$code'/> </rnd:code> <rnd:message> <xsl:value-of select='$message'/> </rnd:message> </rnd:warning> </xsl:template> </xsl:stylesheet>
{ "pile_set_name": "Github" }
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package validation import ( "reflect" "strings" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation/field" apivalidation "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apis/storage" ) // ValidateStorageClass validates a StorageClass. func ValidateStorageClass(storageClass *storage.StorageClass) field.ErrorList { allErrs := apivalidation.ValidateObjectMeta(&storageClass.ObjectMeta, false, apivalidation.ValidateClassName, field.NewPath("metadata")) allErrs = append(allErrs, validateProvisioner(storageClass.Provisioner, field.NewPath("provisioner"))...) allErrs = append(allErrs, validateParameters(storageClass.Parameters, field.NewPath("parameters"))...) return allErrs } // ValidateStorageClassUpdate tests if an update to StorageClass is valid. func ValidateStorageClassUpdate(storageClass, oldStorageClass *storage.StorageClass) field.ErrorList { allErrs := apivalidation.ValidateObjectMetaUpdate(&storageClass.ObjectMeta, &oldStorageClass.ObjectMeta, field.NewPath("metadata")) if !reflect.DeepEqual(oldStorageClass.Parameters, storageClass.Parameters) { allErrs = append(allErrs, field.Forbidden(field.NewPath("parameters"), "updates to parameters are forbidden.")) } if storageClass.Provisioner != oldStorageClass.Provisioner { allErrs = append(allErrs, field.Forbidden(field.NewPath("provisioner"), "updates to provisioner are forbidden.")) } return allErrs } // validateProvisioner tests if provisioner is a valid qualified name. func validateProvisioner(provisioner string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if len(provisioner) == 0 { allErrs = append(allErrs, field.Required(fldPath, provisioner)) } if len(provisioner) > 0 { for _, msg := range validation.IsQualifiedName(strings.ToLower(provisioner)) { allErrs = append(allErrs, field.Invalid(fldPath, provisioner, msg)) } } return allErrs } const maxProvisionerParameterSize = 256 * (1 << 10) // 256 kB const maxProvisionerParameterLen = 512 // validateParameters tests that keys are qualified names and that provisionerParameter are < 256kB. func validateParameters(params map[string]string, fldPath *field.Path) field.ErrorList { var totalSize int64 allErrs := field.ErrorList{} if len(params) > maxProvisionerParameterLen { allErrs = append(allErrs, field.TooLong(fldPath, "Provisioner Parameters exceeded max allowed", maxProvisionerParameterLen)) return allErrs } for k, v := range params { if len(k) < 1 { allErrs = append(allErrs, field.Invalid(fldPath, k, "field can not be empty.")) } totalSize += (int64)(len(k)) + (int64)(len(v)) } if totalSize > maxProvisionerParameterSize { allErrs = append(allErrs, field.TooLong(fldPath, "", maxProvisionerParameterSize)) } return allErrs }
{ "pile_set_name": "Github" }
# Tenko parser test case - Path: tests/testcases/strict_mode/directive_headers/ident_3d_5barguments5d/function_decl/as_func_name_w_directive.md > :: strict mode : directive headers : ident 3d 5barguments5d : function decl > > ::> as func name w directive ## Input `````js function arguments(b){ "use strict"; } ````` ## Output _Note: the whole output block is auto-generated. Manual changes will be overwritten!_ Below follow outputs in five parsing modes: sloppy, sloppy+annexb, strict script, module, module+annexb. Note that the output parts are auto-generated by the test runner to reflect actual result. ### Sloppy mode Parsed with script goal and as if the code did not start with strict mode header. ````` throws: Parser error! Can not use reserved keyword `arguments` in strict mode as id for function that has a use strict directive start@1:0, error@1:9 ╔══╦════════════════ 1 ║ function arguments(b){ "use strict"; } ║ ^^^^^^^^^------- error ╚══╩════════════════ ````` ### Strict mode Parsed with script goal but as if it was starting with `"use strict"` at the top. ````` throws: Parser error! Cannot use this name (`arguments`) as a variable name because: Cannot create a binding named `arguments` in strict mode start@1:0, error@1:9 ╔══╦════════════════ 1 ║ function arguments(b){ "use strict"; } ║ ^^^^^^^^^------- error ╚══╩════════════════ ````` ### Module goal Parsed with the module goal. _Output same as strict mode._ ### Sloppy mode with AnnexB Parsed with script goal with AnnexB rules enabled and as if the code did not start with strict mode header. _Output same as sloppy mode._ ### Module goal with AnnexB Parsed with the module goal with AnnexB rules enabled. _Output same as strict mode._
{ "pile_set_name": "Github" }
#ifndef __ALPHA_EXEC_H #define __ALPHA_EXEC_H #define arch_align_stack(x) (x) #endif /* __ALPHA_EXEC_H */
{ "pile_set_name": "Github" }
#!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@"
{ "pile_set_name": "Github" }
--- Description: This topic is not current. For the most current information, see the Print Schema Specification. ms.assetid: b49e20b7-bd9e-4b8f-bb4a-bb1e99b0c417 title: Creating a PrintCapabilities Document ms.topic: article ms.date: 05/31/2018 --- # Creating a PrintCapabilities Document This topic is not current. For the most current information, see the [Print Schema Specification](https://www.microsoft.com/whdc/xps/printschema.mspx). After a PrintTicket is validated, it can be used to create a snapshot of the PrintCapabilities. The provider must have an internal representation for any Property whose Value is dependent on the device configuration. For example, if SpotDiameter is a Property that is dependent on both the Resolution and MediaType Features, an internal representation of SpotDiameter as it relates to the various values for Resolution and MediaType might appear as in the following table: | Resolution | MediaType | SpotDiameter | |-----------------|-------------------|----------------| | 300<br/> | Bond<br/> | 520<br/> | | 300<br/> | Glossy<br/> | 350<br/> | | 600<br/> | Bond<br/> | 330<br/> | | 600<br/> | Glossy<br/> | 180<br/> | | 1200<br/> | Bond<br/> | 250<br/> | | 1200<br/> | Glossy<br/> | 100<br/> | For this example, the PrintCapabilities provider must use the provided PrintTicket to select the proper entry from the internal table and report that as the Value for the SpotDiameter Property. This process is repeated for every multi-valued Property (for every Property whose Value is dependent on the configuration). The [PrintCapabilities Schema and Document Construction](printcapabilities-schema-and-document-construction.md) section describes the other steps involved in creating a snapshot of the PrintCapabilities. To create a snapshot of the default PrintCapabilities document, provide a default PrintTicket (rather than an arbitrary PrintTicket) to the method that creates PrintCapabilities documents. ## Related topics <dl> <dt> [Print Schema Specification](https://www.microsoft.com/whdc/xps/printschema.mspx) </dt> </dl>
{ "pile_set_name": "Github" }
/* ****************************************************************************** * * Copyright (C) 2002-2016, International Business Machines * Corporation and others. All Rights Reserved. * ****************************************************************************** * file name: ucnvbocu.cpp * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * created on: 2002mar27 * created by: Markus W. Scherer * * This is an implementation of the Binary Ordered Compression for Unicode, * in its MIME-friendly form as defined in http://www.unicode.org/notes/tn6/ */ #include "unicode/utypes.h" #if !UCONFIG_NO_CONVERSION && !UCONFIG_ONLY_HTML_CONVERSION #include "unicode/ucnv.h" #include "unicode/ucnv_cb.h" #include "unicode/utf16.h" #include "putilimp.h" #include "ucnv_bld.h" #include "ucnv_cnv.h" #include "uassert.h" /* BOCU-1 constants and macros ---------------------------------------------- */ /* * BOCU-1 encodes the code points of a Unicode string as * a sequence of byte-encoded differences (slope detection), * preserving lexical order. * * Optimize the difference-taking for runs of Unicode text within * small scripts: * * Most small scripts are allocated within aligned 128-blocks of Unicode * code points. Lexical order is preserved if the "previous code point" state * is always moved into the middle of such a block. * * Additionally, "prev" is moved from anywhere in the Unihan and Hangul * areas into the middle of those areas. * * C0 control codes and space are encoded with their US-ASCII bytes. * "prev" is reset for C0 controls but not for space. */ /* initial value for "prev": middle of the ASCII range */ #define BOCU1_ASCII_PREV 0x40 /* bounding byte values for differences */ #define BOCU1_MIN 0x21 #define BOCU1_MIDDLE 0x90 #define BOCU1_MAX_LEAD 0xfe #define BOCU1_MAX_TRAIL 0xff #define BOCU1_RESET 0xff /* number of lead bytes */ #define BOCU1_COUNT (BOCU1_MAX_LEAD-BOCU1_MIN+1) /* adjust trail byte counts for the use of some C0 control byte values */ #define BOCU1_TRAIL_CONTROLS_COUNT 20 #define BOCU1_TRAIL_BYTE_OFFSET (BOCU1_MIN-BOCU1_TRAIL_CONTROLS_COUNT) /* number of trail bytes */ #define BOCU1_TRAIL_COUNT ((BOCU1_MAX_TRAIL-BOCU1_MIN+1)+BOCU1_TRAIL_CONTROLS_COUNT) /* * number of positive and negative single-byte codes * (counting 0==BOCU1_MIDDLE among the positive ones) */ #define BOCU1_SINGLE 64 /* number of lead bytes for positive and negative 2/3/4-byte sequences */ #define BOCU1_LEAD_2 43 #define BOCU1_LEAD_3 3 #define BOCU1_LEAD_4 1 /* The difference value range for single-byters. */ #define BOCU1_REACH_POS_1 (BOCU1_SINGLE-1) #define BOCU1_REACH_NEG_1 (-BOCU1_SINGLE) /* The difference value range for double-byters. */ #define BOCU1_REACH_POS_2 (BOCU1_REACH_POS_1+BOCU1_LEAD_2*BOCU1_TRAIL_COUNT) #define BOCU1_REACH_NEG_2 (BOCU1_REACH_NEG_1-BOCU1_LEAD_2*BOCU1_TRAIL_COUNT) /* The difference value range for 3-byters. */ #define BOCU1_REACH_POS_3 \ (BOCU1_REACH_POS_2+BOCU1_LEAD_3*BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT) #define BOCU1_REACH_NEG_3 (BOCU1_REACH_NEG_2-BOCU1_LEAD_3*BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT) /* The lead byte start values. */ #define BOCU1_START_POS_2 (BOCU1_MIDDLE+BOCU1_REACH_POS_1+1) #define BOCU1_START_POS_3 (BOCU1_START_POS_2+BOCU1_LEAD_2) #define BOCU1_START_POS_4 (BOCU1_START_POS_3+BOCU1_LEAD_3) /* ==BOCU1_MAX_LEAD */ #define BOCU1_START_NEG_2 (BOCU1_MIDDLE+BOCU1_REACH_NEG_1) #define BOCU1_START_NEG_3 (BOCU1_START_NEG_2-BOCU1_LEAD_2) #define BOCU1_START_NEG_4 (BOCU1_START_NEG_3-BOCU1_LEAD_3) /* ==BOCU1_MIN+1 */ /* The length of a byte sequence, according to the lead byte (!=BOCU1_RESET). */ #define BOCU1_LENGTH_FROM_LEAD(lead) \ ((BOCU1_START_NEG_2<=(lead) && (lead)<BOCU1_START_POS_2) ? 1 : \ (BOCU1_START_NEG_3<=(lead) && (lead)<BOCU1_START_POS_3) ? 2 : \ (BOCU1_START_NEG_4<=(lead) && (lead)<BOCU1_START_POS_4) ? 3 : 4) /* The length of a byte sequence, according to its packed form. */ #define BOCU1_LENGTH_FROM_PACKED(packed) \ ((uint32_t)(packed)<0x04000000 ? (packed)>>24 : 4) /* * 12 commonly used C0 control codes (and space) are only used to encode * themselves directly, * which makes BOCU-1 MIME-usable and reasonably safe for * ASCII-oriented software. * * These controls are * 0 NUL * * 7 BEL * 8 BS * * 9 TAB * a LF * b VT * c FF * d CR * * e SO * f SI * * 1a SUB * 1b ESC * * The other 20 C0 controls are also encoded directly (to preserve order) * but are also used as trail bytes in difference encoding * (for better compression). */ #define BOCU1_TRAIL_TO_BYTE(t) ((t)>=BOCU1_TRAIL_CONTROLS_COUNT ? (t)+BOCU1_TRAIL_BYTE_OFFSET : bocu1TrailToByte[t]) /* * Byte value map for control codes, * from external byte values 0x00..0x20 * to trail byte values 0..19 (0..0x13) as used in the difference calculation. * External byte values that are illegal as trail bytes are mapped to -1. */ static const int8_t bocu1ByteToTrail[BOCU1_MIN]={ /* 0 1 2 3 4 5 6 7 */ -1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, -1, /* 8 9 a b c d e f */ -1, -1, -1, -1, -1, -1, -1, -1, /* 10 11 12 13 14 15 16 17 */ 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, /* 18 19 1a 1b 1c 1d 1e 1f */ 0x0e, 0x0f, -1, -1, 0x10, 0x11, 0x12, 0x13, /* 20 */ -1 }; /* * Byte value map for control codes, * from trail byte values 0..19 (0..0x13) as used in the difference calculation * to external byte values 0x00..0x20. */ static const int8_t bocu1TrailToByte[BOCU1_TRAIL_CONTROLS_COUNT]={ /* 0 1 2 3 4 5 6 7 */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x10, 0x11, /* 8 9 a b c d e f */ 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, /* 10 11 12 13 */ 0x1c, 0x1d, 0x1e, 0x1f }; /** * Integer division and modulo with negative numerators * yields negative modulo results and quotients that are one more than * what we need here. * This macro adjust the results so that the modulo-value m is always >=0. * * For positive n, the if() condition is always FALSE. * * @param n Number to be split into quotient and rest. * Will be modified to contain the quotient. * @param d Divisor. * @param m Output variable for the rest (modulo result). */ #define NEGDIVMOD(n, d, m) { \ (m)=(n)%(d); \ (n)/=(d); \ if((m)<0) { \ --(n); \ (m)+=(d); \ } \ } /* Faster versions of packDiff() for single-byte-encoded diff values. */ /** Is a diff value encodable in a single byte? */ #define DIFF_IS_SINGLE(diff) (BOCU1_REACH_NEG_1<=(diff) && (diff)<=BOCU1_REACH_POS_1) /** Encode a diff value in a single byte. */ #define PACK_SINGLE_DIFF(diff) (BOCU1_MIDDLE+(diff)) /** Is a diff value encodable in two bytes? */ #define DIFF_IS_DOUBLE(diff) (BOCU1_REACH_NEG_2<=(diff) && (diff)<=BOCU1_REACH_POS_2) /* BOCU-1 implementation functions ------------------------------------------ */ #define BOCU1_SIMPLE_PREV(c) (((c)&~0x7f)+BOCU1_ASCII_PREV) /** * Compute the next "previous" value for differencing * from the current code point. * * @param c current code point, 0x3040..0xd7a3 (rest handled by macro below) * @return "previous code point" state value */ static inline int32_t bocu1Prev(int32_t c) { /* compute new prev */ if(/* 0x3040<=c && */ c<=0x309f) { /* Hiragana is not 128-aligned */ return 0x3070; } else if(0x4e00<=c && c<=0x9fa5) { /* CJK Unihan */ return 0x4e00-BOCU1_REACH_NEG_2; } else if(0xac00<=c /* && c<=0xd7a3 */) { /* Korean Hangul */ return (0xd7a3+0xac00)/2; } else { /* mostly small scripts */ return BOCU1_SIMPLE_PREV(c); } } /** Fast version of bocu1Prev() for most scripts. */ #define BOCU1_PREV(c) ((c)<0x3040 || (c)>0xd7a3 ? BOCU1_SIMPLE_PREV(c) : bocu1Prev(c)) /* * The BOCU-1 converter uses the standard setup code in ucnv.c/ucnv_bld.c. * The UConverter fields are used as follows: * * fromUnicodeStatus encoder's prev (0 will be interpreted as BOCU1_ASCII_PREV) * * toUnicodeStatus decoder's prev (0 will be interpreted as BOCU1_ASCII_PREV) * mode decoder's incomplete (diff<<2)|count (ignored when toULength==0) */ /* BOCU-1-from-Unicode conversion functions --------------------------------- */ /** * Encode a difference -0x10ffff..0x10ffff in 1..4 bytes * and return a packed integer with them. * * The encoding favors small absolute differences with short encodings * to compress runs of same-script characters. * * Optimized version with unrolled loops and fewer floating-point operations * than the standard packDiff(). * * @param diff difference value -0x10ffff..0x10ffff * @return * 0x010000zz for 1-byte sequence zz * 0x0200yyzz for 2-byte sequence yy zz * 0x03xxyyzz for 3-byte sequence xx yy zz * 0xwwxxyyzz for 4-byte sequence ww xx yy zz (ww>0x03) */ static int32_t packDiff(int32_t diff) { int32_t result, m; U_ASSERT(!DIFF_IS_SINGLE(diff)); /* assume we won't be called where diff==BOCU1_REACH_NEG_1=-64 */ if(diff>=BOCU1_REACH_NEG_1) { /* mostly positive differences, and single-byte negative ones */ #if 0 /* single-byte case handled in macros, see below */ if(diff<=BOCU1_REACH_POS_1) { /* single byte */ return 0x01000000|(BOCU1_MIDDLE+diff); } else #endif if(diff<=BOCU1_REACH_POS_2) { /* two bytes */ diff-=BOCU1_REACH_POS_1+1; result=0x02000000; m=diff%BOCU1_TRAIL_COUNT; diff/=BOCU1_TRAIL_COUNT; result|=BOCU1_TRAIL_TO_BYTE(m); result|=(BOCU1_START_POS_2+diff)<<8; } else if(diff<=BOCU1_REACH_POS_3) { /* three bytes */ diff-=BOCU1_REACH_POS_2+1; result=0x03000000; m=diff%BOCU1_TRAIL_COUNT; diff/=BOCU1_TRAIL_COUNT; result|=BOCU1_TRAIL_TO_BYTE(m); m=diff%BOCU1_TRAIL_COUNT; diff/=BOCU1_TRAIL_COUNT; result|=BOCU1_TRAIL_TO_BYTE(m)<<8; result|=(BOCU1_START_POS_3+diff)<<16; } else { /* four bytes */ diff-=BOCU1_REACH_POS_3+1; m=diff%BOCU1_TRAIL_COUNT; diff/=BOCU1_TRAIL_COUNT; result=BOCU1_TRAIL_TO_BYTE(m); m=diff%BOCU1_TRAIL_COUNT; diff/=BOCU1_TRAIL_COUNT; result|=BOCU1_TRAIL_TO_BYTE(m)<<8; /* * We know that / and % would deliver quotient 0 and rest=diff. * Avoid division and modulo for performance. */ result|=BOCU1_TRAIL_TO_BYTE(diff)<<16; result|=((uint32_t)BOCU1_START_POS_4)<<24; } } else { /* two- to four-byte negative differences */ if(diff>=BOCU1_REACH_NEG_2) { /* two bytes */ diff-=BOCU1_REACH_NEG_1; result=0x02000000; NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); result|=BOCU1_TRAIL_TO_BYTE(m); result|=(BOCU1_START_NEG_2+diff)<<8; } else if(diff>=BOCU1_REACH_NEG_3) { /* three bytes */ diff-=BOCU1_REACH_NEG_2; result=0x03000000; NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); result|=BOCU1_TRAIL_TO_BYTE(m); NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); result|=BOCU1_TRAIL_TO_BYTE(m)<<8; result|=(BOCU1_START_NEG_3+diff)<<16; } else { /* four bytes */ diff-=BOCU1_REACH_NEG_3; NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); result=BOCU1_TRAIL_TO_BYTE(m); NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); result|=BOCU1_TRAIL_TO_BYTE(m)<<8; /* * We know that NEGDIVMOD would deliver * quotient -1 and rest=diff+BOCU1_TRAIL_COUNT. * Avoid division and modulo for performance. */ m=diff+BOCU1_TRAIL_COUNT; result|=BOCU1_TRAIL_TO_BYTE(m)<<16; result|=BOCU1_MIN<<24; } } return result; } static void _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const UChar *source, *sourceLimit; uint8_t *target; int32_t targetCapacity; int32_t *offsets; int32_t prev, c, diff; int32_t sourceIndex, nextSourceIndex; /* set up the local pointers */ cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; target=(uint8_t *)pArgs->target; targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); offsets=pArgs->offsets; /* get the converter state from UConverter */ c=cnv->fromUChar32; prev=(int32_t)cnv->fromUnicodeStatus; if(prev==0) { prev=BOCU1_ASCII_PREV; } /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex= c==0 ? 0 : -1; nextSourceIndex=0; /* conversion loop */ if(c!=0 && targetCapacity>0) { goto getTrail; } fastSingle: /* fast loop for single-byte differences */ /* use only one loop counter variable, targetCapacity, not also source */ diff=(int32_t)(sourceLimit-source); if(targetCapacity>diff) { targetCapacity=diff; } while(targetCapacity>0 && (c=*source)<0x3000) { if(c<=0x20) { if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(uint8_t)c; *offsets++=nextSourceIndex++; ++source; --targetCapacity; } else { diff=c-prev; if(DIFF_IS_SINGLE(diff)) { prev=BOCU1_SIMPLE_PREV(c); *target++=(uint8_t)PACK_SINGLE_DIFF(diff); *offsets++=nextSourceIndex++; ++source; --targetCapacity; } else { break; } } } /* restore real values */ targetCapacity=(int32_t)((const uint8_t *)pArgs->targetLimit-target); sourceIndex=nextSourceIndex; /* wrong if offsets==NULL but does not matter */ /* regular loop for all cases */ while(source<sourceLimit) { if(targetCapacity>0) { c=*source++; ++nextSourceIndex; if(c<=0x20) { /* * ISO C0 control & space: * Encode directly for MIME compatibility, * and reset state except for space, to not disrupt compression. */ if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(uint8_t)c; *offsets++=sourceIndex; --targetCapacity; sourceIndex=nextSourceIndex; continue; } if(U16_IS_LEAD(c)) { getTrail: if(source<sourceLimit) { /* test the following code unit */ UChar trail=*source; if(U16_IS_TRAIL(trail)) { ++source; ++nextSourceIndex; c=U16_GET_SUPPLEMENTARY(c, trail); } } else { /* no more input */ c=-c; /* negative lead surrogate as "incomplete" indicator to avoid c=0 everywhere else */ break; } } /* * all other Unicode code points c==U+0021..U+10ffff * are encoded with the difference c-prev * * a new prev is computed from c, * placed in the middle of a 0x80-block (for most small scripts) or * in the middle of the Unihan and Hangul blocks * to statistically minimize the following difference */ diff=c-prev; prev=BOCU1_PREV(c); if(DIFF_IS_SINGLE(diff)) { *target++=(uint8_t)PACK_SINGLE_DIFF(diff); *offsets++=sourceIndex; --targetCapacity; sourceIndex=nextSourceIndex; if(c<0x3000) { goto fastSingle; } } else if(DIFF_IS_DOUBLE(diff) && 2<=targetCapacity) { /* optimize 2-byte case */ int32_t m; if(diff>=0) { diff-=BOCU1_REACH_POS_1+1; m=diff%BOCU1_TRAIL_COUNT; diff/=BOCU1_TRAIL_COUNT; diff+=BOCU1_START_POS_2; } else { diff-=BOCU1_REACH_NEG_1; NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); diff+=BOCU1_START_NEG_2; } *target++=(uint8_t)diff; *target++=(uint8_t)BOCU1_TRAIL_TO_BYTE(m); *offsets++=sourceIndex; *offsets++=sourceIndex; targetCapacity-=2; sourceIndex=nextSourceIndex; } else { int32_t length; /* will be 2..4 */ diff=packDiff(diff); length=BOCU1_LENGTH_FROM_PACKED(diff); /* write the output character bytes from diff and length */ /* from the first if in the loop we know that targetCapacity>0 */ if(length<=targetCapacity) { switch(length) { /* each branch falls through to the next one */ case 4: *target++=(uint8_t)(diff>>24); *offsets++=sourceIndex; U_FALLTHROUGH; case 3: *target++=(uint8_t)(diff>>16); *offsets++=sourceIndex; U_FALLTHROUGH; case 2: *target++=(uint8_t)(diff>>8); *offsets++=sourceIndex; /* case 1: handled above */ *target++=(uint8_t)diff; *offsets++=sourceIndex; U_FALLTHROUGH; default: /* will never occur */ break; } targetCapacity-=length; sourceIndex=nextSourceIndex; } else { uint8_t *charErrorBuffer; /* * We actually do this backwards here: * In order to save an intermediate variable, we output * first to the overflow buffer what does not fit into the * regular target. */ /* we know that 1<=targetCapacity<length<=4 */ length-=targetCapacity; charErrorBuffer=(uint8_t *)cnv->charErrorBuffer; switch(length) { /* each branch falls through to the next one */ case 3: *charErrorBuffer++=(uint8_t)(diff>>16); U_FALLTHROUGH; case 2: *charErrorBuffer++=(uint8_t)(diff>>8); U_FALLTHROUGH; case 1: *charErrorBuffer=(uint8_t)diff; U_FALLTHROUGH; default: /* will never occur */ break; } cnv->charErrorBufferLength=(int8_t)length; /* now output what fits into the regular target */ diff>>=8*length; /* length was reduced by targetCapacity */ switch(targetCapacity) { /* each branch falls through to the next one */ case 3: *target++=(uint8_t)(diff>>16); *offsets++=sourceIndex; U_FALLTHROUGH; case 2: *target++=(uint8_t)(diff>>8); *offsets++=sourceIndex; U_FALLTHROUGH; case 1: *target++=(uint8_t)diff; *offsets++=sourceIndex; U_FALLTHROUGH; default: /* will never occur */ break; } /* target overflow */ targetCapacity=0; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } } else { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } /* set the converter state back into UConverter */ cnv->fromUChar32= c<0 ? -c : 0; cnv->fromUnicodeStatus=(uint32_t)prev; /* write back the updated pointers */ pArgs->source=source; pArgs->target=(char *)target; pArgs->offsets=offsets; } /* * Identical to _Bocu1FromUnicodeWithOffsets but without offset handling. * If a change is made in the original function, then either * change this function the same way or * re-copy the original function and remove the variables * offsets, sourceIndex, and nextSourceIndex. */ static void _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const UChar *source, *sourceLimit; uint8_t *target; int32_t targetCapacity; int32_t prev, c, diff; /* set up the local pointers */ cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; target=(uint8_t *)pArgs->target; targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); /* get the converter state from UConverter */ c=cnv->fromUChar32; prev=(int32_t)cnv->fromUnicodeStatus; if(prev==0) { prev=BOCU1_ASCII_PREV; } /* conversion loop */ if(c!=0 && targetCapacity>0) { goto getTrail; } fastSingle: /* fast loop for single-byte differences */ /* use only one loop counter variable, targetCapacity, not also source */ diff=(int32_t)(sourceLimit-source); if(targetCapacity>diff) { targetCapacity=diff; } while(targetCapacity>0 && (c=*source)<0x3000) { if(c<=0x20) { if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(uint8_t)c; } else { diff=c-prev; if(DIFF_IS_SINGLE(diff)) { prev=BOCU1_SIMPLE_PREV(c); *target++=(uint8_t)PACK_SINGLE_DIFF(diff); } else { break; } } ++source; --targetCapacity; } /* restore real values */ targetCapacity=(int32_t)((const uint8_t *)pArgs->targetLimit-target); /* regular loop for all cases */ while(source<sourceLimit) { if(targetCapacity>0) { c=*source++; if(c<=0x20) { /* * ISO C0 control & space: * Encode directly for MIME compatibility, * and reset state except for space, to not disrupt compression. */ if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(uint8_t)c; --targetCapacity; continue; } if(U16_IS_LEAD(c)) { getTrail: if(source<sourceLimit) { /* test the following code unit */ UChar trail=*source; if(U16_IS_TRAIL(trail)) { ++source; c=U16_GET_SUPPLEMENTARY(c, trail); } } else { /* no more input */ c=-c; /* negative lead surrogate as "incomplete" indicator to avoid c=0 everywhere else */ break; } } /* * all other Unicode code points c==U+0021..U+10ffff * are encoded with the difference c-prev * * a new prev is computed from c, * placed in the middle of a 0x80-block (for most small scripts) or * in the middle of the Unihan and Hangul blocks * to statistically minimize the following difference */ diff=c-prev; prev=BOCU1_PREV(c); if(DIFF_IS_SINGLE(diff)) { *target++=(uint8_t)PACK_SINGLE_DIFF(diff); --targetCapacity; if(c<0x3000) { goto fastSingle; } } else if(DIFF_IS_DOUBLE(diff) && 2<=targetCapacity) { /* optimize 2-byte case */ int32_t m; if(diff>=0) { diff-=BOCU1_REACH_POS_1+1; m=diff%BOCU1_TRAIL_COUNT; diff/=BOCU1_TRAIL_COUNT; diff+=BOCU1_START_POS_2; } else { diff-=BOCU1_REACH_NEG_1; NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); diff+=BOCU1_START_NEG_2; } *target++=(uint8_t)diff; *target++=(uint8_t)BOCU1_TRAIL_TO_BYTE(m); targetCapacity-=2; } else { int32_t length; /* will be 2..4 */ diff=packDiff(diff); length=BOCU1_LENGTH_FROM_PACKED(diff); /* write the output character bytes from diff and length */ /* from the first if in the loop we know that targetCapacity>0 */ if(length<=targetCapacity) { switch(length) { /* each branch falls through to the next one */ case 4: *target++=(uint8_t)(diff>>24); U_FALLTHROUGH; case 3: *target++=(uint8_t)(diff>>16); /* case 2: handled above */ *target++=(uint8_t)(diff>>8); /* case 1: handled above */ *target++=(uint8_t)diff; U_FALLTHROUGH; default: /* will never occur */ break; } targetCapacity-=length; } else { uint8_t *charErrorBuffer; /* * We actually do this backwards here: * In order to save an intermediate variable, we output * first to the overflow buffer what does not fit into the * regular target. */ /* we know that 1<=targetCapacity<length<=4 */ length-=targetCapacity; charErrorBuffer=(uint8_t *)cnv->charErrorBuffer; switch(length) { /* each branch falls through to the next one */ case 3: *charErrorBuffer++=(uint8_t)(diff>>16); U_FALLTHROUGH; case 2: *charErrorBuffer++=(uint8_t)(diff>>8); U_FALLTHROUGH; case 1: *charErrorBuffer=(uint8_t)diff; U_FALLTHROUGH; default: /* will never occur */ break; } cnv->charErrorBufferLength=(int8_t)length; /* now output what fits into the regular target */ diff>>=8*length; /* length was reduced by targetCapacity */ switch(targetCapacity) { /* each branch falls through to the next one */ case 3: *target++=(uint8_t)(diff>>16); U_FALLTHROUGH; case 2: *target++=(uint8_t)(diff>>8); U_FALLTHROUGH; case 1: *target++=(uint8_t)diff; U_FALLTHROUGH; default: /* will never occur */ break; } /* target overflow */ targetCapacity=0; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } } else { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } /* set the converter state back into UConverter */ cnv->fromUChar32= c<0 ? -c : 0; cnv->fromUnicodeStatus=(uint32_t)prev; /* write back the updated pointers */ pArgs->source=source; pArgs->target=(char *)target; } /* BOCU-1-to-Unicode conversion functions ----------------------------------- */ /** * Function for BOCU-1 decoder; handles multi-byte lead bytes. * * @param b lead byte; * BOCU1_MIN<=b<BOCU1_START_NEG_2 or BOCU1_START_POS_2<=b<BOCU1_MAX_LEAD * @return (diff<<2)|count */ static inline int32_t decodeBocu1LeadByte(int32_t b) { int32_t diff, count; if(b>=BOCU1_START_NEG_2) { /* positive difference */ if(b<BOCU1_START_POS_3) { /* two bytes */ diff=((int32_t)b-BOCU1_START_POS_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_POS_1+1; count=1; } else if(b<BOCU1_START_POS_4) { /* three bytes */ diff=((int32_t)b-BOCU1_START_POS_3)*BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT+BOCU1_REACH_POS_2+1; count=2; } else { /* four bytes */ diff=BOCU1_REACH_POS_3+1; count=3; } } else { /* negative difference */ if(b>=BOCU1_START_NEG_3) { /* two bytes */ diff=((int32_t)b-BOCU1_START_NEG_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_1; count=1; } else if(b>BOCU1_MIN) { /* three bytes */ diff=((int32_t)b-BOCU1_START_NEG_3)*BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_2; count=2; } else { /* four bytes */ diff=-BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_3; count=3; } } /* return the state for decoding the trail byte(s) */ return (diff<<2)|count; } /** * Function for BOCU-1 decoder; handles multi-byte trail bytes. * * @param count number of remaining trail bytes including this one * @param b trail byte * @return new delta for diff including b - <0 indicates an error * * @see decodeBocu1 */ static inline int32_t decodeBocu1TrailByte(int32_t count, int32_t b) { if(b<=0x20) { /* skip some C0 controls and make the trail byte range contiguous */ b=bocu1ByteToTrail[b]; /* b<0 for an illegal trail byte value will result in return<0 below */ #if BOCU1_MAX_TRAIL<0xff } else if(b>BOCU1_MAX_TRAIL) { return -99; #endif } else { b-=BOCU1_TRAIL_BYTE_OFFSET; } /* add trail byte into difference and decrement count */ if(count==1) { return b; } else if(count==2) { return b*BOCU1_TRAIL_COUNT; } else /* count==3 */ { return b*(BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT); } } static void _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const uint8_t *source, *sourceLimit; UChar *target; const UChar *targetLimit; int32_t *offsets; int32_t prev, count, diff, c; int8_t byteIndex; uint8_t *bytes; int32_t sourceIndex, nextSourceIndex; /* set up the local pointers */ cnv=pArgs->converter; source=(const uint8_t *)pArgs->source; sourceLimit=(const uint8_t *)pArgs->sourceLimit; target=pArgs->target; targetLimit=pArgs->targetLimit; offsets=pArgs->offsets; /* get the converter state from UConverter */ prev=(int32_t)cnv->toUnicodeStatus; if(prev==0) { prev=BOCU1_ASCII_PREV; } diff=cnv->mode; /* mode may be set to UCNV_SI by ucnv_bld.c but then toULength==0 */ count=diff&3; diff>>=2; byteIndex=cnv->toULength; bytes=cnv->toUBytes; /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex=byteIndex==0 ? 0 : -1; nextSourceIndex=0; /* conversion "loop" similar to _SCSUToUnicodeWithOffsets() */ if(count>0 && byteIndex>0 && target<targetLimit) { goto getTrail; } fastSingle: /* fast loop for single-byte differences */ /* use count as the only loop counter variable */ diff=(int32_t)(sourceLimit-source); count=(int32_t)(pArgs->targetLimit-target); if(count>diff) { count=diff; } while(count>0) { if(BOCU1_START_NEG_2<=(c=*source) && c<BOCU1_START_POS_2) { c=prev+(c-BOCU1_MIDDLE); if(c<0x3000) { *target++=(UChar)c; *offsets++=nextSourceIndex++; prev=BOCU1_SIMPLE_PREV(c); } else { break; } } else if(c<=0x20) { if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(UChar)c; *offsets++=nextSourceIndex++; } else { break; } ++source; --count; } sourceIndex=nextSourceIndex; /* wrong if offsets==NULL but does not matter */ /* decode a sequence of single and lead bytes */ while(source<sourceLimit) { if(target>=targetLimit) { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } ++nextSourceIndex; c=*source++; if(BOCU1_START_NEG_2<=c && c<BOCU1_START_POS_2) { /* Write a code point directly from a single-byte difference. */ c=prev+(c-BOCU1_MIDDLE); if(c<0x3000) { *target++=(UChar)c; *offsets++=sourceIndex; prev=BOCU1_SIMPLE_PREV(c); sourceIndex=nextSourceIndex; goto fastSingle; } } else if(c<=0x20) { /* * Direct-encoded C0 control code or space. * Reset prev for C0 control codes but not for space. */ if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(UChar)c; *offsets++=sourceIndex; sourceIndex=nextSourceIndex; continue; } else if(BOCU1_START_NEG_3<=c && c<BOCU1_START_POS_3 && source<sourceLimit) { /* Optimize two-byte case. */ if(c>=BOCU1_MIDDLE) { diff=((int32_t)c-BOCU1_START_POS_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_POS_1+1; } else { diff=((int32_t)c-BOCU1_START_NEG_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_1; } /* trail byte */ ++nextSourceIndex; c=decodeBocu1TrailByte(1, *source++); if(c<0 || (uint32_t)(c=prev+diff+c)>0x10ffff) { bytes[0]=source[-2]; bytes[1]=source[-1]; byteIndex=2; *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } else if(c==BOCU1_RESET) { /* only reset the state, no code point */ prev=BOCU1_ASCII_PREV; sourceIndex=nextSourceIndex; continue; } else { /* * For multi-byte difference lead bytes, set the decoder state * with the partial difference value from the lead byte and * with the number of trail bytes. */ bytes[0]=(uint8_t)c; byteIndex=1; diff=decodeBocu1LeadByte(c); count=diff&3; diff>>=2; getTrail: for(;;) { if(source>=sourceLimit) { goto endloop; } ++nextSourceIndex; c=bytes[byteIndex++]=*source++; /* trail byte in any position */ c=decodeBocu1TrailByte(count, c); if(c<0) { *pErrorCode=U_ILLEGAL_CHAR_FOUND; goto endloop; } diff+=c; if(--count==0) { /* final trail byte, deliver a code point */ byteIndex=0; c=prev+diff; if((uint32_t)c>0x10ffff) { *pErrorCode=U_ILLEGAL_CHAR_FOUND; goto endloop; } break; } } } /* calculate the next prev and output c */ prev=BOCU1_PREV(c); if(c<=0xffff) { *target++=(UChar)c; *offsets++=sourceIndex; } else { /* output surrogate pair */ *target++=U16_LEAD(c); if(target<targetLimit) { *target++=U16_TRAIL(c); *offsets++=sourceIndex; *offsets++=sourceIndex; } else { /* target overflow */ *offsets++=sourceIndex; cnv->UCharErrorBuffer[0]=U16_TRAIL(c); cnv->UCharErrorBufferLength=1; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } sourceIndex=nextSourceIndex; } endloop: if(*pErrorCode==U_ILLEGAL_CHAR_FOUND) { /* set the converter state in UConverter to deal with the next character */ cnv->toUnicodeStatus=BOCU1_ASCII_PREV; cnv->mode=0; } else { /* set the converter state back into UConverter */ cnv->toUnicodeStatus=(uint32_t)prev; cnv->mode=(diff<<2)|count; } cnv->toULength=byteIndex; /* write back the updated pointers */ pArgs->source=(const char *)source; pArgs->target=target; pArgs->offsets=offsets; return; } /* * Identical to _Bocu1ToUnicodeWithOffsets but without offset handling. * If a change is made in the original function, then either * change this function the same way or * re-copy the original function and remove the variables * offsets, sourceIndex, and nextSourceIndex. */ static void _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const uint8_t *source, *sourceLimit; UChar *target; const UChar *targetLimit; int32_t prev, count, diff, c; int8_t byteIndex; uint8_t *bytes; /* set up the local pointers */ cnv=pArgs->converter; source=(const uint8_t *)pArgs->source; sourceLimit=(const uint8_t *)pArgs->sourceLimit; target=pArgs->target; targetLimit=pArgs->targetLimit; /* get the converter state from UConverter */ prev=(int32_t)cnv->toUnicodeStatus; if(prev==0) { prev=BOCU1_ASCII_PREV; } diff=cnv->mode; /* mode may be set to UCNV_SI by ucnv_bld.c but then toULength==0 */ count=diff&3; diff>>=2; byteIndex=cnv->toULength; bytes=cnv->toUBytes; /* conversion "loop" similar to _SCSUToUnicodeWithOffsets() */ if(count>0 && byteIndex>0 && target<targetLimit) { goto getTrail; } fastSingle: /* fast loop for single-byte differences */ /* use count as the only loop counter variable */ diff=(int32_t)(sourceLimit-source); count=(int32_t)(pArgs->targetLimit-target); if(count>diff) { count=diff; } while(count>0) { if(BOCU1_START_NEG_2<=(c=*source) && c<BOCU1_START_POS_2) { c=prev+(c-BOCU1_MIDDLE); if(c<0x3000) { *target++=(UChar)c; prev=BOCU1_SIMPLE_PREV(c); } else { break; } } else if(c<=0x20) { if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(UChar)c; } else { break; } ++source; --count; } /* decode a sequence of single and lead bytes */ while(source<sourceLimit) { if(target>=targetLimit) { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } c=*source++; if(BOCU1_START_NEG_2<=c && c<BOCU1_START_POS_2) { /* Write a code point directly from a single-byte difference. */ c=prev+(c-BOCU1_MIDDLE); if(c<0x3000) { *target++=(UChar)c; prev=BOCU1_SIMPLE_PREV(c); goto fastSingle; } } else if(c<=0x20) { /* * Direct-encoded C0 control code or space. * Reset prev for C0 control codes but not for space. */ if(c!=0x20) { prev=BOCU1_ASCII_PREV; } *target++=(UChar)c; continue; } else if(BOCU1_START_NEG_3<=c && c<BOCU1_START_POS_3 && source<sourceLimit) { /* Optimize two-byte case. */ if(c>=BOCU1_MIDDLE) { diff=((int32_t)c-BOCU1_START_POS_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_POS_1+1; } else { diff=((int32_t)c-BOCU1_START_NEG_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_1; } /* trail byte */ c=decodeBocu1TrailByte(1, *source++); if(c<0 || (uint32_t)(c=prev+diff+c)>0x10ffff) { bytes[0]=source[-2]; bytes[1]=source[-1]; byteIndex=2; *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } else if(c==BOCU1_RESET) { /* only reset the state, no code point */ prev=BOCU1_ASCII_PREV; continue; } else { /* * For multi-byte difference lead bytes, set the decoder state * with the partial difference value from the lead byte and * with the number of trail bytes. */ bytes[0]=(uint8_t)c; byteIndex=1; diff=decodeBocu1LeadByte(c); count=diff&3; diff>>=2; getTrail: for(;;) { if(source>=sourceLimit) { goto endloop; } c=bytes[byteIndex++]=*source++; /* trail byte in any position */ c=decodeBocu1TrailByte(count, c); if(c<0) { *pErrorCode=U_ILLEGAL_CHAR_FOUND; goto endloop; } diff+=c; if(--count==0) { /* final trail byte, deliver a code point */ byteIndex=0; c=prev+diff; if((uint32_t)c>0x10ffff) { *pErrorCode=U_ILLEGAL_CHAR_FOUND; goto endloop; } break; } } } /* calculate the next prev and output c */ prev=BOCU1_PREV(c); if(c<=0xffff) { *target++=(UChar)c; } else { /* output surrogate pair */ *target++=U16_LEAD(c); if(target<targetLimit) { *target++=U16_TRAIL(c); } else { /* target overflow */ cnv->UCharErrorBuffer[0]=U16_TRAIL(c); cnv->UCharErrorBufferLength=1; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } } endloop: if(*pErrorCode==U_ILLEGAL_CHAR_FOUND) { /* set the converter state in UConverter to deal with the next character */ cnv->toUnicodeStatus=BOCU1_ASCII_PREV; cnv->mode=0; } else { /* set the converter state back into UConverter */ cnv->toUnicodeStatus=(uint32_t)prev; cnv->mode=(diff<<2)|count; } cnv->toULength=byteIndex; /* write back the updated pointers */ pArgs->source=(const char *)source; pArgs->target=target; return; } /* miscellaneous ------------------------------------------------------------ */ static const UConverterImpl _Bocu1Impl={ UCNV_BOCU1, NULL, NULL, NULL, NULL, NULL, _Bocu1ToUnicode, _Bocu1ToUnicodeWithOffsets, _Bocu1FromUnicode, _Bocu1FromUnicodeWithOffsets, NULL, NULL, NULL, NULL, NULL, ucnv_getCompleteUnicodeSet, NULL, NULL }; static const UConverterStaticData _Bocu1StaticData={ sizeof(UConverterStaticData), "BOCU-1", 1214, /* CCSID for BOCU-1 */ UCNV_IBM, UCNV_BOCU1, 1, 4, /* one UChar generates at least 1 byte and at most 4 bytes */ { 0x1a, 0, 0, 0 }, 1, /* BOCU-1 never needs to write a subchar */ FALSE, FALSE, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } /* reserved */ }; const UConverterSharedData _Bocu1Data= UCNV_IMMUTABLE_SHARED_DATA_INITIALIZER(&_Bocu1StaticData, &_Bocu1Impl); #endif
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <background android:drawable="@color/ic_launcher_background"/> <foreground android:drawable="@mipmap/ic_launcher_foreground"/> </adaptive-icon>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2017-2018 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef ARM_COMPUTE_TEST_DATASET #define ARM_COMPUTE_TEST_DATASET #include <string> #include <utility> namespace arm_compute { namespace test { namespace framework { namespace dataset { /** Abstract dataset base class. */ class Dataset { protected: /** Default constructor. */ Dataset() = default; /** Default destructor. */ ~Dataset() = default; public: /** Allow instances of this class to be move constructed */ Dataset(Dataset &&) = default; }; /** Abstract implementation of a named dataset. * * The name should describe the values of the dataset. */ class NamedDataset : public Dataset { protected: /** Construct the dataset with the given name. * * @param[in] name Description of the values. */ explicit NamedDataset(std::string name) : _name{ std::move(name) } { } /** Default destructor. */ ~NamedDataset() = default; public: /** Allow instances of this class to be move constructed */ NamedDataset(NamedDataset &&) = default; /** Return name of the dataset. * * @return Description of the values. */ std::string name() const { return _name; } protected: const std::string _name; }; } // namespace dataset } // namespace framework } // namespace test } // namespace arm_compute #endif /* ARM_COMPUTE_TEST_DATASET */
{ "pile_set_name": "Github" }
/* * Copyright (C) 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.errai.common.client.logging.util; import java.util.Arrays; import java.util.Date; import com.google.gwt.i18n.client.LocaleInfo; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.i18n.client.TimeZone; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.user.datepicker.client.CalendarUtil; /** * A utility class for replacing the {@link String#format(String, Object...)} method. * * @author Max Barkley <[email protected]> */ public class StringFormat { private static enum Conversion { bool, hexStr, str, uniChar, decInt, octInt, hexInt, sciInt, decNum, compNum, hexNum, date, escLit, line } private static final String argIndex = "(?:(\\d+)\\$)?"; private static final String flags = "([-#+ 0,(]*)?"; private static final String width = "(\\d+)?"; private static final String prec = "(?:\\.(\\d+))?"; private static final String dateSuffix = "([HIklMSLNpzZsQBbhAaCYyjmdeRTrDFc])?"; // Includes date/time suffix private static final String conv = "([bBhHsScCdoxXeEfgGaA%n]|(?:[tT]" + dateSuffix + "))"; private static RegExp convPattern = RegExp.compile("%" + argIndex + flags + width + prec + conv); /** * This method emulates {@link String#format(String, Object...)} with some * notable differences: * <ul> * <li>flags are unsupported (and are silently ignored)</li> * <li>the '{@code a}' and '{@code A}' conversions are unsupported</li> * <li>the other scientific notation flags use {@link NumberFormat} and thus * produce slightly different output</li> * </ul> * * @param format * The format string. * @param args * The values available for format string conversions. * @return A formatted string, similar to the result of calling * {@link String#format(String, Object...)} with {@code format} and * {@code args}. * @see String#format(String, Object...) */ public static String format(String format, Object... args) { StringBuffer buffer = new StringBuffer(format.length()); final String originalFormat = format; int count = 0; // Special case: user does StringFormat.format("...", null) if (args == null) { args = new Object[] {null}; } int i = 0; while (i < format.length()) { if (format.charAt(i) == '%') { final String subStr = format.substring(i); final MatchResult match = convPattern.exec(subStr); if (match == null || match.getIndex() != 0) { throw new IllegalArgumentException("Bad conversion at index " + i + " in format String: " + format); } if (match.getGroup(2) != null && !match.getGroup(2).equals("")) { throw new UnsupportedOperationException("Flags are not yet supported in this implementation."); } // TODO: check preconditions and possibly throw IllegalFormatException final Object arg; final int width; final int prec; final String suffix; final Conversion conv = getConversion(match.getGroup(5).charAt(0)); final boolean autoIndexed = match.getGroup(1) == null || match.getGroup(1).equals(""); if (conv.equals(Conversion.escLit) || conv.equals(Conversion.line)) { arg = null; } else if (autoIndexed) { arg = args[count]; } else { arg = args[Integer.valueOf(match.getGroup(1)) - 1]; } if (match.getGroup(3) == null || match.getGroup(3).equals("")) { width = 0; } else { width = Integer.valueOf(match.getGroup(3)); } if (match.getGroup(4) == null || match.getGroup(4).equals("")) { prec = Integer.MAX_VALUE; } else { prec = Integer.valueOf(match.getGroup(4)); } if (match.getGroup(6) == null || match.getGroup(6).equals("")) { suffix = ""; } else { suffix = match.getGroup(6); } final boolean upper = match.getGroup(5).toUpperCase().equals(match.getGroup(5)); String replacement; try { replacement = buildReplacement(conv, upper, width, prec, suffix, arg); } catch (Exception e) { throw new IllegalArgumentException("Error processing substitution " + (count + 1) + ".\nFormat: " + originalFormat + "\nArgs: " + Arrays.toString(args), e); } buffer.append(replacement); i += match.getGroup(0).length(); // Auto-index is incremented for non-explicitly indexed conversions if (autoIndexed) count += 1; } else { buffer.append(format.charAt(i++)); } } return buffer.toString(); } private static String buildReplacement(Conversion conv, boolean upper, int width, int prec, String suffix, Object arg) { String res = null; switch (conv) { case bool: if (arg instanceof Boolean) { if ((Boolean) arg) { res = "true"; } else { res = "false"; } } else if (arg != null) { res = "true"; } else { res = "false"; } break; case date: if (suffix == null || suffix.length() != 1) throw new IllegalArgumentException("Must provide suffix with date conversion."); if (arg instanceof Long) arg = new Date((Long) arg); res = processDate((Date) arg, upper, suffix.charAt(0)); break; case decInt: res = String.valueOf((Integer) arg); break; case decNum: if (arg instanceof Float) { res = String.valueOf((Float) arg); } else { res = String.valueOf((Double) arg); } break; case hexInt: res = Integer.toHexString((Integer) arg); break; case hexStr: if (arg == null) res = "null"; else res = Integer.toHexString(arg.hashCode()); break; case octInt: res = Integer.toOctalString((Integer) arg); break; case str: if (arg == null) res = "null"; else res = arg.toString(); break; case uniChar: if (arg instanceof Integer) arg = Character.valueOf((char) ((Integer) arg).intValue()); res = Character.toString((Character) arg); break; case compNum: case sciInt: if (arg instanceof Float) { arg = Double.valueOf((Float) arg); } if (Integer.MAX_VALUE == prec) prec = 6; final StringBuilder formatString = new StringBuilder(prec+5); formatString.append("0."); for (int i = 0; i < prec; i++) formatString.append('0'); formatString.append("E00"); res = NumberFormat.getFormat(formatString.toString()).format((Double) arg); if (!upper) res = res.toLowerCase(); return padOrTrunc(res, width, Integer.MAX_VALUE); // TODO case hexNum: throw new UnsupportedOperationException(); case line: return "\n"; case escLit: return "%"; } res = padOrTrunc(res, width, prec); if (upper) return res.toUpperCase(); else return res; } @SuppressWarnings("deprecation") private static String processDate(Date date, boolean upper, char suffix) { String retVal = null; switch (suffix) { case 'k': retVal = String.valueOf(date.getHours()); break; case 'H': retVal = String.valueOf(padInt(date.getHours(), 2)); break; case 'l': retVal = String.valueOf(date.getHours() % 12); break; case 'I': retVal = String.valueOf(padInt(date.getHours() % 12, 2)); break; case 'M': retVal = String.valueOf(padInt(date.getMinutes(), 2)); break; case 'S': retVal = String.valueOf(padInt(date.getSeconds(), 2)); break; case 'L': retVal = String.valueOf(padInt((int) (date.getTime() % 1000), 3)); break; case 'N': retVal = String.valueOf(padInt((int) ((date.getTime() % 1000) * 1000000), 9)); break; case 'p': retVal = LocaleInfo.getCurrentLocale().getDateTimeFormatInfo().ampms()[date.getHours() / 12]; break; case 's': retVal = String.valueOf(date.getTime() / 1000); break; case 'Q': retVal = String.valueOf(date.getTime()); break; case 'C': retVal = String.valueOf(padInt((date.getYear() + 1900) / 100, 2)); break; case 'Y': retVal = String.valueOf(padInt(date.getYear() + 1900, 4)); break; case 'y': retVal = String.valueOf(padInt(date.getYear() % 100, 2)); break; case 'j': final Date lastYear = new Date(date.getTime()); lastYear.setYear(date.getYear() - 1); lastYear.setMonth(11); lastYear.setDate(31); retVal = String.valueOf(padInt(CalendarUtil.getDaysBetween(lastYear, date), 3)); break; case 'z': retVal = TimeZone.createTimeZone(date.getTimezoneOffset()).getRFCTimeZoneString(date); break; case 'm': retVal = String.valueOf(padInt(date.getMonth() + 1, 2)); break; case 'd': retVal = String.valueOf(padInt(date.getDate(), 2)); break; case 'e': retVal = String.valueOf(date.getDate()); break; case 'R': retVal = processDate(date, false, 'H') + ":" + processDate(date, false, 'M'); break; case 'T': retVal = processDate(date, false, 'R') + ":" + processDate(date, false, 'S'); break; case 'r': retVal = processDate(date, false, 'I') + ":" + processDate(date, false, 'M') + ":" + processDate(date, upper, 'S') + " " + processDate(date, true, 'p'); break; case 'D': retVal = processDate(date, false, 'm') + "/" + processDate(date, false, 'd') + "/" + processDate(date, false, 'y'); break; case 'F': retVal = processDate(date, false, 'Y') + "-" + processDate(date, false, 'm') + "-" + processDate(date, false, 'd'); break; case 'Z': retVal = TimeZone.createTimeZone(date.getTimezoneOffset()).getShortName(date); break; case 'B': retVal = LocaleInfo.getCurrentLocale().getDateTimeFormatInfo().monthsFull()[date.getMonth()]; break; case 'b': case 'h': retVal = LocaleInfo.getCurrentLocale().getDateTimeFormatInfo().monthsShort()[date.getMonth()]; break; case 'A': retVal = LocaleInfo.getCurrentLocale().getDateTimeFormatInfo().weekdaysFull()[date.getDay()]; break; case 'a': retVal = LocaleInfo.getCurrentLocale().getDateTimeFormatInfo().weekdaysShort()[date.getDay()]; break; case 'c': retVal = processDate(date, false, 'a') + " " + processDate(date, false, 'b') + " " + processDate(date, false, 'd') + " " + processDate(date, false, 'T') + " " + processDate(date, false, 'Z') + " " + processDate(date, false, 'Y'); break; default: throw new IllegalArgumentException("Invalid date suffix: " + suffix); } if (upper) return retVal.toUpperCase(); else return retVal; } private static String padInt(int num, int width) { final StringBuilder builder = new StringBuilder(width); // num %= (int) Math.pow(10, width); for (int d = width - 1; d >= 0; d--) { int div = (int) Math.pow(10, d); builder.append(num / div); num %= div; } return builder.toString(); } private static String padOrTrunc(String res, int min, int max) { if (res.length() < min) { final StringBuilder builder = new StringBuilder(min); for (int i = 0; i < min - res.length(); i++) { builder.append(" "); } builder.append(res); return builder.toString(); } else if (res.length() > max) { return res.substring(0, max); } else { return res; } } private static Conversion getConversion(char c) { switch (c) { case 'b': case 'B': return Conversion.bool; case 'h': case 'H': return Conversion.hexStr; case 's': case 'S': return Conversion.str; case 'c': case 'C': return Conversion.uniChar; case 'd': return Conversion.decInt; case 'o': return Conversion.octInt; case 'x': case 'X': return Conversion.hexInt; case 'e': case 'E': return Conversion.sciInt; case 'f': return Conversion.decNum; case 'g': case 'G': return Conversion.compNum; case 'a': case 'A': return Conversion.hexNum; case 'T': case 't': return Conversion.date; case '%': return Conversion.escLit; case 'n': return Conversion.line; default: throw new IllegalArgumentException(c + " is not a valid conversion character."); } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:textSize="@dimen/default_label_size" android:text="@string/vert_drag_label" android:lines="1" /> <!-- When over-scrolling is applied over views that don't stretch over the entire vertical region, an artificial parent must be introduced so that bounds are clipped while over-scrolling is in effect. --> <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:paddingTop="@dimen/activity_vertical_margin" android:layout_weight="1" > <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </LinearLayout>
{ "pile_set_name": "Github" }
{ "name": "data-lake-authorizer", "description": "A Lambda function for authorizing access to the Data Lake API", "main": "index.js", "author": { "name": "aws-solutions-builder" }, "license": "Apache-2.0", "version": "0.0.1", "private": "true", "dependencies": { "moment": "^2.22.2", "underscore": "^1.9.1", "jsonwebtoken": "^8.3.0", "jwk-to-pem": "^2.0.0", "request": "^2.88.0", "js-base64": "^2.4.9" }, "devDependencies": { "grunt": "^0.4.5", "grunt-aws-lambda": "^0.13.0", "grunt-pack": "^0.1.*", "grunt-contrib-clean": "^2.0.0", "chai": "^4.2.0", "sinon": "^2.4.1", "sinon-chai": "^3.3.0", "mocha": "^6.2.2", "aws-sdk-mock": "^4.5.0", "npm-run-all": "^4.1.5" }, "scripts": { "test": "mocha *.spec.js", "build-init": "rm -rf dist && rm -f archive.zip && mkdir dist", "build:copy": "cp index.js dist/", "build:install": "cp package.json dist/ && cd dist && npm install --production", "build": "npm-run-all -s build-init build:copy build:install", "zip": "cd dist && zip -rq data-lake-authorizer.zip ." }, "bundledDependencies": [ "moment", "jsonwebtoken", "jwk-to-pem", "request", "underscore", "js-base64" ] }
{ "pile_set_name": "Github" }
/** * @file enums.h * * Various global enumerators. */ typedef enum item_quality { ITEM_QUALITY_NORMAL = 0, ITEM_QUALITY_MAGIC = 1, ITEM_QUALITY_UNIQUE = 2, } item_quality; typedef enum unique_base_item { UITYPE_NONE = 0x0, UITYPE_SHORTBOW = 0x1, UITYPE_LONGBOW = 0x2, UITYPE_HUNTBOW = 0x3, UITYPE_COMPBOW = 0x4, UITYPE_WARBOW = 0x5, UITYPE_BATTLEBOW = 0x6, UITYPE_DAGGER = 0x7, UITYPE_FALCHION = 0x8, UITYPE_CLAYMORE = 0x9, UITYPE_BROADSWR = 0xA, UITYPE_SABRE = 0xB, UITYPE_SCIMITAR = 0xC, UITYPE_LONGSWR = 0xD, UITYPE_BASTARDSWR = 0xE, UITYPE_TWOHANDSWR = 0xF, UITYPE_GREATSWR = 0x10, UITYPE_CLEAVER = 0x11, UITYPE_LARGEAXE = 0x12, UITYPE_BROADAXE = 0x13, UITYPE_SMALLAXE = 0x14, UITYPE_BATTLEAXE = 0x15, UITYPE_GREATAXE = 0x16, UITYPE_MACE = 0x17, UITYPE_MORNSTAR = 0x18, UITYPE_SPIKCLUB = 0x19, UITYPE_MAUL = 0x1A, UITYPE_WARHAMMER = 0x1B, UITYPE_FLAIL = 0x1C, UITYPE_LONGSTAFF = 0x1D, UITYPE_SHORTSTAFF = 0x1E, UITYPE_COMPSTAFF = 0x1F, UITYPE_QUARSTAFF = 0x20, UITYPE_WARSTAFF = 0x21, UITYPE_SKULLCAP = 0x22, UITYPE_HELM = 0x23, UITYPE_GREATHELM = 0x24, UITYPE_CROWN = 0x25, UITYPE_38 = 0x26, UITYPE_RAGS = 0x27, UITYPE_STUDARMOR = 0x28, UITYPE_CLOAK = 0x29, UITYPE_ROBE = 0x2A, UITYPE_CHAINMAIL = 0x2B, UITYPE_LEATHARMOR = 0x2C, UITYPE_BREASTPLATE = 0x2D, UITYPE_CAPE = 0x2E, UITYPE_PLATEMAIL = 0x2F, UITYPE_FULLPLATE = 0x30, UITYPE_BUCKLER = 0x31, UITYPE_SMALLSHIELD = 0x32, UITYPE_LARGESHIELD = 0x33, UITYPE_KITESHIELD = 0x34, UITYPE_GOTHSHIELD = 0x35, UITYPE_RING = 0x36, UITYPE_55 = 0x37, UITYPE_AMULET = 0x38, UITYPE_SKCROWN = 0x39, UITYPE_INFRARING = 0x3A, UITYPE_OPTAMULET = 0x3B, UITYPE_TRING = 0x3C, UITYPE_HARCREST = 0x3D, UITYPE_MAPOFDOOM = 0x3E, UITYPE_ELIXIR = 0x3F, UITYPE_ARMOFVAL = 0x40, UITYPE_STEELVEIL = 0x41, UITYPE_GRISWOLD = 0x42, UITYPE_LGTFORGE = 0x43, UITYPE_LAZSTAFF = 0x44, UITYPE_INVALID = -1, } unique_base_item; typedef enum item_effect_type { IPL_TOHIT = 0x0, IPL_TOHIT_CURSE = 0x1, IPL_DAMP = 0x2, IPL_DAMP_CURSE = 0x3, IPL_TOHIT_DAMP = 0x4, IPL_TOHIT_DAMP_CURSE = 0x5, IPL_ACP = 0x6, IPL_ACP_CURSE = 0x7, IPL_FIRERES = 0x8, IPL_LIGHTRES = 0x9, IPL_MAGICRES = 0xA, IPL_ALLRES = 0xB, IPL_SPLCOST = 0xC, /* only used in beta */ IPL_SPLDUR = 0xD, /* only used in beta */ IPL_SPLLVLADD = 0xE, IPL_CHARGES = 0xF, IPL_FIREDAM = 0x10, IPL_LIGHTDAM = 0x11, IPL_STR = 0x13, IPL_STR_CURSE = 0x14, IPL_MAG = 0x15, IPL_MAG_CURSE = 0x16, IPL_DEX = 0x17, IPL_DEX_CURSE = 0x18, IPL_VIT = 0x19, IPL_VIT_CURSE = 0x1A, IPL_ATTRIBS = 0x1B, IPL_ATTRIBS_CURSE = 0x1C, IPL_GETHIT_CURSE = 0x1D, IPL_GETHIT = 0x1E, IPL_LIFE = 0x1F, IPL_LIFE_CURSE = 0x20, IPL_MANA = 0x21, IPL_MANA_CURSE = 0x22, IPL_DUR = 0x23, IPL_DUR_CURSE = 0x24, IPL_INDESTRUCTIBLE = 0x25, IPL_LIGHT = 0x26, IPL_LIGHT_CURSE = 0x27, IPL_MULT_ARROWS = 0x29, /* only used in hellfire */ IPL_FIRE_ARROWS = 0x2A, IPL_LIGHT_ARROWS = 0x2B, IPL_INVCURS = 0x2C, IPL_THORNS = 0x2D, IPL_NOMANA = 0x2E, IPL_NOHEALPLR = 0x2F, IPL_FIREBALL = 0x32, /* only used in hellfire */ IPL_ABSHALFTRAP = 0x34, IPL_KNOCKBACK = 0x35, IPL_NOHEALMON = 0x36, IPL_STEALMANA = 0x37, IPL_STEALLIFE = 0x38, IPL_TARGAC = 0x39, IPL_FASTATTACK = 0x3A, IPL_FASTRECOVER = 0x3B, IPL_FASTBLOCK = 0x3C, IPL_DAMMOD = 0x3D, IPL_RNDARROWVEL = 0x3E, IPL_SETDAM = 0x3F, IPL_SETDUR = 0x40, IPL_NOMINSTR = 0x41, IPL_SPELL = 0x42, IPL_FASTSWING = 0x43, IPL_ONEHAND = 0x44, IPL_3XDAMVDEM = 0x45, IPL_ALLRESZERO = 0x46, IPL_DRAINLIFE = 0x48, IPL_RNDSTEALLIFE = 0x49, IPL_INFRAVISION = 0x4A, IPL_SETAC = 0x4B, IPL_ADDACLIFE = 0x4C, IPL_ADDMANAAC = 0x4D, IPL_FIRERESCLVL = 0x4E, IPL_AC_CURSE = 0x4F, IPL_INVALID = -1, } item_effect_type; typedef enum affix_item_type { PLT_MISC = 0x1, PLT_BOW = 0x10, PLT_STAFF = 0x100, PLT_WEAP = 0x1000, PLT_SHLD = 0x10000, PLT_ARMO = 0x100000, } affix_item_type; /// Item graphic IDs; frame_num-11 of objcurs.cel. typedef enum item_cursor_graphic { ICURS_POTION_OF_FULL_MANA = 0, ICURS_SCROLL_OF = 1, ICURS_GOLD_SMALL = 4, ICURS_GOLD_MEDIUM = 5, ICURS_GOLD_LARGE = 6, ICURS_RING_OF_TRUTH = 10, ICURS_RING = 12, ICURS_SPECTRAL_ELIXIR = 15, ICURS_GOLDEN_ELIXIR = 17, ICURS_EMPYREAN_BAND = 18, ICURS_EAR_SORCEROR = 19, ICURS_EAR_WARRIOR = 20, ICURS_EAR_ROGUE = 21, ICURS_BLOOD_STONE = 25, ICURS_ELIXIR_OF_VITALITY = 31, ICURS_POTION_OF_HEALING = 32, ICURS_POTION_OF_FULL_REJUVENATION = 33, ICURS_ELIXIR_OF_MAGIC = 34, ICURS_POTION_OF_FULL_HEALING = 35, ICURS_ELIXIR_OF_DEXTERITY = 36, ICURS_POTION_OF_REJUVENATION = 37, ICURS_ELIXIR_OF_STRENGTH = 38, ICURS_POTION_OF_MANA = 39, ICURS_BRAIN = 40, ICURS_OPTIC_AMULET = 44, ICURS_AMULET = 45, ICURS_DAGGER = 51, ICURS_BLADE = 56, ICURS_BASTARD_SWORD = 57, ICURS_MACE = 59, ICURS_LONG_SWORD = 60, ICURS_BROAD_SWORD = 61, ICURS_FALCHION = 62, ICURS_MORNING_STAR = 63, ICURS_SHORT_SWORD = 64, ICURS_CLAYMORE = 65, ICURS_CLUB = 66, ICURS_SABRE = 67, ICURS_SPIKED_CLUB = 70, ICURS_SCIMITAR = 72, ICURS_FULL_HELM = 75, ICURS_MAGIC_ROCK = 76, ICURS_THE_UNDEAD_CROWN = 78, ICURS_HELM = 82, ICURS_BUCKLER = 83, ICURS_VIEL_OF_STEEL = 85, ICURS_BOOK_GREY = 86, ICURS_BOOK_RED = 87, ICURS_BOOK_BLUE = 88, ICURS_BLACK_MUSHROOM = 89, ICURS_SKULL_CAP = 90, ICURS_CAP = 91, ICURS_HARLEQUIN_CREST = 93, ICURS_CROWN = 95, ICURS_MAP_OF_THE_STARS = 96, ICURS_FUNGAL_TOME = 97, ICURS_GREAT_HELM = 98, ICURS_BATTLE_AXE = 101, ICURS_HUNTERS_BOW = 102, ICURS_FIELD_PLATE = 103, ICURS_SMALL_SHIELD = 105, ICURS_CLEAVER = 106, ICURS_STUDDED_LEATHER_ARMOR = 107, ICURS_SHORT_STAFF = 109, ICURS_TWO_HANDED_SWORD = 110, ICURS_CHAIN_MAIL = 111, ICURS_SMALL_AXE = 112, ICURS_KITE_SHIELD = 113, ICURS_SCALE_MAIL = 114, ICURS_SHORT_BOW = 118, ICURS_LONG_WAR_BOW = 119, ICURS_WAR_HAMMER = 121, ICURS_MAUL = 122, ICURS_LONG_STAFF = 123, ICURS_WAR_STAFF = 124, ICURS_TAVERN_SIGN = 126, ICURS_HARD_LEATHER_ARMOR = 127, ICURS_RAGS = 128, ICURS_QUILTED_ARMOR = 129, ICURS_FLAIL = 131, ICURS_TOWER_SHIELD = 132, ICURS_COMPOSITE_BOW = 133, ICURS_GREAT_SWORD = 134, ICURS_LEATHER_ARMOR = 135, ICURS_SPLINT_MAIL = 136, ICURS_ROBE = 137, ICURS_ANVIL_OF_FURY = 140, ICURS_BROAD_AXE = 141, ICURS_LARGE_AXE = 142, ICURS_GREAT_AXE = 143, ICURS_AXE = 144, ICURS_LARGE_SHIELD = 147, ICURS_GOTHIC_SHIELD = 148, ICURS_CLOAK = 149, ICURS_CAPE = 150, ICURS_FULL_PLATE_MAIL = 151, ICURS_GOTHIC_PLATE = 152, ICURS_BREAST_PLATE = 153, ICURS_RING_MAIL = 154, ICURS_STAFF_OF_LAZARUS = 155, ICURS_ARKAINES_VALOR = 157, ICURS_SHORT_WAR_BOW = 165, ICURS_COMPOSITE_STAFF = 166, ICURS_SHORT_BATTLE_BOW = 167, ICURS_GOLD = 168, } item_cursor_graphic; typedef enum _sfx_id { PS_WALK1, PS_WALK2, PS_WALK3, PS_WALK4, PS_BFIRE, PS_FMAG, PS_TMAG, PS_LGHIT, PS_LGHIT1, PS_SWING, PS_SWING2, PS_DEAD, IS_QUESTDN, IS_ARMRFKD, IS_BARLFIRE, IS_BARREL, IS_BHIT, IS_BHIT1, IS_CHEST, IS_DOORCLOS, IS_DOOROPEN, IS_FANVL, IS_FAXE, IS_FBLST, IS_FBODY, IS_FBOOK, IS_FBOW, IS_FCAP, IS_FHARM, IS_FLARM, IS_FMAG, IS_FMAG1, IS_FMUSH, IS_FPOT, IS_FRING, IS_FROCK, IS_FSCRL, IS_FSHLD, IS_FSIGN, IS_FSTAF, IS_FSWOR, IS_GOLD, IS_HLMTFKD, IS_IANVL, IS_IAXE, IS_IBLST, IS_IBODY, IS_IBOOK, IS_IBOW, IS_ICAP, IS_IGRAB, IS_IHARM, IS_ILARM, IS_IMUSH, IS_IPOT, IS_IRING, IS_IROCK, IS_ISCROL, IS_ISHIEL, IS_ISIGN, IS_ISTAF, IS_ISWORD, IS_LEVER, IS_MAGIC, IS_MAGIC1, IS_RBOOK, IS_SARC, IS_SHLDFKD, IS_SWRDFKD, IS_TITLEMOV, IS_TITLSLCT, SFX_SILENCE, IS_TRAP, IS_CAST1, IS_CAST10, IS_CAST12, IS_CAST2, IS_CAST3, IS_CAST4, IS_CAST5, IS_CAST6, IS_CAST7, IS_CAST8, IS_CAST9, LS_HEALING, IS_REPAIR, LS_ACID, LS_ACIDS, LS_APOC, LS_ARROWALL, LS_BLODBOIL, LS_BLODSTAR, LS_BLSIMPT, LS_BONESP, LS_BSIMPCT, LS_CALDRON, LS_CBOLT, LS_CHLTNING, LS_DSERP, LS_ELECIMP1, LS_ELEMENTL, LS_ETHEREAL, LS_FBALL, LS_FBOLT1, LS_FBOLT2, LS_FIRIMP1, LS_FIRIMP2, LS_FLAMWAVE, LS_FLASH, LS_FOUNTAIN, LS_GOLUM, LS_GOLUMDED, LS_GSHRINE, LS_GUARD, LS_GUARDLAN, LS_HOLYBOLT, LS_HYPER, LS_INFRAVIS, LS_INVISIBL, LS_INVPOT, LS_LNING1, LS_LTNING, LS_MSHIELD, LS_NOVA, LS_PORTAL, LS_PUDDLE, LS_RESUR, LS_SCURSE, LS_SCURIMP, LS_SENTINEL, LS_SHATTER, LS_SOULFIRE, LS_SPOUTLOP, LS_SPOUTSTR, LS_STORM, LS_TRAPDIS, LS_TELEPORT, LS_VTHEFT, LS_WALLLOOP, LS_WALLSTRT, #ifndef SPAWN TSFX_BMAID1, TSFX_BMAID2, TSFX_BMAID3, TSFX_BMAID4, TSFX_BMAID5, TSFX_BMAID6, TSFX_BMAID7, TSFX_BMAID8, TSFX_BMAID9, TSFX_BMAID10, TSFX_BMAID11, TSFX_BMAID12, TSFX_BMAID13, TSFX_BMAID14, TSFX_BMAID15, TSFX_BMAID16, TSFX_BMAID17, TSFX_BMAID18, TSFX_BMAID19, TSFX_BMAID20, TSFX_BMAID21, TSFX_BMAID22, TSFX_BMAID23, TSFX_BMAID24, TSFX_BMAID25, TSFX_BMAID26, TSFX_BMAID27, TSFX_BMAID28, TSFX_BMAID29, TSFX_BMAID30, #endif TSFX_BMAID31, #ifndef SPAWN TSFX_BMAID32, TSFX_BMAID33, TSFX_BMAID34, TSFX_BMAID35, TSFX_BMAID36, TSFX_BMAID37, TSFX_BMAID38, TSFX_BMAID39, TSFX_BMAID40, TSFX_SMITH1, TSFX_SMITH2, TSFX_SMITH3, TSFX_SMITH4, TSFX_SMITH5, TSFX_SMITH6, TSFX_SMITH7, TSFX_SMITH8, TSFX_SMITH9, TSFX_SMITH10, TSFX_SMITH11, TSFX_SMITH12, TSFX_SMITH13, TSFX_SMITH14, TSFX_SMITH15, TSFX_SMITH16, TSFX_SMITH17, TSFX_SMITH18, TSFX_SMITH19, TSFX_SMITH20, TSFX_SMITH21, TSFX_SMITH22, TSFX_SMITH23, TSFX_SMITH24, TSFX_SMITH25, TSFX_SMITH26, TSFX_SMITH27, TSFX_SMITH28, TSFX_SMITH29, TSFX_SMITH30, TSFX_SMITH31, TSFX_SMITH32, TSFX_SMITH33, TSFX_SMITH34, TSFX_SMITH35, TSFX_SMITH36, TSFX_SMITH37, TSFX_SMITH38, TSFX_SMITH39, TSFX_SMITH40, TSFX_SMITH41, TSFX_SMITH42, TSFX_SMITH43, #endif TSFX_SMITH44, #ifndef SPAWN TSFX_SMITH45, TSFX_SMITH46, TSFX_SMITH47, TSFX_SMITH48, TSFX_SMITH49, TSFX_SMITH50, TSFX_SMITH51, TSFX_SMITH52, TSFX_SMITH53, TSFX_SMITH54, TSFX_SMITH55, TSFX_SMITH56, #endif TSFX_COW1, TSFX_COW2, #ifndef SPAWN TSFX_DEADGUY, TSFX_DRUNK1, TSFX_DRUNK2, TSFX_DRUNK3, TSFX_DRUNK4, TSFX_DRUNK5, TSFX_DRUNK6, TSFX_DRUNK7, TSFX_DRUNK8, TSFX_DRUNK9, TSFX_DRUNK10, TSFX_DRUNK11, TSFX_DRUNK12, TSFX_DRUNK13, TSFX_DRUNK14, TSFX_DRUNK15, TSFX_DRUNK16, TSFX_DRUNK17, TSFX_DRUNK18, TSFX_DRUNK19, TSFX_DRUNK20, TSFX_DRUNK21, TSFX_DRUNK22, TSFX_DRUNK23, TSFX_DRUNK24, TSFX_DRUNK25, TSFX_DRUNK26, #endif TSFX_DRUNK27, #ifndef SPAWN TSFX_DRUNK28, TSFX_DRUNK29, TSFX_DRUNK30, TSFX_DRUNK31, TSFX_DRUNK32, TSFX_DRUNK33, TSFX_DRUNK34, TSFX_DRUNK35, TSFX_HEALER1, TSFX_HEALER2, TSFX_HEALER3, TSFX_HEALER4, TSFX_HEALER5, TSFX_HEALER6, TSFX_HEALER7, TSFX_HEALER8, TSFX_HEALER9, TSFX_HEALER10, TSFX_HEALER11, TSFX_HEALER12, TSFX_HEALER13, TSFX_HEALER14, TSFX_HEALER15, TSFX_HEALER16, TSFX_HEALER17, TSFX_HEALER18, TSFX_HEALER19, TSFX_HEALER20, TSFX_HEALER21, TSFX_HEALER22, TSFX_HEALER23, TSFX_HEALER24, TSFX_HEALER25, TSFX_HEALER26, TSFX_HEALER27, TSFX_HEALER28, TSFX_HEALER29, TSFX_HEALER30, TSFX_HEALER31, TSFX_HEALER32, TSFX_HEALER33, TSFX_HEALER34, TSFX_HEALER35, TSFX_HEALER36, #endif TSFX_HEALER37, #ifndef SPAWN TSFX_HEALER38, TSFX_HEALER39, TSFX_HEALER40, TSFX_HEALER41, TSFX_HEALER42, TSFX_HEALER43, TSFX_HEALER44, TSFX_HEALER45, TSFX_HEALER46, TSFX_HEALER47, TSFX_PEGBOY1, TSFX_PEGBOY2, TSFX_PEGBOY3, TSFX_PEGBOY4, TSFX_PEGBOY5, TSFX_PEGBOY6, TSFX_PEGBOY7, TSFX_PEGBOY8, TSFX_PEGBOY9, TSFX_PEGBOY10, TSFX_PEGBOY11, TSFX_PEGBOY12, TSFX_PEGBOY13, TSFX_PEGBOY14, TSFX_PEGBOY15, TSFX_PEGBOY16, TSFX_PEGBOY17, TSFX_PEGBOY18, TSFX_PEGBOY19, TSFX_PEGBOY20, TSFX_PEGBOY21, TSFX_PEGBOY22, TSFX_PEGBOY23, TSFX_PEGBOY24, TSFX_PEGBOY25, TSFX_PEGBOY26, TSFX_PEGBOY27, TSFX_PEGBOY28, TSFX_PEGBOY29, TSFX_PEGBOY30, TSFX_PEGBOY31, #endif TSFX_PEGBOY32, #ifndef SPAWN TSFX_PEGBOY33, TSFX_PEGBOY34, TSFX_PEGBOY35, TSFX_PEGBOY36, TSFX_PEGBOY37, TSFX_PEGBOY38, TSFX_PEGBOY39, TSFX_PEGBOY40, TSFX_PEGBOY41, TSFX_PEGBOY42, TSFX_PEGBOY43, TSFX_PRIEST0, TSFX_PRIEST1, TSFX_PRIEST2, TSFX_PRIEST3, TSFX_PRIEST4, TSFX_PRIEST5, TSFX_PRIEST6, TSFX_PRIEST7, TSFX_STORY0, TSFX_STORY1, TSFX_STORY2, TSFX_STORY3, TSFX_STORY4, TSFX_STORY5, TSFX_STORY6, TSFX_STORY7, TSFX_STORY8, TSFX_STORY9, TSFX_STORY10, TSFX_STORY11, TSFX_STORY12, TSFX_STORY13, TSFX_STORY14, TSFX_STORY15, TSFX_STORY16, TSFX_STORY17, TSFX_STORY18, TSFX_STORY19, TSFX_STORY20, TSFX_STORY21, TSFX_STORY22, TSFX_STORY23, TSFX_STORY24, #endif TSFX_STORY25, #ifndef SPAWN TSFX_STORY26, TSFX_STORY27, TSFX_STORY28, TSFX_STORY29, TSFX_STORY30, TSFX_STORY31, TSFX_STORY32, TSFX_STORY33, TSFX_STORY34, TSFX_STORY35, TSFX_STORY36, TSFX_STORY37, TSFX_STORY38, #endif TSFX_TAVERN0, #ifndef SPAWN TSFX_TAVERN1, TSFX_TAVERN2, TSFX_TAVERN3, TSFX_TAVERN4, TSFX_TAVERN5, TSFX_TAVERN6, TSFX_TAVERN7, TSFX_TAVERN8, TSFX_TAVERN9, TSFX_TAVERN10, TSFX_TAVERN11, TSFX_TAVERN12, TSFX_TAVERN13, TSFX_TAVERN14, TSFX_TAVERN15, TSFX_TAVERN16, TSFX_TAVERN17, TSFX_TAVERN18, TSFX_TAVERN19, TSFX_TAVERN20, TSFX_TAVERN21, TSFX_TAVERN22, TSFX_TAVERN23, TSFX_TAVERN24, TSFX_TAVERN25, TSFX_TAVERN26, TSFX_TAVERN27, TSFX_TAVERN28, TSFX_TAVERN29, TSFX_TAVERN30, TSFX_TAVERN31, TSFX_TAVERN32, TSFX_TAVERN33, TSFX_TAVERN34, TSFX_TAVERN35, #endif TSFX_TAVERN36, #ifndef SPAWN TSFX_TAVERN37, TSFX_TAVERN38, TSFX_TAVERN39, TSFX_TAVERN40, TSFX_TAVERN41, TSFX_TAVERN42, TSFX_TAVERN43, TSFX_TAVERN44, TSFX_TAVERN45, TSFX_WITCH1, TSFX_WITCH2, TSFX_WITCH3, TSFX_WITCH4, TSFX_WITCH5, TSFX_WITCH6, TSFX_WITCH7, TSFX_WITCH8, TSFX_WITCH9, TSFX_WITCH10, TSFX_WITCH11, TSFX_WITCH12, TSFX_WITCH13, TSFX_WITCH14, TSFX_WITCH15, TSFX_WITCH16, TSFX_WITCH17, TSFX_WITCH18, TSFX_WITCH19, TSFX_WITCH20, TSFX_WITCH21, TSFX_WITCH22, TSFX_WITCH23, TSFX_WITCH24, TSFX_WITCH25, TSFX_WITCH26, TSFX_WITCH27, TSFX_WITCH28, TSFX_WITCH29, TSFX_WITCH30, TSFX_WITCH31, TSFX_WITCH32, TSFX_WITCH33, TSFX_WITCH34, TSFX_WITCH35, TSFX_WITCH36, TSFX_WITCH37, #endif TSFX_WITCH38, #ifndef SPAWN TSFX_WITCH39, TSFX_WITCH40, TSFX_WITCH41, TSFX_WITCH42, TSFX_WITCH43, TSFX_WITCH44, TSFX_WITCH45, TSFX_WITCH46, TSFX_WITCH47, TSFX_WITCH48, TSFX_WITCH49, TSFX_WITCH50, TSFX_WOUND, PS_MAGE1, PS_MAGE2, PS_MAGE3, PS_MAGE4, PS_MAGE5, PS_MAGE6, PS_MAGE7, PS_MAGE8, PS_MAGE9, PS_MAGE10, PS_MAGE11, PS_MAGE12, PS_MAGE13, PS_MAGE14, PS_MAGE15, PS_MAGE16, PS_MAGE17, PS_MAGE18, PS_MAGE19, PS_MAGE20, PS_MAGE21, PS_MAGE22, PS_MAGE23, PS_MAGE24, PS_MAGE25, PS_MAGE26, PS_MAGE27, PS_MAGE28, PS_MAGE29, PS_MAGE30, PS_MAGE31, PS_MAGE32, PS_MAGE33, PS_MAGE34, PS_MAGE35, PS_MAGE36, PS_MAGE37, PS_MAGE38, PS_MAGE39, PS_MAGE40, PS_MAGE41, PS_MAGE42, PS_MAGE43, PS_MAGE44, PS_MAGE45, PS_MAGE46, PS_MAGE47, PS_MAGE48, PS_MAGE49, PS_MAGE50, PS_MAGE51, PS_MAGE52, PS_MAGE53, PS_MAGE54, PS_MAGE55, PS_MAGE56, PS_MAGE57, PS_MAGE58, PS_MAGE59, PS_MAGE60, PS_MAGE61, PS_MAGE62, PS_MAGE63, PS_MAGE64, PS_MAGE65, PS_MAGE66, PS_MAGE67, PS_MAGE68, PS_MAGE69, PS_MAGE69B, PS_MAGE70, PS_MAGE71, PS_MAGE72, PS_MAGE73, PS_MAGE74, PS_MAGE75, PS_MAGE76, PS_MAGE77, PS_MAGE78, PS_MAGE79, PS_MAGE80, PS_MAGE81, PS_MAGE82, PS_MAGE83, PS_MAGE84, PS_MAGE85, PS_MAGE86, PS_MAGE87, PS_MAGE88, PS_MAGE89, PS_MAGE90, PS_MAGE91, PS_MAGE92, PS_MAGE93, PS_MAGE94, PS_MAGE95, PS_MAGE96, PS_MAGE97, PS_MAGE98, PS_MAGE99, PS_MAGE100, PS_MAGE101, PS_MAGE102, PS_ROGUE1, PS_ROGUE2, PS_ROGUE3, PS_ROGUE4, PS_ROGUE5, PS_ROGUE6, PS_ROGUE7, PS_ROGUE8, PS_ROGUE9, PS_ROGUE10, PS_ROGUE11, PS_ROGUE12, PS_ROGUE13, PS_ROGUE14, PS_ROGUE15, PS_ROGUE16, PS_ROGUE17, PS_ROGUE18, PS_ROGUE19, PS_ROGUE20, PS_ROGUE21, PS_ROGUE22, PS_ROGUE23, PS_ROGUE24, PS_ROGUE25, PS_ROGUE26, PS_ROGUE27, PS_ROGUE28, PS_ROGUE29, PS_ROGUE30, PS_ROGUE31, PS_ROGUE32, PS_ROGUE33, PS_ROGUE34, PS_ROGUE35, PS_ROGUE36, PS_ROGUE37, PS_ROGUE38, PS_ROGUE39, PS_ROGUE40, PS_ROGUE41, PS_ROGUE42, PS_ROGUE43, PS_ROGUE44, PS_ROGUE45, PS_ROGUE46, PS_ROGUE47, PS_ROGUE48, PS_ROGUE49, PS_ROGUE50, PS_ROGUE51, PS_ROGUE52, PS_ROGUE53, PS_ROGUE54, PS_ROGUE55, PS_ROGUE56, PS_ROGUE57, PS_ROGUE58, PS_ROGUE59, PS_ROGUE60, PS_ROGUE61, PS_ROGUE62, PS_ROGUE63, PS_ROGUE64, PS_ROGUE65, PS_ROGUE66, PS_ROGUE67, PS_ROGUE68, PS_ROGUE69, PS_ROGUE69B, PS_ROGUE70, PS_ROGUE71, PS_ROGUE72, PS_ROGUE73, PS_ROGUE74, PS_ROGUE75, PS_ROGUE76, PS_ROGUE77, PS_ROGUE78, PS_ROGUE79, PS_ROGUE80, PS_ROGUE81, PS_ROGUE82, PS_ROGUE83, PS_ROGUE84, PS_ROGUE85, PS_ROGUE86, PS_ROGUE87, PS_ROGUE88, PS_ROGUE89, PS_ROGUE90, PS_ROGUE91, PS_ROGUE92, PS_ROGUE93, PS_ROGUE94, PS_ROGUE95, PS_ROGUE96, PS_ROGUE97, PS_ROGUE98, PS_ROGUE99, PS_ROGUE100, PS_ROGUE101, PS_ROGUE102, PS_WARR1, PS_WARR2, PS_WARR3, PS_WARR4, PS_WARR5, PS_WARR6, PS_WARR7, PS_WARR8, PS_WARR9, PS_WARR10, PS_WARR11, PS_WARR12, #endif PS_WARR13, PS_WARR14, PS_WARR14B, PS_WARR14C, PS_WARR15, PS_WARR15B, PS_WARR15C, PS_WARR16, PS_WARR16B, PS_WARR16C, PS_WARR17, PS_WARR18, PS_WARR19, PS_WARR20, PS_WARR21, PS_WARR22, PS_WARR23, PS_WARR24, PS_WARR25, PS_WARR26, PS_WARR27, PS_WARR28, PS_WARR29, PS_WARR30, PS_WARR31, PS_WARR32, PS_WARR33, PS_WARR34, PS_WARR35, PS_WARR36, PS_WARR37, PS_WARR38, PS_WARR39, PS_WARR40, PS_WARR41, PS_WARR42, PS_WARR43, PS_WARR44, PS_WARR45, PS_WARR46, PS_WARR47, PS_WARR48, PS_WARR49, PS_WARR50, PS_WARR51, PS_WARR52, PS_WARR53, PS_WARR54, PS_WARR55, PS_WARR56, PS_WARR57, PS_WARR58, PS_WARR59, PS_WARR60, PS_WARR61, PS_WARR62, PS_WARR63, PS_WARR64, PS_WARR65, PS_WARR66, PS_WARR67, PS_WARR68, PS_WARR69, PS_WARR69B, PS_WARR70, PS_WARR71, PS_WARR72, PS_WARR73, PS_WARR74, PS_WARR75, PS_WARR76, PS_WARR77, PS_WARR78, PS_WARR79, #ifndef SPAWN PS_WARR80, PS_WARR81, PS_WARR82, PS_WARR83, PS_WARR84, PS_WARR85, PS_WARR86, PS_WARR87, PS_WARR88, PS_WARR89, PS_WARR90, PS_WARR91, PS_WARR92, PS_WARR93, PS_WARR94, PS_WARR95, PS_WARR95B, PS_WARR95C, PS_WARR95D, PS_WARR95E, PS_WARR95F, #endif PS_WARR96B, PS_WARR97, PS_WARR98, PS_WARR99, #ifndef SPAWN PS_WARR100, PS_WARR101, PS_WARR102, PS_NAR1, PS_NAR2, PS_NAR3, PS_NAR4, PS_NAR5, PS_NAR6, PS_NAR7, PS_NAR8, PS_NAR9, PS_DIABLVLINT, USFX_CLEAVER, USFX_GARBUD1, USFX_GARBUD2, USFX_GARBUD3, USFX_GARBUD4, USFX_IZUAL1, USFX_LACH1, USFX_LACH2, USFX_LACH3, USFX_LAZ1, USFX_LAZ2, USFX_SKING1, USFX_SNOT1, USFX_SNOT2, USFX_SNOT3, USFX_WARLRD1, USFX_WLOCK1, USFX_ZHAR1, USFX_ZHAR2, USFX_DIABLOD, #endif } _sfx_id; typedef enum sfx_flag { sfx_STREAM = 0x01, sfx_MISC = 0x02, sfx_UI = 0x04, sfx_MONK = 0x08, sfx_ROGUE = 0x10, sfx_WARRIOR = 0x20, sfx_SORCEROR = 0x40, sfx_LOADED = 0x80, } sfx_flag; typedef enum item_equip_type { ILOC_NONE = 0x0, ILOC_ONEHAND = 0x1, ILOC_TWOHAND = 0x2, ILOC_ARMOR = 0x3, ILOC_HELM = 0x4, ILOC_RING = 0x5, ILOC_AMULET = 0x6, ILOC_UNEQUIPABLE = 0x7, ILOC_BELT = 0x8, ILOC_INVALID = -1, } item_equip_type; typedef enum missile_id { MIS_ARROW = 0x0, MIS_FIREBOLT = 0x1, MIS_GUARDIAN = 0x2, MIS_RNDTELEPORT = 0x3, MIS_LIGHTBALL = 0x4, MIS_FIREWALL = 0x5, MIS_FIREBALL = 0x6, MIS_LIGHTCTRL = 0x7, MIS_LIGHTNING = 0x8, MIS_MISEXP = 0x9, MIS_TOWN = 0xA, MIS_FLASH = 0xB, MIS_FLASH2 = 0xC, MIS_MANASHIELD = 0xD, MIS_FIREMOVE = 0xE, MIS_CHAIN = 0xF, MIS_SENTINAL = 0x10, // TODO: Check beta MIS_BLODSTAR = 0x11, // TODO: Check beta MIS_BONE = 0x12, // TODO: Check beta MIS_METLHIT = 0x13, // TODO: Check beta MIS_RHINO = 0x14, MIS_MAGMABALL = 0x15, MIS_LIGHTCTRL2 = 0x16, MIS_LIGHTNING2 = 0x17, MIS_FLARE = 0x18, MIS_MISEXP2 = 0x19, MIS_TELEPORT = 0x1A, MIS_FARROW = 0x1B, MIS_DOOMSERP = 0x1C, MIS_FIREWALLA = 0x1D, // TODO: Check beta MIS_STONE = 0x1E, MIS_NULL_1F = 0x1F, MIS_INVISIBL = 0x20, MIS_GOLEM = 0x21, MIS_ETHEREALIZE = 0x22, MIS_BLODBUR = 0x23, // TODO: Check beta MIS_BOOM = 0x24, MIS_HEAL = 0x25, MIS_FIREWALLC = 0x26, MIS_INFRA = 0x27, MIS_IDENTIFY = 0x28, MIS_WAVE = 0x29, MIS_NOVA = 0x2A, MIS_BLODBOIL = 0x2B, MIS_APOCA = 0x2C, MIS_REPAIR = 0x2D, MIS_RECHARGE = 0x2E, MIS_DISARM = 0x2F, MIS_FLAME = 0x30, MIS_FLAMEC = 0x31, MIS_FIREMAN = 0x32, // TODO: Check beta MIS_KRULL = 0x33, // TODO: Check beta MIS_CBOLT = 0x34, MIS_HBOLT = 0x35, MIS_RESURRECT = 0x36, MIS_TELEKINESIS = 0x37, MIS_LARROW = 0x38, MIS_ACID = 0x39, MIS_MISEXP3 = 0x3A, MIS_ACIDPUD = 0x3B, MIS_HEALOTHER = 0x3C, MIS_ELEMENT = 0x3D, MIS_RESURRECTBEAM = 0x3E, MIS_BONESPIRIT = 0x3F, MIS_WEAPEXP = 0x40, MIS_RPORTAL = 0x41, MIS_BOOM2 = 0x42, MIS_DIABAPOCA = 0x43, } missile_id; typedef enum missile_graphic_id { MFILE_ARROWS, MFILE_FIREBA, MFILE_GUARD, MFILE_LGHNING, MFILE_FIREWAL, MFILE_MAGBLOS, MFILE_PORTAL, MFILE_BLUEXFR, MFILE_BLUEXBK, MFILE_MANASHLD, MFILE_BLOOD, MFILE_BONE, MFILE_METLHIT, MFILE_FARROW, MFILE_DOOM, MFILE_0F, MFILE_BLODBUR, MFILE_NEWEXP, MFILE_SHATTER1, MFILE_BIGEXP, MFILE_INFERNO, MFILE_THINLGHT, MFILE_FLARE, MFILE_FLAREEXP, MFILE_MAGBALL, MFILE_KRULL, MFILE_MINILTNG, MFILE_HOLY, MFILE_HOLYEXPL, MFILE_LARROW, MFILE_FIRARWEX, MFILE_ACIDBF, MFILE_ACIDSPLA, MFILE_ACIDPUD, MFILE_ETHRSHLD, MFILE_FIRERUN, MFILE_RESSUR1, MFILE_SKLBALL, MFILE_RPORTAL, MFILE_FIREPLAR, MFILE_SCUBMISB, MFILE_SCBSEXPB, MFILE_SCUBMISC, MFILE_SCBSEXPC, MFILE_SCUBMISD, MFILE_SCBSEXPD, MFILE_NULL, MFILE_NONE = 0xFF, // BUGFIX: should be `MFILE_NONE = MFILE_SCBSEXPD+1`, i.e. MFILE_NULL, since there would otherwise be an out-of-bounds in SetMissAnim when accessing misfiledata for any of the missiles that have MFILE_NONE as mFileNum in missiledata. } missile_graphic_id; typedef enum _mai_id { AI_ZOMBIE = 0, AI_FAT = 1, AI_SKELSD = 2, AI_SKELBOW = 3, AI_SCAV = 4, AI_RHINO = 5, AI_GOATMC = 6, AI_GOATBOW = 7, AI_FALLEN = 8, AI_MAGMA = 9, AI_SKELKING = 10, AI_BAT = 11, AI_GARG = 12, AI_CLEAVER = 13, AI_SUCC = 14, AI_SNEAK = 15, AI_STORM = 16, AI_FIREMAN = 17, AI_GARBUD = 18, AI_ACID = 19, AI_ACIDUNIQ = 20, AI_GOLUM = 21, AI_ZHAR = 22, AI_SNOTSPIL = 23, AI_SNAKE = 24, AI_COUNSLR = 25, AI_MEGA = 26, AI_DIABLO = 27, AI_LAZURUS = 28, AI_LAZHELP = 29, AI_LACHDAN = 30, AI_WARLORD = 31, } _mai_id; typedef enum _mc_id { MC_UNDEAD = 0, MC_DEMON = 1, MC_ANIMAL = 2, } _mc_id; typedef enum FILE_SYSTEM { FS_PC = 0, FS_CD = 1, } FILE_SYSTEM; typedef enum _artfonts { AF_SMALL = 0, AF_SMALLGRAY = 1, AF_MED = 2, AF_MEDGRAY = 3, AF_BIG = 4, AF_BIGGRAY = 5, AF_HUGE = 6, AF_HUGEGRAY = 7, } _artfonts; typedef enum _monster_id { MT_NZOMBIE = 0x0, MT_BZOMBIE = 0x1, MT_GZOMBIE = 0x2, MT_YZOMBIE = 0x3, MT_RFALLSP = 0x4, MT_DFALLSP = 0x5, MT_YFALLSP = 0x6, MT_BFALLSP = 0x7, MT_WSKELAX = 0x8, MT_TSKELAX = 0x9, MT_RSKELAX = 0xA, MT_XSKELAX = 0xB, MT_RFALLSD = 0xC, MT_DFALLSD = 0xD, MT_YFALLSD = 0xE, MT_BFALLSD = 0xF, MT_NSCAV = 0x10, MT_BSCAV = 0x11, MT_WSCAV = 0x12, MT_YSCAV = 0x13, MT_WSKELBW = 0x14, MT_TSKELBW = 0x15, MT_RSKELBW = 0x16, MT_XSKELBW = 0x17, MT_WSKELSD = 0x18, MT_TSKELSD = 0x19, MT_RSKELSD = 0x1A, MT_XSKELSD = 0x1B, MT_INVILORD = 0x1C, MT_SNEAK = 0x1D, MT_STALKER = 0x1E, MT_UNSEEN = 0x1F, MT_ILLWEAV = 0x20, MT_LRDSAYTR = 0x21, MT_NGOATMC = 0x22, MT_BGOATMC = 0x23, MT_RGOATMC = 0x24, MT_GGOATMC = 0x25, MT_FIEND = 0x26, MT_BLINK = 0x27, MT_GLOOM = 0x28, MT_FAMILIAR = 0x29, MT_NGOATBW = 0x2A, MT_BGOATBW = 0x2B, MT_RGOATBW = 0x2C, MT_GGOATBW = 0x2D, MT_NACID = 0x2E, MT_RACID = 0x2F, MT_BACID = 0x30, MT_XACID = 0x31, MT_SKING = 0x32, MT_CLEAVER = 0x33, MT_FAT = 0x34, MT_MUDMAN = 0x35, MT_TOAD = 0x36, MT_FLAYED = 0x37, MT_WYRM = 0x38, MT_CAVSLUG = 0x39, MT_DVLWYRM = 0x3A, MT_DEVOUR = 0x3B, MT_NMAGMA = 0x3C, MT_YMAGMA = 0x3D, MT_BMAGMA = 0x3E, MT_WMAGMA = 0x3F, MT_HORNED = 0x40, MT_MUDRUN = 0x41, MT_FROSTC = 0x42, MT_OBLORD = 0x43, MT_BONEDMN = 0x44, MT_REDDTH = 0x45, MT_LTCHDMN = 0x46, MT_UDEDBLRG = 0x47, MT_INCIN = 0x48, MT_FLAMLRD = 0x49, MT_DOOMFIRE = 0x4A, MT_HELLBURN = 0x4B, MT_STORM = 0x4C, MT_RSTORM = 0x4D, MT_STORML = 0x4E, MT_MAEL = 0x4F, MT_BIGFALL = 0x50, MT_WINGED = 0x51, MT_GARGOYLE = 0x52, MT_BLOODCLW = 0x53, MT_DEATHW = 0x54, MT_MEGA = 0x55, MT_GUARD = 0x56, MT_VTEXLRD = 0x57, MT_BALROG = 0x58, MT_NSNAKE = 0x59, MT_RSNAKE = 0x5A, MT_BSNAKE = 0x5B, MT_GSNAKE = 0x5C, MT_NBLACK = 0x5D, MT_RTBLACK = 0x5E, MT_BTBLACK = 0x5F, MT_RBLACK = 0x60, MT_UNRAV = 0x61, MT_HOLOWONE = 0x62, MT_PAINMSTR = 0x63, MT_REALWEAV = 0x64, MT_SUCCUBUS = 0x65, MT_SNOWWICH = 0x66, MT_HLSPWN = 0x67, MT_SOLBRNR = 0x68, MT_COUNSLR = 0x69, MT_MAGISTR = 0x6A, MT_CABALIST = 0x6B, MT_ADVOCATE = 0x6C, MT_GOLEM = 0x6D, MT_DIABLO = 0x6E, MT_DARKMAGE = 0x6F, NUM_MTYPES = 0x6F, /// BUGFIX the count is off by one } _monster_id; // this enum contains indexes from UniqMonst array for special unique monsters (usually quest related) typedef enum { UMT_GARBUD = 0, UMT_SKELKING = 1, UMT_ZHAR = 2, UMT_SNOTSPIL = 3, UMT_LAZURUS = 4, UMT_RED_VEX = 5, UMT_BLACKJADE = 6, UMT_LACHDAN = 7, UMT_WARLORD = 8, UMT_BUTCHER = 9, } _uniq_monsterid; typedef enum monster_flag { MFLAG_HIDDEN = 0x01, MFLAG_LOCK_ANIMATION = 0x02, MFLAG_ALLOW_SPECIAL = 0x04, MFLAG_NOHEAL = 0x08, MFLAG_TARGETS_MONSTER = 0x10, MFLAG_GOLEM = 0x20, MFLAG_QUEST_COMPLETE = 0x40, MFLAG_KNOCKBACK = 0x80, MFLAG_SEARCH = 0x100, MFLAG_CAN_OPEN_DOOR = 0x200, MFLAG_NO_ENEMY = 0x400, MFLAG_UNUSED = 0x800, MFLAG_NOLIFESTEAL = 0x1000 } monster_flag; typedef enum monster_goal { MGOAL_NORMAL = 1, MGOAL_RETREAT = 2, MGOAL_HEALING = 3, MGOAL_MOVE = 4, MGOAL_SHOOT = 5, MGOAL_INQUIRING = 6, MGOAL_TALKING = 7, } monster_goal; typedef enum monster_resistance { RESIST_MAGIC = 0x01, RESIST_FIRE = 0x02, RESIST_LIGHTNING = 0x04, IMUNE_MAGIC = 0x08, IMUNE_FIRE = 0x10, IMUNE_LIGHTNING = 0x20, IMUNE_NULL_40 = 0x40, IMUNE_ACID = 0x80, } monster_resistance; typedef enum missile_resistance { MISR_FIRE = 1, MISR_LIGHTNING = 2, MISR_MAGIC = 3, MISR_ACID = 4, } missile_resistance; typedef enum _speech_id { TEXT_KING1 = 0x0, TEXT_KING2 = 0x1, TEXT_KING3 = 0x2, TEXT_KING4 = 0x3, TEXT_KING5 = 0x4, TEXT_KING6 = 0x5, TEXT_KING7 = 0x6, TEXT_KING8 = 0x7, TEXT_KING9 = 0x8, TEXT_KING10 = 0x9, TEXT_KING11 = 0xA, TEXT_BANNER1 = 0xB, TEXT_BANNER2 = 0xC, TEXT_BANNER3 = 0xD, TEXT_BANNER4 = 0xE, TEXT_BANNER5 = 0xF, TEXT_BANNER6 = 0x10, TEXT_BANNER7 = 0x11, TEXT_BANNER8 = 0x12, TEXT_BANNER9 = 0x13, TEXT_BANNER10 = 0x14, TEXT_BANNER11 = 0x15, TEXT_BANNER12 = 0x16, TEXT_VILE1 = 0x17, TEXT_VILE2 = 0x18, TEXT_VILE3 = 0x19, TEXT_VILE4 = 0x1A, TEXT_VILE5 = 0x1B, TEXT_VILE6 = 0x1C, TEXT_VILE7 = 0x1D, TEXT_VILE8 = 0x1E, TEXT_VILE9 = 0x1F, TEXT_VILE10 = 0x20, TEXT_VILE11 = 0x21, TEXT_VILE12 = 0x22, TEXT_VILE13 = 0x23, TEXT_VILE14 = 0x24, TEXT_POISON1 = 0x25, TEXT_POISON2 = 0x26, TEXT_POISON3 = 0x27, TEXT_POISON4 = 0x28, TEXT_POISON5 = 0x29, TEXT_POISON6 = 0x2A, TEXT_POISON7 = 0x2B, TEXT_POISON8 = 0x2C, TEXT_POISON9 = 0x2D, TEXT_POISON10 = 0x2E, TEXT_BONE1 = 0x2F, TEXT_BONE2 = 0x30, TEXT_BONE3 = 0x31, TEXT_BONE4 = 0x32, TEXT_BONE5 = 0x33, TEXT_BONE6 = 0x34, TEXT_BONE7 = 0x35, TEXT_BONE8 = 0x36, TEXT_BUTCH1 = 0x37, TEXT_BUTCH2 = 0x38, TEXT_BUTCH3 = 0x39, TEXT_BUTCH4 = 0x3A, TEXT_BUTCH5 = 0x3B, TEXT_BUTCH6 = 0x3C, TEXT_BUTCH7 = 0x3D, TEXT_BUTCH8 = 0x3E, TEXT_BUTCH9 = 0x3F, TEXT_BUTCH10 = 0x40, TEXT_BLIND1 = 0x41, TEXT_BLIND2 = 0x42, TEXT_BLIND3 = 0x43, TEXT_BLIND4 = 0x44, TEXT_BLIND5 = 0x45, TEXT_BLIND6 = 0x46, TEXT_BLIND7 = 0x47, TEXT_BLIND8 = 0x48, TEXT_VEIL1 = 0x49, TEXT_VEIL2 = 0x4A, TEXT_VEIL3 = 0x4B, TEXT_VEIL4 = 0x4C, TEXT_VEIL5 = 0x4D, TEXT_VEIL6 = 0x4E, TEXT_VEIL7 = 0x4F, TEXT_VEIL8 = 0x50, TEXT_VEIL9 = 0x51, TEXT_VEIL10 = 0x52, TEXT_VEIL11 = 0x53, TEXT_ANVIL1 = 0x54, TEXT_ANVIL2 = 0x55, TEXT_ANVIL3 = 0x56, TEXT_ANVIL4 = 0x57, TEXT_ANVIL5 = 0x58, TEXT_ANVIL6 = 0x59, TEXT_ANVIL7 = 0x5A, TEXT_ANVIL8 = 0x5B, TEXT_ANVIL9 = 0x5C, TEXT_ANVIL10 = 0x5D, TEXT_BLOOD1 = 0x5E, TEXT_BLOOD2 = 0x5F, TEXT_BLOOD3 = 0x60, TEXT_BLOOD4 = 0x61, TEXT_BLOOD5 = 0x62, TEXT_BLOOD6 = 0x63, TEXT_BLOOD7 = 0x64, TEXT_BLOOD8 = 0x65, TEXT_WARLRD1 = 0x66, TEXT_WARLRD2 = 0x67, TEXT_WARLRD3 = 0x68, TEXT_WARLRD4 = 0x69, TEXT_WARLRD5 = 0x6A, TEXT_WARLRD6 = 0x6B, TEXT_WARLRD7 = 0x6C, TEXT_WARLRD8 = 0x6D, TEXT_WARLRD9 = 0x6E, TEXT_INFRA1 = 0x6F, TEXT_INFRA2 = 0x70, TEXT_INFRA3 = 0x71, TEXT_INFRA4 = 0x72, TEXT_INFRA5 = 0x73, TEXT_INFRA6 = 0x74, TEXT_INFRA7 = 0x75, TEXT_INFRA8 = 0x76, TEXT_INFRA9 = 0x77, TEXT_INFRA10 = 0x78, TEXT_MUSH1 = 0x79, TEXT_MUSH2 = 0x7A, TEXT_MUSH3 = 0x7B, TEXT_MUSH4 = 0x7C, TEXT_MUSH5 = 0x7D, TEXT_MUSH6 = 0x7E, TEXT_MUSH7 = 0x7F, TEXT_MUSH8 = 0x80, TEXT_MUSH9 = 0x81, TEXT_MUSH10 = 0x82, TEXT_MUSH11 = 0x83, TEXT_MUSH12 = 0x84, TEXT_MUSH13 = 0x85, TEXT_DOOM1 = 0x86, TEXT_DOOM2 = 0x87, TEXT_DOOM3 = 0x88, TEXT_DOOM4 = 0x89, TEXT_DOOM5 = 0x8A, TEXT_DOOM6 = 0x8B, TEXT_DOOM7 = 0x8C, TEXT_DOOM8 = 0x8D, TEXT_DOOM9 = 0x8E, TEXT_DOOM10 = 0x8F, TEXT_GARBUD1 = 0x90, TEXT_GARBUD2 = 0x91, TEXT_GARBUD3 = 0x92, TEXT_GARBUD4 = 0x93, TEXT_ZHAR1 = 0x94, TEXT_ZHAR2 = 0x95, TEXT_STORY1 = 0x96, TEXT_STORY2 = 0x97, TEXT_STORY3 = 0x98, TEXT_STORY4 = 0x99, TEXT_STORY5 = 0x9A, TEXT_STORY6 = 0x9B, TEXT_STORY7 = 0x9C, TEXT_STORY9 = 0x9D, TEXT_STORY10 = 0x9E, TEXT_STORY11 = 0x9F, TEXT_OGDEN1 = 0xA0, TEXT_OGDEN2 = 0xA1, TEXT_OGDEN3 = 0xA2, TEXT_OGDEN4 = 0xA3, TEXT_OGDEN5 = 0xA4, TEXT_OGDEN6 = 0xA5, TEXT_OGDEN8 = 0xA6, TEXT_OGDEN9 = 0xA7, TEXT_OGDEN10 = 0xA8, TEXT_PEPIN1 = 0xA9, TEXT_PEPIN2 = 0xAA, TEXT_PEPIN3 = 0xAB, TEXT_PEPIN4 = 0xAC, TEXT_PEPIN5 = 0xAD, TEXT_PEPIN6 = 0xAE, TEXT_PEPIN7 = 0xAF, TEXT_PEPIN9 = 0xB0, TEXT_PEPIN10 = 0xB1, TEXT_PEPIN11 = 0xB2, TEXT_GILLIAN1 = 0xB3, TEXT_GILLIAN2 = 0xB4, TEXT_GILLIAN3 = 0xB5, TEXT_GILLIAN4 = 0xB6, TEXT_GILLIAN5 = 0xB7, TEXT_GILLIAN6 = 0xB8, TEXT_GILLIAN7 = 0xB9, TEXT_GILLIAN9 = 0xBA, TEXT_GILLIAN10 = 0xBB, TEXT_GRISWOLD1 = 0xBC, TEXT_GRISWOLD2 = 0xBD, TEXT_GRISWOLD3 = 0xBE, TEXT_GRISWOLD4 = 0xBF, TEXT_GRISWOLD5 = 0xC0, TEXT_GRISWOLD6 = 0xC1, TEXT_GRISWOLD7 = 0xC2, TEXT_GRISWOLD8 = 0xC3, TEXT_GRISWOLD9 = 0xC4, TEXT_GRISWOLD10 = 0xC5, TEXT_GRISWOLD12 = 0xC6, TEXT_GRISWOLD13 = 0xC7, TEXT_FARNHAM1 = 0xC8, TEXT_FARNHAM2 = 0xC9, TEXT_FARNHAM3 = 0xCA, TEXT_FARNHAM4 = 0xCB, TEXT_FARNHAM5 = 0xCC, TEXT_FARNHAM6 = 0xCD, TEXT_FARNHAM8 = 0xCE, TEXT_FARNHAM9 = 0xCF, TEXT_FARNHAM10 = 0xD0, TEXT_FARNHAM11 = 0xD1, TEXT_FARNHAM12 = 0xD2, TEXT_FARNHAM13 = 0xD3, TEXT_ADRIA1 = 0xD4, TEXT_ADRIA2 = 0xD5, TEXT_ADRIA3 = 0xD6, TEXT_ADRIA4 = 0xD7, TEXT_ADRIA5 = 0xD8, TEXT_ADRIA6 = 0xD9, TEXT_ADRIA7 = 0xDA, TEXT_ADRIA8 = 0xDB, TEXT_ADRIA9 = 0xDC, TEXT_ADRIA10 = 0xDD, TEXT_ADRIA12 = 0xDE, TEXT_ADRIA13 = 0xDF, TEXT_WIRT1 = 0xE0, TEXT_WIRT2 = 0xE1, TEXT_WIRT3 = 0xE2, TEXT_WIRT4 = 0xE3, TEXT_WIRT5 = 0xE4, TEXT_WIRT6 = 0xE5, TEXT_WIRT7 = 0xE6, TEXT_WIRT8 = 0xE7, TEXT_WIRT9 = 0xE8, TEXT_WIRT11 = 0xE9, TEXT_WIRT12 = 0xEA, TEXT_BONER = 0xEB, TEXT_BLOODY = 0xEC, TEXT_BLINDING = 0xED, TEXT_BLOODWAR = 0xEE, TEXT_MBONER = 0xEF, TEXT_MBLOODY = 0xF0, TEXT_MBLINDING = 0xF1, TEXT_MBLOODWAR = 0xF2, TEXT_RBONER = 0xF3, TEXT_RBLOODY = 0xF4, TEXT_RBLINDING = 0xF5, TEXT_RBLOODWAR = 0xF6, TEXT_COW1 = 0xF7, TEXT_COW2 = 0xF8, TEXT_BOOK11 = 0xF9, TEXT_BOOK12 = 0xFA, TEXT_BOOK13 = 0xFB, TEXT_BOOK21 = 0xFC, TEXT_BOOK22 = 0xFD, TEXT_BOOK23 = 0xFE, TEXT_BOOK31 = 0xFF, TEXT_BOOK32 = 0x100, TEXT_BOOK33 = 0x101, TEXT_INTRO = 0x102, } _speech_id; typedef enum object_graphic_id { OFILE_L1BRAZ = 0x0, OFILE_L1DOORS = 0x1, OFILE_LEVER = 0x2, OFILE_CHEST1 = 0x3, OFILE_CHEST2 = 0x4, OFILE_BANNER = 0x5, OFILE_SKULPILE = 0x6, OFILE_SKULFIRE = 0x7, OFILE_SKULSTIK = 0x8, OFILE_CRUXSK1 = 0x9, OFILE_CRUXSK2 = 0xA, OFILE_CRUXSK3 = 0xB, OFILE_BOOK1 = 0xC, OFILE_BOOK2 = 0xD, OFILE_ROCKSTAN = 0xE, OFILE_ANGEL = 0xF, OFILE_CHEST3 = 0x10, OFILE_BURNCROS = 0x11, OFILE_CANDLE2 = 0x12, OFILE_NUDE2 = 0x13, OFILE_SWITCH4 = 0x14, OFILE_TNUDEM = 0x15, OFILE_TNUDEW = 0x16, OFILE_TSOUL = 0x17, OFILE_L2DOORS = 0x18, OFILE_WTORCH4 = 0x19, OFILE_WTORCH3 = 0x1A, OFILE_SARC = 0x1B, OFILE_FLAME1 = 0x1C, OFILE_PRSRPLT1 = 0x1D, OFILE_TRAPHOLE = 0x1E, OFILE_MINIWATR = 0x1F, OFILE_WTORCH2 = 0x20, OFILE_WTORCH1 = 0x21, OFILE_BCASE = 0x22, OFILE_BSHELF = 0x23, OFILE_WEAPSTND = 0x24, OFILE_BARREL = 0x25, OFILE_BARRELEX = 0x26, OFILE_LSHRINEG = 0x27, OFILE_RSHRINEG = 0x28, OFILE_BLOODFNT = 0x29, OFILE_DECAP = 0x2A, OFILE_PEDISTL = 0x2B, OFILE_L3DOORS = 0x2C, OFILE_PFOUNTN = 0x2D, OFILE_ARMSTAND = 0x2E, OFILE_GOATSHRN = 0x2F, OFILE_CAULDREN = 0x30, OFILE_MFOUNTN = 0x31, OFILE_TFOUNTN = 0x32, OFILE_ALTBOY = 0x33, OFILE_MCIRL = 0x34, OFILE_BKSLBRNT = 0x35, OFILE_MUSHPTCH = 0x36, OFILE_LZSTAND = 0x37, } object_graphic_id; typedef enum dungeon_type { DTYPE_TOWN = 0x0, DTYPE_CATHEDRAL = 0x1, DTYPE_CATACOMBS = 0x2, DTYPE_CAVES = 0x3, DTYPE_HELL = 0x4, DTYPE_NONE = 0xFF, } dungeon_type; typedef enum dflag { BFLAG_MISSILE = 0x01, BFLAG_VISIBLE = 0x02, BFLAG_DEAD_PLAYER = 0x04, BFLAG_POPULATED = 0x08, BFLAG_MONSTLR = 0x10, BFLAG_PLAYERLR = 0x20, BFLAG_LIT = 0x40, BFLAG_EXPLORED = 0x80, } dflag; /* First 5 bits store level 6th bit stores onlygood flag 7th bit stores uper15 flag - uper means unique percent, this flag is true for unique monsters and loot from them has 15% to become unique 8th bit stores uper1 flag - this is loot from normal monsters, which has 1% to become unique 9th bit stores info if item is unique 10th bit stores info if item is a basic one from griswold 11th bit stores info if item is a premium one from griswold 12th bit stores info if item is from wirt 13th bit stores info if item is from adria 14th bit stores info if item is from pepin 15th bit stores pregen flag combining CF_UPER15 and CF_UPER1 flags (CF_USEFUL) is used to mark potions and town portal scrolls created on the ground CF_TOWN is combining all store flags and indicates if item has been bought from a NPC */ typedef enum icreateinfo_flag { CF_LEVEL = (1 << 6) - 1, CF_ONLYGOOD = 1 << 6, CF_UPER15 = 1 << 7, CF_UPER1 = 1 << 8, CF_UNIQUE = 1 << 9, CF_SMITH = 1 << 10, CF_SMITHPREMIUM = 1 << 11, CF_BOY = 1 << 12, CF_WITCH = 1 << 13, CF_HEALER = 1 << 14, CF_PREGEN = 1 << 15, CF_USEFUL = CF_UPER15 | CF_UPER1, CF_TOWN = CF_SMITH | CF_SMITHPREMIUM | CF_BOY | CF_WITCH | CF_HEALER, } icreateinfo_flag; typedef enum dungeon_message { DMSG_CATHEDRAL = 1 << 0, DMSG_CATACOMBS = 1 << 1, DMSG_CAVES = 1 << 2, DMSG_HELL = 1 << 3, DMSG_DIABLO = 1 << 4, } dungeon_message; typedef enum diablo_message { EMSG_NONE = 0, EMSG_NO_AUTOMAP_IN_TOWN = 1, EMSG_NO_MULTIPLAYER_IN_DEMO = 2, EMSG_DIRECT_SOUND_FAILED = 3, EMSG_NOT_IN_SHAREWARE = 4, EMSG_NO_SPACE_TO_SAVE = 5, EMSG_NO_PAUSE_IN_TOWN = 6, EMSG_COPY_TO_HDD = 7, EMSG_DESYNC = 8, EMSG_NO_PAUSE_IN_MP = 9, EMSG_LOADING = 10, EMSG_SAVING = 11, EMSG_SHRINE_MYSTERIOUS = 12, EMSG_SHRINE_HIDDEN = 13, EMSG_SHRINE_GLOOMY = 14, EMSG_SHRINE_WEIRD = 15, EMSG_SHRINE_MAGICAL = 16, EMSG_SHRINE_STONE = 17, EMSG_SHRINE_RELIGIOUS = 18, EMSG_SHRINE_ENCHANTED = 19, EMSG_SHRINE_THAUMATURGIC = 20, EMSG_SHRINE_FASCINATING = 21, EMSG_SHRINE_CRYPTIC = 22, EMSG_SHRINE_UNUSED = 23, EMSG_SHRINE_ELDRITCH = 24, EMSG_SHRINE_EERIE = 25, EMSG_SHRINE_DIVINE = 26, EMSG_SHRINE_HOLY = 27, EMSG_SHRINE_SACRED = 28, EMSG_SHRINE_SPIRITUAL = 29, EMSG_SHRINE_SPOOKY1 = 30, EMSG_SHRINE_SPOOKY2 = 31, EMSG_SHRINE_ABANDONED = 32, EMSG_SHRINE_CREEPY = 33, EMSG_SHRINE_QUIET = 34, EMSG_SHRINE_SECLUDED = 35, EMSG_SHRINE_ORNATE = 36, EMSG_SHRINE_GLIMMERING = 37, EMSG_SHRINE_TAINTED1 = 38, EMSG_SHRINE_TAINTED2 = 39, EMSG_REQUIRES_LVL_8 = 40, EMSG_REQUIRES_LVL_13 = 41, EMSG_REQUIRES_LVL_17 = 42, EMSG_BONECHAMB = 43, } diablo_message; typedef enum magic_type { STYPE_FIRE = 0x0, STYPE_LIGHTNING = 0x1, STYPE_MAGIC = 0x2, } magic_type; typedef enum theme_id { THEME_BARREL = 0x0, THEME_SHRINE = 0x1, THEME_MONSTPIT = 0x2, THEME_SKELROOM = 0x3, THEME_TREASURE = 0x4, THEME_LIBRARY = 0x5, THEME_TORTURE = 0x6, THEME_BLOODFOUNTAIN = 0x7, THEME_DECAPITATED = 0x8, THEME_PURIFYINGFOUNTAIN = 0x9, THEME_ARMORSTAND = 0xA, THEME_GOATSHRINE = 0xB, THEME_CAULDRON = 0xC, THEME_MURKYFOUNTAIN = 0xD, THEME_TEARFOUNTAIN = 0xE, THEME_BRNCROSS = 0xF, THEME_WEAPONRACK = 0x10, THEME_NONE = -1, } theme_id; typedef enum event_type { EVENT_TYPE_PLAYER_CREATE_GAME = 1, EVENT_TYPE_2 = 2, EVENT_TYPE_PLAYER_LEAVE_GAME = 3, EVENT_TYPE_PLAYER_MESSAGE = 4, EVENT_TYPE_5 = 5, EVENT_TYPE_6 = 6, EVENT_TYPE_7 = 7, EVENT_TYPE_8 = 8, EVENT_TYPE_9 = 9, EVENT_TYPE_10 = 10, EVENT_TYPE_11 = 11, EVENT_TYPE_12 = 12, EVENT_TYPE_13 = 13, EVENT_TYPE_14 = 14, EVENT_TYPE_15 = 15, } event_type; typedef enum _copyprot_results { COPYPROT_OK = 1, COPYPROT_CANCEL = 2, } _copyprot_results; typedef enum text_color { COL_WHITE = 0x0, COL_BLUE = 0x1, COL_RED = 0x2, COL_GOLD = 0x3, } text_color; typedef enum item_color { ICOL_WHITE = PAL16_YELLOW + 5, ICOL_BLUE = PAL16_BLUE + 5, ICOL_RED = PAL16_RED + 5, } item_color; typedef enum _difficulty { DIFF_NORMAL = 0x0, DIFF_NIGHTMARE = 0x1, DIFF_HELL = 0x2, NUM_DIFFICULTIES = 0x3, } _difficulty; typedef enum MON_MODE { MM_STAND = 0, MM_WALK = 1, MM_WALK2 = 2, MM_WALK3 = 3, MM_ATTACK = 4, MM_GOTHIT = 5, MM_DEATH = 6, MM_SATTACK = 7, MM_FADEIN = 8, MM_FADEOUT = 9, MM_RATTACK = 10, MM_SPSTAND = 11, MM_RSPATTACK = 12, MM_DELAY = 13, MM_CHARGE = 14, MM_STONE = 15, MM_HEAL = 16, MM_TALK = 17, } MON_MODE; typedef enum MON_ANIM { MA_STAND = 0, MA_WALK = 1, MA_ATTACK = 2, MA_GOTHIT = 3, MA_DEATH = 4, MA_SPECIAL = 5, } MON_ANIM; typedef enum PLR_MODE { PM_STAND = 0, PM_WALK = 1, PM_WALK2 = 2, PM_WALK3 = 3, PM_ATTACK = 4, PM_RATTACK = 5, PM_BLOCK = 6, PM_GOTHIT = 7, PM_DEATH = 8, PM_SPELL = 9, PM_NEWLVL = 10, PM_QUIT = 11, } PLR_MODE; typedef enum spell_type { RSPLTYPE_SKILL = 0x0, RSPLTYPE_SPELL = 0x1, RSPLTYPE_SCROLL = 0x2, RSPLTYPE_CHARGES = 0x3, RSPLTYPE_INVALID = 0x4, } spell_type; typedef enum cursor_id { CURSOR_NONE = 0x0, CURSOR_HAND = 0x1, CURSOR_IDENTIFY = 0x2, CURSOR_REPAIR = 0x3, CURSOR_RECHARGE = 0x4, CURSOR_DISARM = 0x5, CURSOR_OIL = 0x6, CURSOR_TELEKINESIS = 0x7, CURSOR_RESURRECT = 0x8, CURSOR_TELEPORT = 0x9, CURSOR_HEALOTHER = 0xA, CURSOR_HOURGLASS = 0xB, CURSOR_FIRSTITEM = 0xC, } cursor_id; typedef enum direction { DIR_S = 0x0, DIR_SW = 0x1, DIR_W = 0x2, DIR_NW = 0x3, DIR_N = 0x4, DIR_NE = 0x5, DIR_E = 0x6, DIR_SE = 0x7, DIR_OMNI = 0x8, } direction; typedef enum _scroll_direction { SDIR_NONE = 0x0, SDIR_N = 0x1, SDIR_NE = 0x2, SDIR_E = 0x3, SDIR_SE = 0x4, SDIR_S = 0x5, SDIR_SW = 0x6, SDIR_W = 0x7, SDIR_NW = 0x8, } _scroll_direction; typedef enum interface_mode { WM_DIABNEXTLVL = 0x402, // WM_USER+2 WM_DIABPREVLVL = 0x403, WM_DIABRTNLVL = 0x404, WM_DIABSETLVL = 0x405, WM_DIABWARPLVL = 0x406, WM_DIABTOWNWARP = 0x407, WM_DIABTWARPUP = 0x408, WM_DIABRETOWN = 0x409, WM_DIABNEWGAME = 0x40A, WM_DIABLOADGAME = 0x40B // WM_LEIGHSKIP = 0x40C, // psx only // WM_DIAVNEWLVL = 0x40D, // psx only } interface_mode; typedef enum game_info { GAMEINFO_NAME = 1, GAMEINFO_PASSWORD = 2, GAMEINFO_STATS = 3, GAMEINFO_MODEFLAG = 4, GAMEINFO_GAMETEMPLATE = 5, GAMEINFO_PLAYERS = 6, } game_info; typedef enum spell_id { SPL_NULL = 0x0, SPL_FIREBOLT = 0x1, SPL_HEAL = 0x2, SPL_LIGHTNING = 0x3, SPL_FLASH = 0x4, SPL_IDENTIFY = 0x5, SPL_FIREWALL = 0x6, SPL_TOWN = 0x7, SPL_STONE = 0x8, SPL_INFRA = 0x9, SPL_RNDTELEPORT = 0xA, SPL_MANASHIELD = 0xB, SPL_FIREBALL = 0xC, SPL_GUARDIAN = 0xD, SPL_CHAIN = 0xE, SPL_WAVE = 0xF, SPL_DOOMSERP = 0x10, SPL_BLODRIT = 0x11, SPL_NOVA = 0x12, SPL_INVISIBIL = 0x13, SPL_FLAME = 0x14, SPL_GOLEM = 0x15, SPL_BLODBOIL = 0x16, SPL_TELEPORT = 0x17, SPL_APOCA = 0x18, SPL_ETHEREALIZE = 0x19, SPL_REPAIR = 0x1A, SPL_RECHARGE = 0x1B, SPL_DISARM = 0x1C, SPL_ELEMENT = 0x1D, SPL_CBOLT = 0x1E, SPL_HBOLT = 0x1F, SPL_RESURRECT = 0x20, SPL_TELEKINESIS = 0x21, SPL_HEALOTHER = 0x22, SPL_FLARE = 0x23, SPL_BONESPIRIT = 0x24, SPL_INVALID = -1, } spell_id; typedef enum _cmd_id { CMD_STAND, CMD_WALKXY, CMD_ACK_PLRINFO, CMD_ADDSTR, CMD_ADDMAG, CMD_ADDDEX, CMD_ADDVIT, CMD_SBSPELL, CMD_GETITEM, CMD_AGETITEM, CMD_PUTITEM, CMD_RESPAWNITEM, CMD_ATTACKXY, CMD_RATTACKXY, CMD_SPELLXY, CMD_TSPELLXY, CMD_OPOBJXY, CMD_DISARMXY, CMD_ATTACKID, CMD_ATTACKPID, CMD_RATTACKID, CMD_RATTACKPID, CMD_SPELLID, CMD_SPELLPID, CMD_TSPELLID, CMD_TSPELLPID, CMD_RESURRECT, CMD_OPOBJT, CMD_KNOCKBACK, CMD_TALKXY, CMD_NEWLVL, CMD_WARP, CMD_CHEAT_EXPERIENCE, CMD_CHEAT_SPELL_LEVEL, CMD_DEBUG, CMD_SYNCDATA, CMD_MONSTDEATH, CMD_MONSTDAMAGE, CMD_PLRDEAD, CMD_REQUESTGITEM, CMD_REQUESTAGITEM, CMD_GOTOGETITEM, CMD_GOTOAGETITEM, CMD_OPENDOOR, CMD_CLOSEDOOR, CMD_OPERATEOBJ, CMD_PLROPOBJ, CMD_BREAKOBJ, CMD_CHANGEPLRITEMS, CMD_DELPLRITEMS, CMD_PLRDAMAGE, CMD_PLRLEVEL, CMD_DROPITEM, CMD_PLAYER_JOINLEVEL, CMD_SEND_PLRINFO, CMD_SATTACKXY, CMD_ACTIVATEPORTAL, CMD_DEACTIVATEPORTAL, CMD_DLEVEL_0, CMD_DLEVEL_1, CMD_DLEVEL_2, CMD_DLEVEL_3, CMD_DLEVEL_4, CMD_DLEVEL_5, CMD_DLEVEL_6, CMD_DLEVEL_7, CMD_DLEVEL_8, CMD_DLEVEL_9, CMD_DLEVEL_10, CMD_DLEVEL_11, CMD_DLEVEL_12, CMD_DLEVEL_13, CMD_DLEVEL_14, CMD_DLEVEL_15, CMD_DLEVEL_16, CMD_DLEVEL_JUNK, CMD_DLEVEL_END, CMD_HEALOTHER, CMD_STRING, CMD_SETSTR, CMD_SETMAG, CMD_SETDEX, CMD_SETVIT, CMD_RETOWN, CMD_SPELLXYD, CMD_ITEMEXTRA, CMD_SYNCPUTITEM, CMD_KILLGOLEM, CMD_SYNCQUEST, CMD_ENDSHIELD, CMD_AWAKEGOLEM, CMD_NOVA, CMD_SETSHIELD, CMD_REMSHIELD, FAKE_CMD_SETID, FAKE_CMD_DROPID, NUM_CMDS, } _cmd_id; typedef enum _talker_id { TOWN_SMITH = 0x0, TOWN_HEALER = 0x1, TOWN_DEADGUY = 0x2, TOWN_TAVERN = 0x3, TOWN_STORY = 0x4, TOWN_DRUNK = 0x5, TOWN_WITCH = 0x6, TOWN_BMAID = 0x7, TOWN_PEGBOY = 0x8, TOWN_COW = 0x9, TOWN_PRIEST = 0xA, } _talker_id; typedef enum _music_id { TMUSIC_TOWN, TMUSIC_L1, TMUSIC_L2, TMUSIC_L3, TMUSIC_L4, TMUSIC_INTRO, NUM_MUSIC, } _music_id; typedef enum _mainmenu_selections { MAINMENU_SINGLE_PLAYER = 1, MAINMENU_MULTIPLAYER = 2, MAINMENU_REPLAY_INTRO = 3, MAINMENU_SHOW_CREDITS = 4, MAINMENU_EXIT_DIABLO = 5, MAINMENU_ATTRACT_MODE = 6, } _mainmenu_selections; typedef enum _selhero_selections { SELHERO_NEW_DUNGEON = 1, SELHERO_CONTINUE = 2, SELHERO_CONNECT = 3, SELHERO_PREVIOUS = 4 } _selhero_selections; typedef enum panel_button_id { PANBTN_CHARINFO = 0, PANBTN_QLOG = 1, PANBTN_AUTOMAP = 2, PANBTN_MAINMENU = 3, PANBTN_INVENTORY = 4, PANBTN_SPELLBOOK = 5, PANBTN_SENDMSG = 6, PANBTN_FRIENDLY = 7, } panel_button_id; typedef enum attribute_id { ATTRIB_STR = 0, ATTRIB_MAG = 1, ATTRIB_DEX = 2, ATTRIB_VIT = 3, } attribute_id; typedef enum _object_id { OBJ_L1LIGHT = 0x0, OBJ_L1LDOOR = 0x1, OBJ_L1RDOOR = 0x2, OBJ_SKFIRE = 0x3, OBJ_LEVER = 0x4, OBJ_CHEST1 = 0x5, OBJ_CHEST2 = 0x6, OBJ_CHEST3 = 0x7, OBJ_CANDLE1 = 0x8, OBJ_CANDLE2 = 0x9, OBJ_CANDLEO = 0xA, OBJ_BANNERL = 0xB, OBJ_BANNERM = 0xC, OBJ_BANNERR = 0xD, OBJ_SKPILE = 0xE, OBJ_SKSTICK1 = 0xF, OBJ_SKSTICK2 = 0x10, OBJ_SKSTICK3 = 0x11, OBJ_SKSTICK4 = 0x12, OBJ_SKSTICK5 = 0x13, OBJ_CRUX1 = 0x14, OBJ_CRUX2 = 0x15, OBJ_CRUX3 = 0x16, OBJ_STAND = 0x17, OBJ_ANGEL = 0x18, OBJ_BOOK2L = 0x19, OBJ_BCROSS = 0x1A, OBJ_NUDEW2R = 0x1B, OBJ_SWITCHSKL = 0x1C, OBJ_TNUDEM1 = 0x1D, OBJ_TNUDEM2 = 0x1E, OBJ_TNUDEM3 = 0x1F, OBJ_TNUDEM4 = 0x20, OBJ_TNUDEW1 = 0x21, OBJ_TNUDEW2 = 0x22, OBJ_TNUDEW3 = 0x23, OBJ_TORTURE1 = 0x24, OBJ_TORTURE2 = 0x25, OBJ_TORTURE3 = 0x26, OBJ_TORTURE4 = 0x27, OBJ_TORTURE5 = 0x28, OBJ_BOOK2R = 0x29, OBJ_L2LDOOR = 0x2A, OBJ_L2RDOOR = 0x2B, OBJ_TORCHL = 0x2C, OBJ_TORCHR = 0x2D, OBJ_TORCHL2 = 0x2E, OBJ_TORCHR2 = 0x2F, OBJ_SARC = 0x30, OBJ_FLAMEHOLE = 0x31, OBJ_FLAMELVR = 0x32, OBJ_WATER = 0x33, OBJ_BOOKLVR = 0x34, OBJ_TRAPL = 0x35, OBJ_TRAPR = 0x36, OBJ_BOOKSHELF = 0x37, OBJ_WEAPRACK = 0x38, OBJ_BARREL = 0x39, OBJ_BARRELEX = 0x3A, OBJ_SHRINEL = 0x3B, OBJ_SHRINER = 0x3C, OBJ_SKELBOOK = 0x3D, OBJ_BOOKCASEL = 0x3E, OBJ_BOOKCASER = 0x3F, OBJ_BOOKSTAND = 0x40, OBJ_BOOKCANDLE = 0x41, OBJ_BLOODFTN = 0x42, OBJ_DECAP = 0x43, OBJ_TCHEST1 = 0x44, OBJ_TCHEST2 = 0x45, OBJ_TCHEST3 = 0x46, OBJ_BLINDBOOK = 0x47, OBJ_BLOODBOOK = 0x48, OBJ_PEDISTAL = 0x49, OBJ_L3LDOOR = 0x4A, OBJ_L3RDOOR = 0x4B, OBJ_PURIFYINGFTN = 0x4C, OBJ_ARMORSTAND = 0x4D, OBJ_ARMORSTANDN = 0x4E, OBJ_GOATSHRINE = 0x4F, OBJ_CAULDRON = 0x50, OBJ_MURKYFTN = 0x51, OBJ_TEARFTN = 0x52, OBJ_ALTBOY = 0x53, OBJ_MCIRCLE1 = 0x54, OBJ_MCIRCLE2 = 0x55, OBJ_STORYBOOK = 0x56, OBJ_STORYCANDLE = 0x57, OBJ_STEELTOME = 0x58, OBJ_WARARMOR = 0x59, OBJ_WARWEAP = 0x5A, OBJ_TBCROSS = 0x5B, OBJ_WEAPONRACK = 0x5C, OBJ_WEAPONRACKN = 0x5D, OBJ_MUSHPATCH = 0x5E, OBJ_LAZSTAND = 0x5F, OBJ_SLAINHERO = 0x60, OBJ_SIGNCHEST = 0x61, OBJ_NULL_98 = 0x62, } _object_id; typedef enum item_misc_id { IMISC_NONE = 0x0, IMISC_USEFIRST = 0x1, IMISC_FULLHEAL = 0x2, IMISC_HEAL = 0x3, IMISC_OLDHEAL = 0x4, IMISC_DEADHEAL = 0x5, IMISC_MANA = 0x6, IMISC_FULLMANA = 0x7, IMISC_POTEXP = 0x8, /* add experience */ IMISC_POTFORG = 0x9, /* remove experience */ IMISC_ELIXSTR = 0xA, IMISC_ELIXMAG = 0xB, IMISC_ELIXDEX = 0xC, IMISC_ELIXVIT = 0xD, IMISC_ELIXWEAK = 0xE, /* double check with alpha */ IMISC_ELIXDIS = 0xF, IMISC_ELIXCLUM = 0x10, IMISC_ELIXSICK = 0x11, IMISC_REJUV = 0x12, IMISC_FULLREJUV = 0x13, IMISC_USELAST = 0x14, IMISC_SCROLL = 0x15, IMISC_SCROLLT = 0x16, IMISC_STAFF = 0x17, IMISC_BOOK = 0x18, IMISC_RING = 0x19, IMISC_AMULET = 0x1A, IMISC_UNIQUE = 0x1B, IMISC_MEAT = 0x1C, /* from demo/PSX */ IMISC_OILFIRST = 0x1D, IMISC_OILOF = 0x1E, /* oils are beta or hellfire only */ IMISC_OILACC = 0x1F, IMISC_OILMAST = 0x20, IMISC_OILSHARP = 0x21, IMISC_OILDEATH = 0x22, IMISC_OILSKILL = 0x23, IMISC_OILBSMTH = 0x24, IMISC_OILFORT = 0x25, IMISC_OILPERM = 0x26, IMISC_OILHARD = 0x27, IMISC_OILIMP = 0x28, IMISC_OILLAST = 0x29, IMISC_MAPOFDOOM = 0x2A, IMISC_EAR = 0x2B, IMISC_SPECELIX = 0x2C, IMISC_INVALID = -1, } item_misc_id; typedef enum item_type { ITYPE_MISC = 0x0, ITYPE_SWORD = 0x1, ITYPE_AXE = 0x2, ITYPE_BOW = 0x3, ITYPE_MACE = 0x4, ITYPE_SHIELD = 0x5, ITYPE_LARMOR = 0x6, ITYPE_HELM = 0x7, ITYPE_MARMOR = 0x8, ITYPE_HARMOR = 0x9, ITYPE_STAFF = 0xA, ITYPE_GOLD = 0xB, ITYPE_RING = 0xC, ITYPE_AMULET = 0xD, ITYPE_MEAT = 0xE, /* used in demo, might be generic for 'food' */ ITYPE_NONE = -1, } item_type; typedef enum _item_indexes { IDI_GOLD, IDI_WARRIOR, IDI_WARRSHLD, IDI_WARRCLUB, IDI_ROGUE, IDI_SORCEROR, IDI_CLEAVER, IDI_FIRSTQUEST = IDI_CLEAVER, IDI_SKCROWN, IDI_INFRARING, IDI_ROCK, IDI_OPTAMULET, IDI_TRING, IDI_BANNER, IDI_HARCREST, IDI_STEELVEIL, IDI_GLDNELIX, IDI_ANVIL, IDI_MUSHROOM, IDI_BRAIN, IDI_FUNGALTM, IDI_SPECELIX, IDI_BLDSTONE, IDI_MAPOFDOOM, IDI_LASTQUEST = IDI_MAPOFDOOM, IDI_EAR, IDI_HEAL, IDI_MANA, IDI_IDENTIFY, IDI_PORTAL, IDI_ARMOFVAL, IDI_FULLHEAL, IDI_FULLMANA, IDI_GRISWOLD, IDI_LGTFORGE, IDI_LAZSTAFF, IDI_RESURRECT, } _item_indexes; typedef enum _setlevels { //SL_BUTCHCHAMB = 0x0, SL_SKELKING = 0x1, SL_BONECHAMB = 0x2, SL_MAZE = 0x3, SL_POISONWATER = 0x4, SL_VILEBETRAYER = 0x5, } _setlevels; typedef enum quest_id { Q_ROCK = 0x0, Q_MUSHROOM = 0x1, Q_GARBUD = 0x2, Q_ZHAR = 0x3, Q_VEIL = 0x4, Q_DIABLO = 0x5, Q_BUTCHER = 0x6, Q_LTBANNER = 0x7, Q_BLIND = 0x8, Q_BLOOD = 0x9, Q_ANVIL = 0xA, Q_WARLORD = 0xB, Q_SKELKING = 0xC, Q_PWATER = 0xD, Q_SCHAMB = 0xE, Q_BETRAYER = 0xF, Q_INVALID = -1, } quest_id; typedef enum quest_state { QUEST_NOTAVAIL = 0, QUEST_INIT = 1, QUEST_ACTIVE = 2, QUEST_DONE = 3 } quest_state; typedef enum quest_mush_state { QS_INIT = 0, QS_TOMESPAWNED = 1, QS_TOMEGIVEN = 2, QS_MUSHSPAWNED = 3, QS_MUSHPICKED = 4, QS_MUSHGIVEN = 5, QS_BRAINSPAWNED = 6, QS_BRAINGIVEN = 7, } quest_mush_state; typedef enum talk_id { STORE_NONE = 0x0, STORE_SMITH = 0x1, STORE_SBUY = 0x2, STORE_SSELL = 0x3, STORE_SREPAIR = 0x4, STORE_WITCH = 0x5, STORE_WBUY = 0x6, STORE_WSELL = 0x7, STORE_WRECHARGE = 0x8, STORE_NOMONEY = 0x9, STORE_NOROOM = 0xA, STORE_CONFIRM = 0xB, STORE_BOY = 0xC, STORE_BBOY = 0xD, STORE_HEALER = 0xE, STORE_STORY = 0xF, STORE_HBUY = 0x10, STORE_SIDENTIFY = 0x11, STORE_SPBUY = 0x12, STORE_GOSSIP = 0x13, STORE_IDSHOW = 0x14, STORE_TAVERN = 0x15, STORE_DRUNK = 0x16, STORE_BARMAID = 0x17, } talk_id; typedef enum _unique_items { UITEM_CLEAVER = 0x0, UITEM_SKCROWN = 0x1, UITEM_INFRARING = 0x2, UITEM_OPTAMULET = 0x3, UITEM_TRING = 0x4, UITEM_HARCREST = 0x5, UITEM_STEELVEIL = 0x6, UITEM_ARMOFVAL = 0x7, UITEM_GRISWOLD = 0x8, UITEM_LGTFORGE = 0x9, UITEM_RIFTBOW = 0xA, UITEM_NEEDLER = 0xB, UITEM_CELESTBOW = 0xC, UITEM_DEADLYHUNT = 0xD, UITEM_BOWOFDEAD = 0xE, UITEM_BLKOAKBOW = 0xF, UITEM_FLAMEDART = 0x10, UITEM_FLESHSTING = 0x11, UITEM_WINDFORCE = 0x12, UITEM_EAGLEHORN = 0x13, UITEM_GONNAGALDIRK = 0x14, UITEM_DEFENDER = 0x15, UITEM_GRYPHONCLAW = 0x16, UITEM_BLACKRAZOR = 0x17, UITEM_GIBBOUSMOON = 0x18, UITEM_ICESHANK = 0x19, UITEM_EXECUTIONER = 0x1A, UITEM_BONESAW = 0x1B, UITEM_SHADHAWK = 0x1C, UITEM_WIZSPIKE = 0x1D, UITEM_LGTSABRE = 0x1E, UITEM_FALCONTALON = 0x1F, UITEM_INFERNO = 0x20, UITEM_DOOMBRINGER = 0x21, UITEM_GRIZZLY = 0x22, UITEM_GRANDFATHER = 0x23, UITEM_MANGLER = 0x24, UITEM_SHARPBEAK = 0x25, UITEM_BLOODLSLAYER = 0x26, UITEM_CELESTAXE = 0x27, UITEM_WICKEDAXE = 0x28, UITEM_STONECLEAV = 0x29, UITEM_AGUHATCHET = 0x2A, UITEM_HELLSLAYER = 0x2B, UITEM_MESSERREAVER = 0x2C, UITEM_CRACKRUST = 0x2D, UITEM_JHOLMHAMM = 0x2E, UITEM_CIVERBS = 0x2F, UITEM_CELESTSTAR = 0x30, UITEM_BARANSTAR = 0x31, UITEM_GNARLROOT = 0x32, UITEM_CRANBASH = 0x33, UITEM_SCHAEFHAMM = 0x34, UITEM_DREAMFLANGE = 0x35, UITEM_STAFFOFSHAD = 0x36, UITEM_IMMOLATOR = 0x37, UITEM_STORMSPIRE = 0x38, UITEM_GLEAMSONG = 0x39, UITEM_THUNDERCALL = 0x3A, UITEM_PROTECTOR = 0x3B, UITEM_NAJPUZZLE = 0x3C, UITEM_MINDCRY = 0x3D, UITEM_RODOFONAN = 0x3E, UITEM_SPIRITSHELM = 0x3F, UITEM_THINKINGCAP = 0x40, UITEM_OVERLORDHELM = 0x41, UITEM_FOOLSCREST = 0x42, UITEM_GOTTERDAM = 0x43, UITEM_ROYCIRCLET = 0x44, UITEM_TORNFLESH = 0x45, UITEM_GLADBANE = 0x46, UITEM_RAINCLOAK = 0x47, UITEM_LEATHAUT = 0x48, UITEM_WISDWRAP = 0x49, UITEM_SPARKMAIL = 0x4A, UITEM_SCAVCARAP = 0x4B, UITEM_NIGHTSCAPE = 0x4C, UITEM_NAJPLATE = 0x4D, UITEM_DEMONSPIKE = 0x4E, UITEM_DEFLECTOR = 0x4F, UITEM_SKULLSHLD = 0x50, UITEM_DRAGONBRCH = 0x51, UITEM_BLKOAKSHLD = 0x52, UITEM_HOLYDEF = 0x53, UITEM_STORMSHLD = 0x54, UITEM_BRAMBLE = 0x55, UITEM_REGHA = 0x56, UITEM_BLEEDER = 0x57, UITEM_CONSTRICT = 0x58, UITEM_ENGAGE = 0x59, UITEM_INVALID = 0x5A, } _unique_items; typedef enum plr_class { PC_WARRIOR = 0x0, PC_ROGUE = 0x1, PC_SORCERER = 0x2, NUM_CLASSES } plr_class; typedef enum _ui_classes { UI_WARRIOR = 0x0, UI_ROGUE = 0x1, UI_SORCERER = 0x2, UI_NUM_CLASSES, } _ui_classes; typedef enum _walk_path { WALK_NE = 0x1, WALK_NW = 0x2, WALK_SE = 0x3, WALK_SW = 0x4, WALK_N = 0x5, WALK_E = 0x6, WALK_S = 0x7, WALK_W = 0x8, WALK_NONE = -1, } _walk_path; typedef enum player_weapon_type { WT_MELEE = 0, WT_RANGED = 1, } player_weapon_type; typedef enum item_class { ICLASS_NONE = 0, ICLASS_WEAPON = 1, ICLASS_ARMOR = 2, ICLASS_MISC = 3, ICLASS_GOLD = 4, ICLASS_QUEST = 5, } item_class; typedef enum item_drop_rate { IDROP_NEVER = 0, IDROP_REGULAR = 1, IDROP_DOUBLE = 2, } item_drop_rate; typedef enum item_special_effect { ISPL_NONE = 0x00000000, ISPL_INFRAVISION = 0x00000001, ISPL_RNDSTEALLIFE = 0x00000002, ISPL_RNDARROWVEL = 0x00000004, ISPL_FIRE_ARROWS = 0x00000008, ISPL_FIREDAM = 0x00000010, ISPL_LIGHTDAM = 0x00000020, ISPL_DRAINLIFE = 0x00000040, ISPL_UNKNOWN_1 = 0x00000080, ISPL_NOHEALPLR = 0x00000100, ISPL_UNKNOWN_2 = 0x00000200, ISPL_UNKNOWN_3 = 0x00000400, ISPL_KNOCKBACK = 0x00000800, ISPL_NOHEALMON = 0x00001000, ISPL_STEALMANA_3 = 0x00002000, ISPL_STEALMANA_5 = 0x00004000, ISPL_STEALLIFE_3 = 0x00008000, ISPL_STEALLIFE_5 = 0x00010000, ISPL_QUICKATTACK = 0x00020000, ISPL_FASTATTACK = 0x00040000, ISPL_FASTERATTACK = 0x00080000, ISPL_FASTESTATTACK = 0x00100000, ISPL_FASTRECOVER = 0x00200000, ISPL_FASTERRECOVER = 0x00400000, ISPL_FASTESTRECOVER = 0x00800000, ISPL_FASTBLOCK = 0x01000000, ISPL_LIGHT_ARROWS = 0x02000000, ISPL_THORNS = 0x04000000, ISPL_NOMANA = 0x08000000, ISPL_ABSHALFTRAP = 0x10000000, ISPL_UNKNOWN_4 = 0x20000000, ISPL_3XDAMVDEM = 0x40000000, ISPL_ALLRESZERO = 0x80000000, } item_special_effect; // Logical equipment locations typedef enum inv_body_loc { INVLOC_HEAD = 0, INVLOC_RING_LEFT = 1, INVLOC_RING_RIGHT = 2, INVLOC_AMULET = 3, INVLOC_HAND_LEFT = 4, INVLOC_HAND_RIGHT = 5, INVLOC_CHEST = 6, NUM_INVLOC, } inv_body_loc; typedef enum inv_item { INVITEM_HEAD = 0, INVITEM_RING_LEFT = 1, INVITEM_RING_RIGHT = 2, INVITEM_AMULET = 3, INVITEM_HAND_LEFT = 4, INVITEM_HAND_RIGHT = 5, INVITEM_CHEST = 6, INVITEM_INV_FIRST = 7, INVITEM_INV_LAST = 46, INVITEM_BELT_FIRST = 47, INVITEM_BELT_LAST = 54, NUM_INVELEM } inv_item; // identifiers for each of the inventory squares // see https://github.com/sanctuary/graphics/blob/master/inventory.png typedef enum inv_xy_slot { SLOTXY_HEAD_FIRST = 0, SLOTXY_HEAD_LAST = 3, SLOTXY_RING_LEFT = 4, SLOTXY_RING_RIGHT = 5, SLOTXY_AMULET = 6, SLOTXY_HAND_LEFT_FIRST = 7, SLOTXY_HAND_LEFT_LAST = 12, SLOTXY_HAND_RIGHT_FIRST = 13, SLOTXY_HAND_RIGHT_LAST = 18, SLOTXY_CHEST_FIRST = 19, SLOTXY_CHEST_LAST = 24, // regular inventory SLOTXY_INV_FIRST = 25, SLOTXY_INV_LAST = 64, // belt items SLOTXY_BELT_FIRST = 65, SLOTXY_BELT_LAST = 72, NUM_XY_SLOTS = 73 } inv_xy_slot; typedef enum player_graphic { PFILE_STAND = 1 << 0, PFILE_WALK = 1 << 1, PFILE_ATTACK = 1 << 2, PFILE_HIT = 1 << 3, PFILE_LIGHTNING = 1 << 4, PFILE_FIRE = 1 << 5, PFILE_MAGIC = 1 << 6, PFILE_DEATH = 1 << 7, PFILE_BLOCK = 1 << 8, // everything except PFILE_DEATH // 0b1_0111_1111 PFILE_NONDEATH = 0x17F } player_graphic; typedef enum anim_weapon_id { ANIM_ID_UNARMED = 0x00, ANIM_ID_UNARMED_SHIELD = 0x01, ANIM_ID_SWORD = 0x02, ANIM_ID_SWORD_SHIELD = 0x03, ANIM_ID_BOW = 0x04, ANIM_ID_AXE = 0x05, ANIM_ID_MACE = 0x06, ANIM_ID_MACE_SHIELD = 0x07, ANIM_ID_STAFF = 0x08 } anim_weapon_id; typedef enum anim_armor_id { ANIM_ID_LIGHT_ARMOR = 0x00, #ifndef SPAWN ANIM_ID_MEDIUM_ARMOR = 0x10, ANIM_ID_HEAVY_ARMOR = 0x20 #endif } anim_armor_id; typedef enum shrine_type { SHRINE_MYSTERIOUS = 0, SHRINE_HIDDEN = 1, SHRINE_GLOOMY = 2, SHRINE_WEIRD = 3, SHRINE_MAGICAL = 4, SHRINE_STONE = 5, SHRINE_RELIGIOUS = 6, SHRINE_ENCHANTED = 7, SHRINE_THAUMATURGIC = 8, SHRINE_FASCINATING = 9, SHRINE_CRYPTIC = 10, SHRINE_MAGICAL2 = 11, SHRINE_ELDRITCH = 12, SHRINE_EERIE = 13, SHRINE_DIVINE = 14, SHRINE_HOLY = 15, SHRINE_SACRED = 16, SHRINE_SPIRITUAL = 17, SHRINE_SPOOKY = 18, SHRINE_ABANDONED = 19, SHRINE_CREEPY = 20, SHRINE_QUIET = 21, SHRINE_SECLUDED = 22, SHRINE_ORNATE = 23, SHRINE_GLIMMERING = 24, SHRINE_TAINTED = 25, NUM_SHRINETYPE } shrine_type; typedef enum action_id { ACTION_NONE = -1, ACTION_ATTACK = 9, ACTION_RATTACK = 10, ACTION_SPELL = 12, ACTION_OPERATE = 13, ACTION_DISARM = 14, ACTION_PICKUPITEM = 15, // put item in hand (inventory screen open) ACTION_PICKUPAITEM = 16, // put item in inventory ACTION_TALK = 17, ACTION_OPERATETK = 18, // operate via telekinesis ACTION_ATTACKMON = 20, ACTION_ATTACKPLR = 21, ACTION_RATTACKMON = 22, ACTION_RATTACKPLR = 23, ACTION_SPELLMON = 24, ACTION_SPELLPLR = 25, ACTION_SPELLWALL = 26, } action_id; typedef enum dlrg_flag { DLRG_HDOOR = 0x01, DLRG_VDOOR = 0x02, DLRG_CHAMBER = 0x40, DLRG_PROTECTED = 0x80, } dlrg_flag;
{ "pile_set_name": "Github" }
Private *pynput* API ==================== This is the *internal pynput API*. It is used internally by *pynput*, and its interface is not stable. This documentation will contain only the modules used on the current platform. Utility Modules --------------- .. automodule:: pynput._util :members: :private-members: :special-members: .. automodule:: pynput._util.darwin :members: :private-members: :special-members: .. automodule:: pynput._util.win32 :members: :private-members: :special-members: .. automodule:: pynput._util.xorg :members: :private-members: :special-members: Mouse Modules ------------- .. automodule:: pynput.mouse._darwin :members: :private-members: :special-members: .. automodule:: pynput.mouse._win32 :members: :private-members: :special-members: .. automodule:: pynput.mouse._xorg :members: :private-members: :special-members: Keyboard Modules ---------------- .. automodule:: pynput.keyboard._darwin :members: :private-members: :special-members: .. automodule:: pynput.keyboard._win32 :members: :private-members: :special-members: .. automodule:: pynput.keyboard._xorg :members: :private-members: :special-members:
{ "pile_set_name": "Github" }
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{7950197D-4122-49CB-9FD7-45E666BAFEC2}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>DbLinq</RootNamespace> <AssemblyName>DbLinq</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <SignAssembly>true</SignAssembly> <AssemblyOriginatorKeyFile>..\DbLinq.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>..\..\build.dbg\</OutputPath> <DefineConstants>TRACE;DEBUG</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>..\..\build\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug - Mono Strict|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <OutputPath>..\..\build.dbg.mono\</OutputPath> <DefineConstants>TRACE;DEBUG</DefineConstants> <DebugType>full</DebugType> <PlatformTarget>AnyCPU</PlatformTarget> <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression> <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile> <ErrorReport>prompt</ErrorReport> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Configuration" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Data.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="..\DbLinq.ProductInfo.cs"> <Link>Properties\DbLinq.ProductInfo.cs</Link> </Compile> <Compile Include="Data\Linq\ChangeSet.cs" /> <Compile Include="Data\Linq\Database\IDatabaseContext.cs" /> <Compile Include="Data\Linq\Database\ITransactionalCommand.cs" /> <Compile Include="Data\Linq\Database\Implementation\DatabaseConnection.cs" /> <Compile Include="Data\Linq\Database\Implementation\DatabaseContext.cs" /> <Compile Include="Data\Linq\DataLoadOptions.cs" /> <Compile Include="Data\Linq\DBLinqExtendedAttributte.cs" /> <Compile Include="Data\Linq\EntityRef.cs" /> <Compile Include="Data\Linq\EntitySet.cs" /> <Compile Include="Data\Linq\Implementation\DisabledEntityTracker.cs" /> <Compile Include="Data\Linq\Implementation\IEntityTracker.cs" /> <Compile Include="Data\Linq\Implementation\EntityTrack.cs" /> <Compile Include="Data\Linq\Implementation\EntityState.cs" /> <Compile Include="Data\Linq\Implementation\EntityTracker.cs" /> <Compile Include="Data\Linq\Implementation\VendorProvider.cs" /> <Compile Include="Data\Linq\ITable.Extended.cs" /> <Compile Include="Data\Linq\DataContext.cs" /> <Compile Include="Data\Linq\DataContext.Extended.cs" /> <Compile Include="Data\Linq\Identity\IdentityKey.cs" /> <Compile Include="Data\Linq\Identity\IIdentityProvider.cs" /> <Compile Include="Data\Linq\Identity\IIdentityReader.cs" /> <Compile Include="Data\Linq\Identity\IIdentityReaderFactory.cs" /> <Compile Include="Data\Linq\Identity\Implementation\IdentityProviderReader.cs" /> <Compile Include="Data\Linq\Identity\Implementation\IdentityReader.cs" /> <Compile Include="Data\Linq\Identity\Implementation\IdentityReaderFactory.cs" /> <Compile Include="Data\Linq\IMemberModificationHandler.cs" /> <Compile Include="Data\Linq\Implementation\MemberModificationHandler.cs" /> <Compile Include="Data\Linq\Implementation\QueryProvider.cs" /> <Compile Include="Data\Linq\ITable.cs" /> <Compile Include="Data\Linq\IVendorProvider.cs" /> <Compile Include="Data\Linq\Mapping\AttributedAbstractMetaDataMember.cs" /> <Compile Include="Data\Linq\Mapping\AttributedAssociationMetaDataMember.cs" /> <Compile Include="Data\Linq\Mapping\AttributedColumnMetaDataMember.cs" /> <Compile Include="Data\Linq\Mapping\AttributedMetaAssociation.cs" /> <Compile Include="Data\Linq\Mapping\AttributedMetaFunction.cs" /> <Compile Include="Data\Linq\Mapping\AttributedMetaModel.cs" /> <Compile Include="Data\Linq\Mapping\AttributedMetaTable.cs" /> <Compile Include="Data\Linq\Mapping\AttributedMetaType.cs" /> <Compile Include="Data\Linq\Mapping\AttributeMappingSource.cs" /> <Compile Include="Data\Linq\Mapping\LambdaMetaAccessor.cs" /> <Compile Include="Data\Linq\Mapping\MappingContext.cs" /> <Compile Include="Data\Linq\Mapping\XmlMappingSource.cs" /> <Compile Include="Data\Linq\SqlClient\FirebirdProvider.cs" /> <Compile Include="Data\Linq\SqlClient\Sql2005Provider.cs" /> <Compile Include="Data\Linq\SqlClient\Sql2000Provider.cs" /> <Compile Include="Data\Linq\SqlClient\Sql2008Provider.cs" /> <Compile Include="Data\Linq\SqlClient\SqlServerProvider.cs" /> <Compile Include="Data\Linq\SqlClient\SqliteProvider.cs" /> <Compile Include="Data\Linq\SqlClient\OracleProvider.cs" /> <Compile Include="Data\Linq\SqlClient\PostgreSqlProvider.cs" /> <Compile Include="Data\Linq\SqlClient\MySqlProvider.cs" /> <Compile Include="Data\Linq\SqlClient\IngresProvider.cs" /> <Compile Include="Data\Linq\Sql\SqlStatementBuilder.cs" /> <Compile Include="Data\Linq\Sql\SqlParameterPart.cs" /> <Compile Include="Data\Linq\Sql\SqlLiteralPart.cs" /> <Compile Include="Data\Linq\Sql\SqlPart.cs" /> <Compile Include="Data\Linq\Sql\SqlStatement.cs" /> <Compile Include="Data\Linq\Sugar\BuilderContext.cs" /> <Compile Include="Data\Linq\Database\Implementation\TransactionalCommand.cs" /> <Compile Include="Data\Linq\Sugar\DeleteQuery.cs" /> <Compile Include="Data\Linq\Sugar\DirectQuery.cs" /> <Compile Include="Data\Linq\Sugar\Error.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionChain.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\ExpressionMutatorExtensions.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\ExpressionMutatorFactory.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\BinaryExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\ConditionalExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\ConstantExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\IMemberBindingMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\InvocationExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\LambdaExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\ListInitExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\MemberAssignmentMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\MemberBindingMutatorFactory.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\MemberExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\MemberInitExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\MemberListBindingMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\MemberMemberBindingMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\MethodCallExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\NewArrayExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\NewExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\ParameterExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\TypeBinaryExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionMutator\Implementation\UnaryExpressionMutator.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionPrecedence.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionQuery.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\ExpressionTranslator.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\ColumnExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\EntitySetExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\ObjectInputParameterExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\ObjectOutputParameterExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\CustomExpressionType.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\InputParameterExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\GroupExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\IExecutableExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\IMutableExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\MetaTableExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\MutableExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\OperandsMutableExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\OrderByExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\SelectExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\SelectOperatorType.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\SpecialExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\SpecialExpressionType.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\StartIndexOffsetExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\SubSelectExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\TableExpression.cs" /> <Compile Include="Data\Linq\Sugar\Expressions\TableJoinType.cs" /> <Compile Include="Data\Linq\Sugar\ExpressionTier.cs" /> <Compile Include="Data\Linq\Sugar\IDataMapper.cs" /> <Compile Include="Data\Linq\Sugar\IDataRecordReader.cs" /> <Compile Include="Data\Linq\Sugar\IExpressionDispatcher.cs" /> <Compile Include="Data\Linq\Sugar\IExpressionLanguageParser.cs" /> <Compile Include="Data\Linq\Sugar\IExpressionOptimizer.cs" /> <Compile Include="Data\Linq\Sugar\IExpressionQualifier.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\DataMapper.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\DataRecordReader.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\ExpressionDispatcher.Analyzer.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\ExpressionDispatcher.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\ExpressionDispatcher.Registrar.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\ExpressionLanguageParser.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\ExpressionOptimizer.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\ExpressionQualifier.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\QueryBuilder.Upsert.cs" /> <Compile Include="Data\Linq\Sugar\ParameterizedQuery.cs"> <SubType>Code</SubType> </Compile> <Compile Include="Data\Linq\Sugar\UpsertQuery.cs" /> <Compile Include="Data\Linq\Sugar\IQueryCache.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\LineGrouping.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\PrequelAnalyzer.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\QueryBuilder.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\QueryCache.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\QueryRunner.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\SpecialExpressionTranslator.cs" /> <Compile Include="Data\Linq\Sugar\Implementation\SqlBuilder.cs" /> <Compile Include="Data\Linq\Sugar\IPrequelAnalyzer.cs" /> <Compile Include="Data\Linq\Sugar\IQueryBuilder.cs" /> <Compile Include="Data\Linq\Sugar\IQueryRunner.cs" /> <Compile Include="Data\Linq\Sugar\ISpecialExpressionTranslator.cs" /> <Compile Include="Data\Linq\Sugar\ISqlBuilder.cs" /> <Compile Include="Data\Linq\Sugar\AbstractQuery.cs" /> <Compile Include="Data\Linq\Sugar\SelectQuery.cs" /> <Compile Include="Data\Linq\Sugar\QueryContext.cs" /> <Compile Include="Data\Linq\Table.cs" /> <Compile Include="Data\Linq\Table.Extended.cs" /> <Compile Include="DbLinqToDoAttribute.cs" /> <Compile Include="Factory\DbLinqAttribute.cs" /> <Compile Include="Factory\Implementation\ReflectionObjectFactory.cs" /> <Compile Include="Factory\IObjectFactory.cs" /> <Compile Include="Factory\ObjectFactory.cs" /> <Compile Include="Schema\Case.cs" /> <Compile Include="Schema\Dbml\Adapter\ArrayAdapter.cs" /> <Compile Include="Schema\Dbml\Adapter\CsvArrayAdapter.cs" /> <Compile Include="Schema\Dbml\Adapter\EnumType.cs" /> <Compile Include="Schema\Dbml\Adapter\INamedType.cs" /> <Compile Include="Schema\Dbml\Adapter\ISimpleList.cs" /> <Compile Include="Schema\Dbml\Adapter\SpecifiedPropertyUpdater.cs" /> <Compile Include="Schema\Dbml\DatabaseSerializer.cs" /> <Compile Include="Schema\WordsExtraction.cs" /> <Compile Include="Schema\NameFormat.cs" /> <Compile Include="Schema\AssociationName.cs" /> <Compile Include="Schema\ColumnName.cs" /> <Compile Include="Schema\ParameterName.cs" /> <Compile Include="Schema\Dbml\DbmlSchema.Adapter.cs" /> <Compile Include="Schema\Dbml\DbmlSchema.cs"> <DependentUpon>DbmlSchema.xsd</DependentUpon> </Compile> <Compile Include="Schema\Dbml\DbmlSerializer.cs" /> <Compile Include="Schema\ProcedureName.cs" /> <Compile Include="Schema\Name.cs" /> <Compile Include="Schema\SchemaName.cs" /> <Compile Include="Schema\TableName.cs" /> <Compile Include="Util\DbmlExtensions.cs" /> <Compile Include="Util\ExpressionChainEqualityComparer.cs" /> <Compile Include="Util\ExpressionEqualityComparer.cs" /> <Compile Include="Util\IThreadSafeDictionary.cs" /> <Compile Include="Util\Output.cs" /> <Compile Include="Util\IDataRecordExtensions.cs" /> <Compile Include="Util\IDataTypeExtensions.cs" /> <Compile Include="Language\ILanguages.cs" /> <Compile Include="Language\ILanguageWords.cs" /> <Compile Include="Util\IDbDataParameterExtensions.cs" /> <Compile Include="Util\OutputLevel.cs" /> <Compile Include="Util\Profiler.cs" /> <Compile Include="Util\ReflectionUtility.cs" /> <Compile Include="Util\TextWriterExtension.cs" /> <Compile Include="Util\LambdaComparer.cs" /> <Compile Include="Util\DataCommand.cs" /> <Compile Include="Schema\INameFormatter.cs" /> <Compile Include="Language\Implementation\AbstractEndPluralWords.cs" /> <Compile Include="Language\Implementation\AbstractWords.cs" /> <Compile Include="Language\Implementation\Languages.cs" /> <Compile Include="Language\Implementation\NoLanguageWords.cs" /> <Compile Include="Schema\Implementation\NameFormatter.cs" /> <Compile Include="Util\MemberInfoExtensions.cs" /> <Compile Include="Util\ReflectionExtensions.cs"> <SubType>Code</SubType> </Compile> <Compile Include="Util\StringExtensions.cs" /> <Compile Include="Util\ThreadSafeDictionary.cs" /> <Compile Include="Util\TypeConvert.cs" /> <Compile Include="Util\QuotesHelper.cs" /> <Compile Include="Util\ReferenceEqualityComparer.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Util\Page.cs" /> <Compile Include="Util\TypeExtensions.cs"> <SubType>Code</SubType> </Compile> <Compile Include="Util\TypeLoader.cs" /> <Compile Include="Vendor\DbSchemaLoader.cs" /> <Compile Include="Vendor\VendorAttribute.cs" /> <Compile Include="Vendor\IDataTableColumn.cs" /> <Compile Include="Vendor\IDataName.cs" /> <Compile Include="Vendor\IDataType.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.Name.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.Columns.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.DataTableColumn.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.DataName.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.ForeignKey.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.StoredProcedures.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.Tables.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.TypeMapping.cs" /> <Compile Include="Vendor\Implementation\Vendor.ProcedureResult.cs" /> <Compile Include="Vendor\INameAliases.cs" /> <Compile Include="Vendor\ISchemaLoader.cs" /> <Compile Include="Vendor\ISqlProvider.cs" /> <Compile Include="Vendor\IVendor.cs" /> <Compile Include="Vendor\Implementation\SchemaLoader.cs" /> <Compile Include="Vendor\Implementation\Vendor.cs" /> <Compile Include="Vendor\Implementation\SqlProvider.cs" /> </ItemGroup> <ItemGroup> <None Include="..\DbLinq.snk"> <Link>Properties\DbLinq.snk</Link> </None> <None Include="Schema\Dbml\DbmlSchema.bat" /> <EmbeddedResource Include="Schema\Dbml\DbmlSchema.xsd"> </EmbeddedResource> </ItemGroup> <ItemGroup> <Content Include="Data\Linq\Sugar\Notes.txt" /> <Content Include="Data\Linq\ReadMe.txt" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <PropertyGroup> <PreBuildEvent> </PreBuildEvent> </PropertyGroup> </Project>
{ "pile_set_name": "Github" }
--- author: rosielowther type: normal category: must-know tags: - introduction --- # Functions Can Be Declared After Use --- ## Content Function **declarations** load before other code is executed. This means that the function can be declared after it has been used. For example: ```js alert(foo()); // Alerts 'Enki'. // Function declaration function foo() { return 'Enki'; } ``` If however a function **expression** is used rather than a function **declaration** an error will be produced: ```js alert(foo()); // Error! // Function expression var foo = function() { return 'Enki'; } ``` This is because function **expressions** are evaluated from the top-down as normal. --- ## Practice Give the output: ```js alert(foo()); // ??? var foo = function() { return 'Enki'; } ``` - error - alerts 'Enki' --- ## Revision Give the output: ```js alert(foo()); // ??? function foo() { return 'Enki'; } ``` - alerts 'Enki' - error
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE module PUBLIC "-//NetBeans//DTD Module Status 1.0//EN" "http://www.netbeans.org/dtds/module-status-1_0.dtd"> <module name="org.netbeans.modules.applemenu"> <param name="autoload">false</param> <param name="eager">true</param> <param name="jar">modules/org-netbeans-modules-applemenu.jar</param> <param name="reloadable">false</param> </module>
{ "pile_set_name": "Github" }
this is sub index <%include file="incl.html"/>
{ "pile_set_name": "Github" }
#!/usr/bin/env perl # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. use strict; if($ENV{'GOARCH'} eq "" || $ENV{'GOOS'} eq "") { print STDERR "GOARCH or GOOS not defined in environment\n"; exit 1; } # Check that we are using the new build system if we should if($ENV{'GOLANG_SYS_BUILD'} ne "docker") { print STDERR "In the new build system, mksysnum should not be called directly.\n"; print STDERR "See README.md\n"; exit 1; } my $command = "$0 ". join(' ', @ARGV); print <<EOF; // $command // Code generated by the command above; see README.md. DO NOT EDIT. // +build $ENV{'GOARCH'},$ENV{'GOOS'} package unix const( EOF my $offset = 0; sub fmt { my ($name, $num) = @_; if($num > 999){ # ignore deprecated syscalls that are no longer implemented # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/uapi/asm-generic/unistd.h?id=refs/heads/master#n716 return; } $name =~ y/a-z/A-Z/; $num = $num + $offset; print " SYS_$name = $num;\n"; } my $prev; open(CC, "$ENV{'CC'} -E -dD @ARGV |") || die "can't run $ENV{'CC'}"; while(<CC>){ if(/^#define __NR_Linux\s+([0-9]+)/){ # mips/mips64: extract offset $offset = $1; } elsif(/^#define __NR(\w*)_SYSCALL_BASE\s+([0-9]+)/){ # arm: extract offset $offset = $1; } elsif(/^#define __NR_syscalls\s+/) { # ignore redefinitions of __NR_syscalls } elsif(/^#define __NR_(\w*)Linux_syscalls\s+/) { # mips/mips64: ignore definitions about the number of syscalls } elsif(/^#define __NR_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR3264_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR_(\w+)\s+\(\w+\+\s*([0-9]+)\)/){ fmt($1, $prev+$2) } elsif(/^#define __NR_(\w+)\s+\(__NR_Linux \+ ([0-9]+)/){ fmt($1, $2); } elsif(/^#define __NR_(\w+)\s+\(__NR_SYSCALL_BASE \+ ([0-9]+)/){ fmt($1, $2); } } print <<EOF; ) EOF
{ "pile_set_name": "Github" }
#Project properties #Sun May 22 02:48:51 BST 2011 project.organization=org.bowlerframework project.name=parent sbt.version=0.7.5.RC0 project.version=0.7-SNAPSHOT build.scala.versions=2.9.1 project.initialize=false
{ "pile_set_name": "Github" }
/* * Copyright (C) Research In Motion Limited 2010. All rights reserved. * * 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. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG) #include "SVGShadowTreeElements.h" #include "Document.h" #include "FloatSize.h" #include "RenderObject.h" #include "SVGNames.h" #include "SVGUseElement.h" namespace WebCore { // SVGShadowTreeContainerElement SVGShadowTreeContainerElement::SVGShadowTreeContainerElement(Document* document) : SVGGElement(SVGNames::gTag, document) { } PassRefPtr<SVGShadowTreeContainerElement> SVGShadowTreeContainerElement::create(Document* document) { return adoptRef(new SVGShadowTreeContainerElement(document)); } FloatSize SVGShadowTreeContainerElement::containerTranslation() const { return FloatSize(m_xOffset.value(this), m_yOffset.value(this)); } PassRefPtr<Element> SVGShadowTreeContainerElement::cloneElementWithoutAttributesAndChildren() const { return adoptRef(new SVGShadowTreeContainerElement(document())); } // SVGShadowTreeRootElement inline SVGShadowTreeRootElement::SVGShadowTreeRootElement(Document* document, SVGUseElement* host) : SVGShadowTreeContainerElement(document) { setParent(host); setInDocument(); } PassRefPtr<SVGShadowTreeRootElement> SVGShadowTreeRootElement::create(Document* document, SVGUseElement* host) { return adoptRef(new SVGShadowTreeRootElement(document, host)); } void SVGShadowTreeRootElement::attachElement(PassRefPtr<RenderStyle> style, RenderArena* arena) { ASSERT(svgShadowHost()); // Create the renderer with the specified style RenderObject* renderer = createRenderer(arena, style.get()); if (renderer) { setRenderer(renderer); renderer->setStyle(style); } // Set these explicitly since this normally happens during an attach() setAttached(); // Add the renderer to the render tree if (renderer) svgShadowHost()->renderer()->addChild(renderer); } void SVGShadowTreeRootElement::clearSVGShadowHost() { setParent(0); } } #endif
{ "pile_set_name": "Github" }
+++ title = "Category:Pythonwin" description = "" date = 2014-11-29T21:35:09Z aliases = [] [extra] id = 1746 [taxonomies] categories = [] tags = [] +++ {{stub}} {{library}} [[Category:Python]] [[Python]] extensions for Windows ;Websites * http://sourceforge.net/projects/pywin32/ * http://starship.python.net/crew/mhammond/win32/Downloads.html ;Current version: Build 219 (2014-05-04)
{ "pile_set_name": "Github" }
/* * Copyright 2017-2019 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.inject.errors import io.micronaut.AbstractBeanDefinitionSpec import io.micronaut.context.DefaultBeanContext import io.micronaut.inject.BeanDefinition import io.micronaut.inject.BeanFactory import io.micronaut.inject.qualifiers.One class GroovySingletonSpec extends AbstractBeanDefinitionSpec { void "test that compilation fails if injection visited on Groovy singleton"() { when: BeanDefinition beanDefinition = buildBeanDefinition('io.micronaut.inject.property.MyBean', ''' package io.micronaut.inject.property; import io.micronaut.inject.qualifiers.* @Singleton class MyBean { @javax.inject.Inject @javax.annotation.Nullable AnotherBean injected } @javax.inject.Singleton class AnotherBean { } ''') then: def e = thrown(Exception) e.message.contains("Class annotated with groovy.lang.Singleton instead of javax.inject.Singleton. Import javax.inject.Singleton to use Micronaut Dependency Injection") } }
{ "pile_set_name": "Github" }
from rsf.proj import* from rsf.prog import RSFROOT def Grey(data,other): Result(data,'window f2=560 n2=180 | put o2=0| real | grey clip=0.7 label2=Trace color=d unit2="" label1=Time unit1="s" title="" wherexlabel=t scalebar=n %s'%other) def Grey1(data,other): Result(data,'window f2=560 n2=180 | put o2=0 | math output="abs(input)" | real | grey label2=Trace unit2="" label1=Time unit1="s" wherexlabel=t allpos=y color=j title= scalebar=y unit2= %s'%other) def Grey2(data,other): Result(data,'window f2=560 n2=180 |put o2=0 | grey clip=0.7 label2=Trace color=d unit2="" label1=Time unit1="s" title="" wherexlabel=t scalebar=n %s'%other) def Grey3(data,other): Result(data,'put o2=0 | grey clip=0.7 label2=Trace color=d unit2="" label1=Time unit1="s" title="" wherexlabel=t scalebar=n %s'%other) def Greyzoom(data,other): Result(data,'put d1=0.002 d2=1 o1=1.5 o2=0 | grey minval=-0.3 maxval=0.3 clip=0.3 label2=Trace color=g unit2="" label1=Time unit1="s" title="" wherexlabel=t scalebar=n %s'%other) Fetch('stack.bin','freeusp') Flow('data','stack.bin',' echo in=$SOURCE n1=751 n2=1285 data_format=native_float | put n1=751 n2=1285 d1=0.004 d2=1 o1=0 o2=0 | scale axis=2' ) #Plot('data','grey clip=0.9 title="Input Data"') Grey2('data','title="Input data"') ######################################################################## # INITIALIZATION ######################################################################## Flow('data1','data','window f2=560 n2=180') n1=751 n2=180 matlab = WhereIs('matlab') matROOT = '../matfun' matfun = 'Freeusp' matlabpath = os.environ.get('MATLABPATH',os.path.join(RSFROOT,'lib')) if not matlab: sys.stderr.write('\nCannot find Matlab.\n') sys.exit(1) ############################################################ ## generate and process synthetic data ############################################################ Flow('imf1 imf2 imf3 imf4',[os.path.join(matROOT,matfun+'.m'),'data1'], '''MATLABPATH=%(matlabpath)s %(matlab)s -nosplash -nojvm -r "addpath %(matROOT)s;%(matfun)s('${SOURCES[1]}',%(n1)d,%(n2)d,'${TARGETS[0]}','${TARGETS[1]}','${TARGETS[2]}','${TARGETS[3]}');quit" '''%vars(),stdin=0,stdout=-1) Grey3('imf1','title="Component 1"') Grey3('imf2','title="Component 2"') Grey3('imf3','title="Component 3"') Grey3('imf4','title="Component 4"') End()
{ "pile_set_name": "Github" }
%% % Plot of "Generalized extreme value distribution" addpath('../toolbox/'); rep = MkResRep(); n = 2048; A = 4; s = linspace(-A,A,n); q0 = 12; xilist0 = linspace(-.7,.9,q0); q = 50; % for animation xilist = linspace(-.7,.9,q); for j=1:q t = (j-1)/(q-1); % background display clf; hold on; for i=1:q0 t0 = (i-1)/(q0-1); plot(s(1:n-1), ExtVal(s,xilist0(i)), 'LineWidth', 1, 'Color', .6*[1 1 1] + .4*[t0 0 1-t0]); end % display plot(s(1:n-1), ExtVal(s,xilist(j)), 'LineWidth', 3, 'Color', [t 0 1-t]); set(gca, 'XTick', [], 'YTick', [], 'PlotBoxAspectRatio', [1 1/2 1], 'FontSize', 20); axis([-A A 0 .6]); box on; drawnow; saveas(gcf, [rep 'extreme-' znum2str(j,2) '.png']); end % AutoCrop(rep, 'extreme'); %axis tight; % set(gca, 'XTick', -A:2:A, 'YTick', 0:.2:1, 'PlotBoxAspectRatio', [1 1/2 1], 'FontSize', 20); % axis([-A A 0 .6]); box on;
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 7bc1a2717a9454c4992a584ac902b809 timeCreated: 1469444756 licenseType: Free NativeFormatImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
noinst_LIBRARIES = libiso9660.a libiso9660_a_SOURCES = iso9660.c iso9660_fs.c rock.c xa.c # Boy do you NOT want to have HAVE_CONFIG_H set before $(AM_CFLAGS) with Clang! libiso9660_a_CFLAGS = $(AM_CFLAGS) -DHAVE_CONFIG_H -I$(srcdir) -I$(srcdir)/.. -I$(srcdir)/../driver
{ "pile_set_name": "Github" }
'use strict'; module.exports = app => { app.router.get('/', 'home.render'); app.router.get('/ajax', app.controller.ajax.show); app.router.post('/ajax', app.controller.ajax.upload); app.router.get('/form', app.controller.form.show); app.router.post('/form', app.controller.form.upload); app.router.get('/multiple-file', app.controller.multiple.show); app.router.post('/multiple-file', app.controller.multiple.upload); app.router.get('/buffer', app.controller.buffer.show); app.router.post('/buffer', app.controller.buffer.upload); };
{ "pile_set_name": "Github" }
var ip6__addr_8c = [ [ "ip6addr_aton", "ip6__addr_8c.html#a3f555ae302eb056f28f6cb266a27036e", null ], [ "ip6addr_ntoa", "ip6__addr_8c.html#adba4443e6629583d48e1d1c7c21a977e", null ], [ "ip6addr_ntoa_r", "ip6__addr_8c.html#a64d442f35f34c43121bf91cfea2e77a2", null ] ];
{ "pile_set_name": "Github" }
include ../../../rel-eng/Makefile.git
{ "pile_set_name": "Github" }
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fuzz import ( "fmt" "math/rand" "reflect" "regexp" "time" ) // fuzzFuncMap is a map from a type to a fuzzFunc that handles that type. type fuzzFuncMap map[reflect.Type]reflect.Value // Fuzzer knows how to fill any object with random fields. type Fuzzer struct { fuzzFuncs fuzzFuncMap defaultFuzzFuncs fuzzFuncMap r *rand.Rand nilChance float64 minElements int maxElements int maxDepth int skipFieldPatterns []*regexp.Regexp } // New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs, // RandSource, NilChance, or NumElements in any order. func New() *Fuzzer { return NewWithSeed(time.Now().UnixNano()) } func NewWithSeed(seed int64) *Fuzzer { f := &Fuzzer{ defaultFuzzFuncs: fuzzFuncMap{ reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime), }, fuzzFuncs: fuzzFuncMap{}, r: rand.New(rand.NewSource(seed)), nilChance: .2, minElements: 1, maxElements: 10, maxDepth: 100, } return f } // Funcs adds each entry in fuzzFuncs as a custom fuzzing function. // // Each entry in fuzzFuncs must be a function taking two parameters. // The first parameter must be a pointer or map. It is the variable that // function will fill with random data. The second parameter must be a // fuzz.Continue, which will provide a source of randomness and a way // to automatically continue fuzzing smaller pieces of the first parameter. // // These functions are called sensibly, e.g., if you wanted custom string // fuzzing, the function `func(s *string, c fuzz.Continue)` would get // called and passed the address of strings. Maps and pointers will always // be made/new'd for you, ignoring the NilChange option. For slices, it // doesn't make much sense to pre-create them--Fuzzer doesn't know how // long you want your slice--so take a pointer to a slice, and make it // yourself. (If you don't want your map/pointer type pre-made, take a // pointer to it, and make it yourself.) See the examples for a range of // custom functions. func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer { for i := range fuzzFuncs { v := reflect.ValueOf(fuzzFuncs[i]) if v.Kind() != reflect.Func { panic("Need only funcs!") } t := v.Type() if t.NumIn() != 2 || t.NumOut() != 0 { panic("Need 2 in and 0 out params!") } argT := t.In(0) switch argT.Kind() { case reflect.Ptr, reflect.Map: default: panic("fuzzFunc must take pointer or map type") } if t.In(1) != reflect.TypeOf(Continue{}) { panic("fuzzFunc's second parameter must be type fuzz.Continue") } f.fuzzFuncs[argT] = v } return f } // RandSource causes f to get values from the given source of randomness. // Use if you want deterministic fuzzing. func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer { f.r = rand.New(s) return f } // NilChance sets the probability of creating a nil pointer, map, or slice to // 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive. func (f *Fuzzer) NilChance(p float64) *Fuzzer { if p < 0 || p > 1 { panic("p should be between 0 and 1, inclusive.") } f.nilChance = p return f } // NumElements sets the minimum and maximum number of elements that will be // added to a non-nil map or slice. func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer { if atLeast > atMost { panic("atLeast must be <= atMost") } if atLeast < 0 { panic("atLeast must be >= 0") } f.minElements = atLeast f.maxElements = atMost return f } func (f *Fuzzer) genElementCount() int { if f.minElements == f.maxElements { return f.minElements } return f.minElements + f.r.Intn(f.maxElements-f.minElements+1) } func (f *Fuzzer) genShouldFill() bool { return f.r.Float64() > f.nilChance } // MaxDepth sets the maximum number of recursive fuzz calls that will be made // before stopping. This includes struct members, pointers, and map and slice // elements. func (f *Fuzzer) MaxDepth(d int) *Fuzzer { f.maxDepth = d return f } // Skip fields which match the supplied pattern. Call this multiple times if needed // This is useful to skip XXX_ fields generated by protobuf func (f *Fuzzer) SkipFieldsWithPattern(pattern *regexp.Regexp) *Fuzzer { f.skipFieldPatterns = append(f.skipFieldPatterns, pattern) return f } // Fuzz recursively fills all of obj's fields with something random. First // this tries to find a custom fuzz function (see Funcs). If there is no // custom function this tests whether the object implements fuzz.Interface and, // if so, calls Fuzz on it to fuzz itself. If that fails, this will see if // there is a default fuzz function provided by this package. If all of that // fails, this will generate random values for all primitive fields and then // recurse for all non-primitives. // // This is safe for cyclic or tree-like structs, up to a limit. Use the // MaxDepth method to adjust how deep you need it to recurse. // // obj must be a pointer. Only exported (public) fields can be set (thanks, // golang :/ ) Intended for tests, so will panic on bad input or unimplemented // fields. func (f *Fuzzer) Fuzz(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() f.fuzzWithContext(v, 0) } // FuzzNoCustom is just like Fuzz, except that any custom fuzz function for // obj's type will not be called and obj will not be tested for fuzz.Interface // conformance. This applies only to obj and not other instances of obj's // type. // Not safe for cyclic or tree-like structs! // obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) // Intended for tests, so will panic on bad input or unimplemented fields. func (f *Fuzzer) FuzzNoCustom(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() f.fuzzWithContext(v, flagNoCustomFuzz) } const ( // Do not try to find a custom fuzz function. Does not apply recursively. flagNoCustomFuzz uint64 = 1 << iota ) func (f *Fuzzer) fuzzWithContext(v reflect.Value, flags uint64) { fc := &fuzzerContext{fuzzer: f} fc.doFuzz(v, flags) } // fuzzerContext carries context about a single fuzzing run, which lets Fuzzer // be thread-safe. type fuzzerContext struct { fuzzer *Fuzzer curDepth int } func (fc *fuzzerContext) doFuzz(v reflect.Value, flags uint64) { if fc.curDepth >= fc.fuzzer.maxDepth { return } fc.curDepth++ defer func() { fc.curDepth-- }() if !v.CanSet() { return } if flags&flagNoCustomFuzz == 0 { // Check for both pointer and non-pointer custom functions. if v.CanAddr() && fc.tryCustom(v.Addr()) { return } if fc.tryCustom(v) { return } } if fn, ok := fillFuncMap[v.Kind()]; ok { fn(v, fc.fuzzer.r) return } switch v.Kind() { case reflect.Map: if fc.fuzzer.genShouldFill() { v.Set(reflect.MakeMap(v.Type())) n := fc.fuzzer.genElementCount() for i := 0; i < n; i++ { key := reflect.New(v.Type().Key()).Elem() fc.doFuzz(key, 0) val := reflect.New(v.Type().Elem()).Elem() fc.doFuzz(val, 0) v.SetMapIndex(key, val) } return } v.Set(reflect.Zero(v.Type())) case reflect.Ptr: if fc.fuzzer.genShouldFill() { v.Set(reflect.New(v.Type().Elem())) fc.doFuzz(v.Elem(), 0) return } v.Set(reflect.Zero(v.Type())) case reflect.Slice: if fc.fuzzer.genShouldFill() { n := fc.fuzzer.genElementCount() v.Set(reflect.MakeSlice(v.Type(), n, n)) for i := 0; i < n; i++ { fc.doFuzz(v.Index(i), 0) } return } v.Set(reflect.Zero(v.Type())) case reflect.Array: if fc.fuzzer.genShouldFill() { n := v.Len() for i := 0; i < n; i++ { fc.doFuzz(v.Index(i), 0) } return } v.Set(reflect.Zero(v.Type())) case reflect.Struct: for i := 0; i < v.NumField(); i++ { skipField := false fieldName := v.Type().Field(i).Name for _, pattern := range fc.fuzzer.skipFieldPatterns { if pattern.MatchString(fieldName) { skipField = true break } } if !skipField { fc.doFuzz(v.Field(i), 0) } } case reflect.Chan: fallthrough case reflect.Func: fallthrough case reflect.Interface: fallthrough default: panic(fmt.Sprintf("Can't handle %#v", v.Interface())) } } // tryCustom searches for custom handlers, and returns true iff it finds a match // and successfully randomizes v. func (fc *fuzzerContext) tryCustom(v reflect.Value) bool { // First: see if we have a fuzz function for it. doCustom, ok := fc.fuzzer.fuzzFuncs[v.Type()] if !ok { // Second: see if it can fuzz itself. if v.CanInterface() { intf := v.Interface() if fuzzable, ok := intf.(Interface); ok { fuzzable.Fuzz(Continue{fc: fc, Rand: fc.fuzzer.r}) return true } } // Finally: see if there is a default fuzz function. doCustom, ok = fc.fuzzer.defaultFuzzFuncs[v.Type()] if !ok { return false } } switch v.Kind() { case reflect.Ptr: if v.IsNil() { if !v.CanSet() { return false } v.Set(reflect.New(v.Type().Elem())) } case reflect.Map: if v.IsNil() { if !v.CanSet() { return false } v.Set(reflect.MakeMap(v.Type())) } default: return false } doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ fc: fc, Rand: fc.fuzzer.r, })}) return true } // Interface represents an object that knows how to fuzz itself. Any time we // find a type that implements this interface we will delegate the act of // fuzzing itself. type Interface interface { Fuzz(c Continue) } // Continue can be passed to custom fuzzing functions to allow them to use // the correct source of randomness and to continue fuzzing their members. type Continue struct { fc *fuzzerContext // For convenience, Continue implements rand.Rand via embedding. // Use this for generating any randomness if you want your fuzzing // to be repeatable for a given seed. *rand.Rand } // Fuzz continues fuzzing obj. obj must be a pointer. func (c Continue) Fuzz(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() c.fc.doFuzz(v, 0) } // FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for // obj's type will not be called and obj will not be tested for fuzz.Interface // conformance. This applies only to obj and not other instances of obj's // type. func (c Continue) FuzzNoCustom(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() c.fc.doFuzz(v, flagNoCustomFuzz) } // RandString makes a random string up to 20 characters long. The returned string // may include a variety of (valid) UTF-8 encodings. func (c Continue) RandString() string { return randString(c.Rand) } // RandUint64 makes random 64 bit numbers. // Weirdly, rand doesn't have a function that gives you 64 random bits. func (c Continue) RandUint64() uint64 { return randUint64(c.Rand) } // RandBool returns true or false randomly. func (c Continue) RandBool() bool { return randBool(c.Rand) } func fuzzInt(v reflect.Value, r *rand.Rand) { v.SetInt(int64(randUint64(r))) } func fuzzUint(v reflect.Value, r *rand.Rand) { v.SetUint(randUint64(r)) } func fuzzTime(t *time.Time, c Continue) { var sec, nsec int64 // Allow for about 1000 years of random time values, which keeps things // like JSON parsing reasonably happy. sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60) c.Fuzz(&nsec) *t = time.Unix(sec, nsec) } var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){ reflect.Bool: func(v reflect.Value, r *rand.Rand) { v.SetBool(randBool(r)) }, reflect.Int: fuzzInt, reflect.Int8: fuzzInt, reflect.Int16: fuzzInt, reflect.Int32: fuzzInt, reflect.Int64: fuzzInt, reflect.Uint: fuzzUint, reflect.Uint8: fuzzUint, reflect.Uint16: fuzzUint, reflect.Uint32: fuzzUint, reflect.Uint64: fuzzUint, reflect.Uintptr: fuzzUint, reflect.Float32: func(v reflect.Value, r *rand.Rand) { v.SetFloat(float64(r.Float32())) }, reflect.Float64: func(v reflect.Value, r *rand.Rand) { v.SetFloat(r.Float64()) }, reflect.Complex64: func(v reflect.Value, r *rand.Rand) { panic("unimplemented") }, reflect.Complex128: func(v reflect.Value, r *rand.Rand) { panic("unimplemented") }, reflect.String: func(v reflect.Value, r *rand.Rand) { v.SetString(randString(r)) }, reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) { panic("unimplemented") }, } // randBool returns true or false randomly. func randBool(r *rand.Rand) bool { if r.Int()&1 == 1 { return true } return false } type charRange struct { first, last rune } // choose returns a random unicode character from the given range, using the // given randomness source. func (r *charRange) choose(rand *rand.Rand) rune { count := int64(r.last - r.first) return r.first + rune(rand.Int63n(count)) } var unicodeRanges = []charRange{ {' ', '~'}, // ASCII characters {'\u00a0', '\u02af'}, // Multi-byte encoded characters {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings) } // randString makes a random string up to 20 characters long. The returned string // may include a variety of (valid) UTF-8 encodings. func randString(r *rand.Rand) string { n := r.Intn(20) runes := make([]rune, n) for i := range runes { runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r) } return string(runes) } // randUint64 makes random 64 bit numbers. // Weirdly, rand doesn't have a function that gives you 64 random bits. func randUint64(r *rand.Rand) uint64 { return uint64(r.Uint32())<<32 | uint64(r.Uint32()) }
{ "pile_set_name": "Github" }
#!/usr/bin/env ruby # This file is part of Metasm, the Ruby assembly manipulation suite # Copyright (C) 2006-2009 Yoann GUILLOT # # Licence is LGPL, see LICENCE in the top-level directory # # this sample shows how to compile an executable file from source # use --exe PE to compile a PE/ELF/MachO etc # use --cpu MIPS/--16/--be to change the CPU # the arg is a source file (c or asm) (some arch may not yet support C compiling) # defaults to encoding a shellcode, use --exe to override (or the scripts samples/{elf,pe}encode) # to compile a shellcode to a cstring, use --cstring # require 'metasm' require 'optparse' $opts ||= {} $opts = { :execlass => Metasm::Shellcode, :cpu => Metasm::Ia32.new, :exetype => :bin, :macros => {} }.merge($opts) OptionParser.new { |opt| opt.on('-o file', 'output filename') { |f| $opts[:outfilename] = f } opt.on('-i', 'dont overwrite existing outfile') { $opts[:nooverwrite_outfile] = true } opt.on('-f', 'overwrite existing outfile (default)') { $opts.delete :nooverwrite_outfile } # without this, optparse autocomplete to --fno-pic and break older scripts... opt.on('--c', 'parse source as a C file') { $opts[:srctype] = 'c' } opt.on('--asm', 'parse asm as an ASM file') { $opts[:srctype] = 'asm' } opt.on('--stdin', 'parse source on stdin') { ARGV << '-' } opt.on('-v', '-W', 'verbose') { $VERBOSE=true } opt.on('-d', 'debug') { $DEBUG=$VERBOSE=true } opt.on('-D var=val', 'define a preprocessor macro') { |v| v0, v1 = v.split('=', 2) ; $opts[:macros][v0] = v1 } opt.on('--cstring', 'encode output as a C string') { $opts[:to_string] = :c } opt.on('--jsstring', 'encode output as a js string') { $opts[:to_string] = :js } opt.on('--string', 'encode output as a string to stdout') { $opts[:to_string] = :inspect } opt.on('--varname name', 'the variable name for string output') { |v| $opts[:varname] = v } opt.on('-e class', '--exe class', 'use a specific ExeFormat class') { |c| $opts[:execlass] = Metasm.const_get(c) } opt.on('--cpu cpu', 'use a specific CPU class') { |c| $opts[:cpu] = Metasm.const_get(c).new } # must come after --cpu in commandline opt.on('--16', 'set cpu in 16bit mode') { $opts[:cpu].size = 16 } opt.on('--le', 'set cpu in little-endian mode') { $opts[:cpu].endianness = :little } opt.on('--be', 'set cpu in big-endian mode') { $opts[:cpu].endianness = :big } opt.on('--fno-pic', 'generate position-dependant code') { $opts[:cpu].generate_PIC = false } opt.on('--shared', '--lib', '--dll', 'generate shared library') { $opts[:exetype] = :lib } opt.on('--ruby-module-hack', 'use the dynldr module hack to use any ruby lib available for ruby symbols') { $opts[:dldrhack] = true } }.parse! src = $opts[:macros].map { |k, v| "#define #{k} #{v}\n" }.join if file = ARGV.shift $opts[:srctype] ||= 'c' if file =~ /\.c$/ if file == '-' src << $stdin.read else src << File.read(file) end else $opts[:srctype] ||= $opts[:srctype_data] src << DATA.read # the text after __END__ in this file end if $opts[:outfilename] and $opts[:nooverwrite_outfile] and File.exist?($opts[:outfilename]) abort "Error: target file exists !" end if $opts[:srctype] == 'c' exe = $opts[:execlass].compile_c($opts[:cpu], src, file) else exe = $opts[:execlass].assemble($opts[:cpu], src, file) end if $opts[:to_string] str = exe.encode_string $opts[:varname] ||= File.basename(file.to_s)[/^\w+/] || 'sc' # derive varname from filename case $opts[:to_string] when :inspect str = "#{$opts[:varname]} = #{str.inspect}" when :c str = ["unsigned char #{$opts[:varname]}[#{str.length}] = "] + str.scan(/.{1,19}/m).map { |l| '"' + l.unpack('C*').map { |c| '\\x%02x' % c }.join + '"' } str.last << ?; when :js str << 0 if str.length & 1 != 0 str = ["#{$opts[:varname]} = "] + str.scan(/.{2,20}/m).map { |l| '"' + l.unpack($opts[:cpu].endianness == :little ? 'v*' : 'n*').map { |c| '%%u%04x' % c }.join + '"+' } str.last[-1] = ?; end if of = $opts[:outfilename] abort "Error: target file #{of.inspect} exists !" if File.exist?(of) and $opts[:nooverwrite_outfile] File.open(of, 'w') { |fd| fd.puts str } puts "saved to file #{of.inspect}" else puts str end else of = $opts[:outfilename] ||= 'a.out' abort "Error: target file #{of.inspect} exists !" if File.exist?(of) and $opts[:nooverwrite_outfile] Metasm::DynLdr.compile_binary_module_hack(exe) if $opts[:dldrhack] exe.encode_file(of, $opts[:exetype]) puts "saved to file #{of.inspect}" end __END__ #include <asm/unistd.h> jmp getip gotip: mov eax, __NR_write mov ebx, 1 pop ecx mov edx, strend-str int 80h mov eax, __NR_exit mov ebx, 1 int 80h getip: call gotip str db "Hello, world!", 0xa strend:
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -E %s > %t.src.cpp // RUN: %clang_cc1 -E %s > %t.dst.cpp -DDEST // RUN: clang-diff -dump-matches -s=10 %t.src.cpp %t.dst.cpp -- | FileCheck %s // // Test the behaviour of the matching according to the optimal tree edit // distance, implemented with Zhang and Shasha's algorithm. // Just for testing we use a tiny value of 10 for maxsize. Subtrees bigger than // this size will not be processed by the optimal algorithm. #ifndef DEST void f1() { {;} {{;}} } void f2() { {;} {{;;;;;}} } void f3() { {;} {{;;;;;;}} } #else void f1() { // Jaccard similarity = 3 / (5 + 4 - 3) = 3 / 6 >= 0.5 // The optimal matching algorithm should move the ; into the outer block // CHECK: Match CompoundStmt(2) to CompoundStmt(2) // CHECK-NOT: Match CompoundStmt(3) // CHECK-NEXT: Match NullStmt(4) to NullStmt(3) ; {{;}} } void f2() { // Jaccard similarity = 7 / (10 + 10 - 7) >= 0.5 // As none of the subtrees is bigger than 10 nodes, the optimal algorithm // will be run. // CHECK: Match NullStmt(11) to NullStmt(9) ;; {{;;;;;}} } void f3() { // Jaccard similarity = 8 / (11 + 11 - 8) >= 0.5 // As the subtrees are bigger than 10 nodes, the optimal algorithm will not // be run. // CHECK: Delete NullStmt(22) ;; {{;;;;;;}} } #endif
{ "pile_set_name": "Github" }
declare module '*.vue' { import Vue from 'vue' export default Vue }
{ "pile_set_name": "Github" }
{ "accountLinkingWhitelistedDomains": null, "asin": "B01M60PZYT", "averageRating": 0, "canDisable": true, "capabilities": null, "category": null, "description": "Here is a list of fun solar power facts! They range from scientific to historical, and are an interesting insight into how we use the most abundant source of energy today.", "enablement": null, "exampleInteractions": [ "Alexa, start my solar power facts", "", "" ], "firstReleaseDate": 1476196929.305, "homepageLinkText": null, "homepageLinkUrl": null, "id": "amzn1.ask.skill.6b2ec9e8-2096-476c-ab24-4be4b204b538", "imageAltText": "my solar power facts icon", "imageUrl": "https://github.com/dale3h/alexa-skills-list/raw/master/skills/B01M60PZYT/skill_icon", "inAppPurchasingSupported": false, "launchPhrase": "my solar power facts", "name": "my solar power facts", "numberOfReviews": 0, "pamsPartnerId": null, "permissions": null, "privacyPolicyUrl": null, "shortDescription": "Solar Power Facts", "skillTypes": null, "stage": "live", "termsOfUseUrl": null, "vendorId": "M10NL1BPBI8AWP", "vendorName": "Shanee Ossa" }
{ "pile_set_name": "Github" }
/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ZORBA_RUNTIME_GFLWOR_GROUPBY #define ZORBA_RUNTIME_GFLWOR_GROUPBY #include "zorbautils/checked_vector.h" #include "common/shared_types.h" #include "runtime/base/plan_iterator.h" #include "runtime/core/gflwor/common.h" namespace zorba { namespace flwor { class GroupByIterator; /***************************************************************************//** ********************************************************************************/ class GroupByState : public PlanIteratorState { friend class GroupByIterator; protected: GroupHashMap * theGroupMap; GroupHashMap::iterator theGroupMapIter; public: GroupByState(); ~GroupByState(); void init( PlanState& aState, const TypeManager* tm, const QueryLoc& loc, std::vector<GroupingSpec>* gspecs); void reset(PlanState& state); }; /***************************************************************************//** ********************************************************************************/ class GroupByIterator : public PlanIterator { private: PlanIter_t theTupleIter; std::vector<GroupingSpec> theGroupingSpecs; std::vector<NonGroupingSpec> theNonGroupingSpecs; public: SERIALIZABLE_CLASS(GroupByIterator) SERIALIZABLE_CLASS_CONSTRUCTOR2(GroupByIterator, PlanIterator) void serialize(::zorba::serialization::Archiver& ar); public: GroupByIterator( static_context* sctx, const QueryLoc& loc, PlanIter_t aTupleIterator, std::vector<GroupingSpec> aGroupingSpecs, std::vector<NonGroupingSpec> aNonGroupingSpecs); ~GroupByIterator(); zstring getNameAsString() const; uint32_t getStateSize() const; uint32_t getStateSizeOfSubtree() const; void accept(PlanIterVisitor&) const; void openImpl(PlanState& planState, uint32_t& offset); bool nextImpl(store::Item_t& result, PlanState& planState) const; void resetImpl(PlanState& planState) const; void closeImpl(PlanState& planState); private: void matVarsAndGroupBy( GroupByState* aGroupByState, PlanState& aPlanState) const; void bindGroupBy( GroupHashMap::iterator aGroupMapIter, GroupByState* aGroupByState, PlanState& aPlanState) const; }; }//namespace gflwor } //namespace zorba #endif /* ZORBA_RUNTIME_GFLWOR_GROUPBY */ /* * Local variables: * mode: c++ * End: */ /* vim:set et sw=2 ts=2: */
{ "pile_set_name": "Github" }
<% content_for :javascript do %> <%= tinymce_assets %> <% end %> <h1>TinyMCE Helpers</h1> <ul> <li><%= link_to 'Back to index', root_path %></li> <% if params[:locale] == "es" %> <li><%= link_to 'Switch to English', :locale => nil %></li> <% else %> <li><%= link_to 'Switch to Spanish', :locale => "es" %></li> <% end %> </ul> <%= text_area_tag :editor1, "", :class => "tinymce", :rows => 20, :cols => 60 %> <%= text_area_tag :editor2, "", :class => "tinymce", :rows => 20, :cols => 60 %> <%= tinymce :selector => "#editor1", :language => I18n.locale %> <%= tinymce :custom, :selector => "#editor2", :language => I18n.locale %>
{ "pile_set_name": "Github" }
#include "kvp_logger_interface.h" #include "kvp_logger_void.h" #include <boost/property_tree/json_parser.hpp> namespace Datacratic{ std::shared_ptr<IKvpLogger> IKvpLogger ::kvpLoggerFactory(const std::string& type, const KvpLoggerParams& params){ if (type == "void"){ return std::shared_ptr<IKvpLogger>(new KvpLoggerVoid()); }else if(type == "metricsLogger"){ } throw ML::Exception("Unknown KvpLogger [" + type + "]"); } std::shared_ptr<IKvpLogger> IKvpLogger ::kvpLoggerFactory(const std::string& configKey){ using namespace boost::property_tree; using namespace std; ptree pt; json_parser::read_json(getenv("CONFIG"), pt); pt = pt.get_child(configKey); string type = pt.get<string>("type"); if(type == "void"){ } throw ML::Exception("Unknown KvpLogger [" + type + "]"); } }
{ "pile_set_name": "Github" }
import {Model} from 'backbone'; import LocalStorage from 'lib/backbone.localStorage'; import ChromeCommand from 'background/enum/chromeCommand'; var ShuffleButton = Model.extend({ localStorage: new LocalStorage('ShuffleButton'), defaults: { // Need to set the ID for Backbone.LocalStorage id: 'ShuffleButton', enabled: false }, initialize: function() { // Load from Backbone.LocalStorage this.fetch(); chrome.commands.onCommand.addListener(this._onChromeCommandsCommand.bind(this)); }, toggleEnabled: function() { this.save({ enabled: !this.get('enabled') }); }, getStateMessage: function() { var isEnabled = this.get('enabled'); var stateMessage = chrome.i18n.getMessage(isEnabled ? 'shufflingOn' : 'shufflingOff'); return stateMessage; }, _onChromeCommandsCommand: function(command) { if (command === ChromeCommand.ToggleShuffle) { this.toggleEnabled(); StreamusBG.channels.backgroundNotification.commands.trigger('show:notification', { message: this.getStateMessage() }); } } }); export default ShuffleButton;
{ "pile_set_name": "Github" }
diff --git a/third_party/blink/renderer/core/page/plugin_data.h b/third_party/blink/renderer/core/page/plugin_data.h index fe5aa20243d89ea6a0f1cecb5ea00846607c6d39..7363a4dab1c30ab26fc57b2d546b77564b359e0b 100644 --- a/third_party/blink/renderer/core/page/plugin_data.h +++ b/third_party/blink/renderer/core/page/plugin_data.h @@ -1,4 +1,3 @@ - /* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) @@ -76,6 +75,7 @@ class CORE_EXPORT PluginInfo final : public GarbageCollected<PluginInfo> { Color BackgroundColor() const { return background_color_; } bool MayUseExternalHandler() const { return may_use_external_handler_; } + BRAVE_PLUGIN_DATA_H private: friend class MimeClassInfo; friend class PluginData;
{ "pile_set_name": "Github" }
# Shadow DOM Shadow DOM serves for encapsulation. It allows a component to have its very own "shadow" DOM tree, that can't be accidentally accessed from the main document, may have local style rules, and more. ## Built-in shadow DOM Did you ever think how complex browser controls are created and styled? Such as `<input type="range">`: <p> <input type="range"> </p> The browser uses DOM/CSS internally to draw them. That DOM structure is normally hidden from us, but we can see it in developer tools. E.g. in Chrome, we need to enable in Dev Tools "Show user agent shadow DOM" option. Then `<input type="range">` looks like this: ![](shadow-dom-range.png) What you see under `#shadow-root` is called "shadow DOM". We can't get built-in shadow DOM elements by regular JavaScript calls or selectors. These are not regular children, but a powerful encapsulation technique. In the example above, we can see a useful attribute `pseudo`. It's non-standard, exists for historical reasons. We can use it style subelements with CSS, like this: ```html run autorun <style> /* make the slider track red */ input::-webkit-slider-runnable-track { background: red; } </style> <input type="range"> ``` Once again, `pseudo` is a non-standard attribute. Chronologically, browsers first started to experiment with internal DOM structures to implement controls, and then, after time, shadow DOM was standardized to allow us, developers, to do the similar thing. Further on, we'll use the modern shadow DOM standard, covered by [DOM spec](https://dom.spec.whatwg.org/#shadow-trees) other related specifications. ## Shadow tree A DOM element can have two types of DOM subtrees: 1. Light tree -- a regular DOM subtree, made of HTML children. All subtrees that we've seen in previous chapters were "light". 2. Shadow tree -- a hidden DOM subtree, not reflected in HTML, hidden from prying eyes. If an element has both, then the browser renders only the shadow tree. But we can setup a kind of composition between shadow and light trees as well. We'll see the details later in the chapter <info:slots-composition>. Shadow tree can be used in Custom Elements to hide component internals and apply component-local styles. For example, this `<show-hello>` element hides its internal DOM in shadow tree: ```html run autorun height=60 <script> customElements.define('show-hello', class extends HTMLElement { connectedCallback() { const shadow = this.attachShadow({mode: 'open'}); shadow.innerHTML = `<p> Hello, ${this.getAttribute('name')} </p>`; } }); </script> <show-hello name="John"></show-hello> ``` That's how the resulting DOM looks in Chrome dev tools, all the content is under "#shadow-root": ![](shadow-dom-say-hello.png) First, the call to `elem.attachShadow({mode: …})` creates a shadow tree. There are two limitations: 1. We can create only one shadow root per element. 2. The `elem` must be either a custom element, or one of: "article", "aside", "blockquote", "body", "div", "footer", "h1..h6", "header", "main" "nav", "p", "section", or "span". Other elements, like `<img>`, can't host shadow tree. The `mode` option sets the encapsulation level. It must have any of two values: - `"open"` -- the shadow root is available as `elem.shadowRoot`. Any code is able to access the shadow tree of `elem`. - `"closed"` -- `elem.shadowRoot` is always `null`. We can only access the shadow DOM by the reference returned by `attachShadow` (and probably hidden inside a class). Browser-native shadow trees, such as `<input type="range">`, are closed. There's no way to access them. The [shadow root](https://dom.spec.whatwg.org/#shadowroot), returned by `attachShadow`, is like an element: we can use `innerHTML` or DOM methods, such as `append`, to populate it. The element with a shadow root is called a "shadow tree host", and is available as the shadow root `host` property: ```js // assuming {mode: "open"}, otherwise elem.shadowRoot is null alert(elem.shadowRoot.host === elem); // true ``` ## Encapsulation Shadow DOM is strongly delimited from the main document: 1. Shadow DOM elements are not visible to `querySelector` from the light DOM. In particular, Shadow DOM elements may have ids that conflict with those in the light DOM. They must be unique only within the shadow tree. 2. Shadow DOM has own stylesheets. Style rules from the outer DOM don't get applied. For example: ```html run untrusted height=40 <style> *!* /* document style won't apply to the shadow tree inside #elem (1) */ */!* p { color: red; } </style> <div id="elem"></div> <script> elem.attachShadow({mode: 'open'}); *!* // shadow tree has its own style (2) */!* elem.shadowRoot.innerHTML = ` <style> p { font-weight: bold; } </style> <p>Hello, John!</p> `; *!* // <p> is only visible from queries inside the shadow tree (3) */!* alert(document.querySelectorAll('p').length); // 0 alert(elem.shadowRoot.querySelectorAll('p').length); // 1 </script> ``` 1. The style from the document does not affect the shadow tree. 2. ...But the style from the inside works. 3. To get elements in shadow tree, we must query from inside the tree. ## References - DOM: <https://dom.spec.whatwg.org/#shadow-trees> - Compatibility: <https://caniuse.com/#feat=shadowdomv1> - Shadow DOM is mentioned in many other specifications, e.g. [DOM Parsing](https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin) specifies that shadow root has `innerHTML`. ## Summary Shadow DOM is a way to create a component-local DOM. 1. `shadowRoot = elem.attachShadow({mode: open|closed})` -- creates shadow DOM for `elem`. If `mode="open"`, then it's accessible as `elem.shadowRoot` property. 2. We can populate `shadowRoot` using `innerHTML` or other DOM methods. Shadow DOM elements: - Have their own ids space, - Invisible to JavaScript selectors from the main document, such as `querySelector`, - Use styles only from the shadow tree, not from the main document. Shadow DOM, if exists, is rendered by the browser instead of so-called "light DOM" (regular children). In the chapter <info:slots-composition> we'll see how to compose them.
{ "pile_set_name": "Github" }
/* * CPView+Border.j * * Copyright (C) 2010 Antoine Mercadal <[email protected]> * 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/>. */ @import <AppKit/CPView.j> /*! @ingroup categories Categories that allows CPView with border */ @implementation CPView (BorderedView) - (void)setBordered { self._DOMElement.style.border = "1px solid black"; } - (void)setBorderedWithHexColor:(CPString)aHexColor { self._DOMElement.style.border = "1px solid " + aHexColor; } - (void)setBorderRadius:(int)aRadius { self._DOMElement.style.borderRadius = aRadius + "px"; } @end
{ "pile_set_name": "Github" }
-- DELETE FROM creature_model_info WHERE `DisplayID` IN (60891, 64194, 62895, 62427, 62900, 62398, 62896, 64118, 63037, 61795, 62249, 63277, 62248, 63274, 63271, 63269, 63268, 64462, 63158, 63137, 63135, 62027, 63159, 62116, 61923, 62033, 62115, 64128, 61820, 64722, 61838, 61837, 64771, 64136, 61981, 61832, 61831, 61867, 61787, 61878, 61788, 63745, 61822, 61856, 62142, 62057, 62058, 62126, 64133, 62002, 63349, 62000, 64434, 63278, 63245, 63244, 63213, 63248, 63280, 63211, 63303, 63290, 62114, 62117, 62034, 62620, 63083, 62019, 62018, 63167, 62017, 62020, 63084, 62042, 63368, 63366, 63365, 63424, 64435, 64436, 64437, 63206, 61755, 61756, 61757, 64129, 61775, 61776, 63079, 63080, 63078, 64127, 63283, 63150, 62853, 63691, 63718, 61995, 61985, 61940, 61943); INSERT INTO creature_model_info (`DisplayID`, `BoundingRadius`, `CombatReach`, `DisplayID_Other_Gender`) VALUES (60891, 0.0525, 0.15, 0), -- 60891 (64194, 0.062, 0.2, 0), -- 64194 (62895, 0.5394, 2.175, 0), -- 62895 (62427, 0.5394, 2.175, 0), -- 62427 (62900, 0.5952, 2.4, 0), -- 62900 (62398, 0.5394, 2.175, 0), -- 62398 (62896, 0.5394, 2.175, 0), -- 62896 (64118, 0.03, 0.15, 0), -- 64118 (63037, 0.525, 0.875, 0), -- 63037 (61795, 0.39, 1.5, 0), -- 61795 (62249, 0.208, 1.5, 0), -- 62249 (63277, 0.347222, 1.5, 0), -- 63277 (62248, 0.306, 1.5, 0), -- 62248 (63274, 0.389, 1.5, 0), -- 63274 (63271, 0.459, 2.25, 0), -- 63271 (63269, 0.2912, 2.1, 0), -- 63269 (63268, 0.5362, 2.1, 0), -- 63268 (64462, 0.306, 1.5, 0), -- 64462 (63158, 1, 1.5, 0), -- 63158 (63137, 1.75, 2.625, 0), -- 63137 (63135, 1.75, 2.625, 0), -- 63135 (62027, 1.05, 1.5, 0), -- 62027 (63159, 1, 1.5, 0), -- 63159 (62116, 1, 1.5, 0), -- 62116 (61923, 1, 1.5, 0), -- 61923 (62033, 1.2, 1.8, 0), -- 62033 (62115, 1, 1.5, 0), -- 62115 (64128, 0.5, 0.75, 0), -- 64128 (61820, 0.4836, 1.95, 0), -- 61820 (64722, 0.5, 5, 0), -- 64722 (61838, 0.2714, 1.725, 0), -- 61838 (61837, 0.4278, 1.725, 0), -- 61837 (64771, 0.372, 1.5, 0), -- 64771 (64136, 0.35, 0.875, 0), -- 64136 (61981, 1.528, 4, 0), -- 61981 (61832, 0.4092, 1.65, 0), -- 61832 (61831, 0.4092, 1.65, 0), -- 61831 (61867, 0.93, 3.75, 0), -- 61867 (61787, 0.4464, 1.8, 0), -- 61787 (61878, 0.465, 1.875, 0), -- 61878 (61788, 0.4092, 1.65, 0), -- 61788 (63745, 0.537204, 1.5, 0), -- 63745 (61822, 0.4836, 1.95, 0), -- 61822 (61856, 0.35, 4.2, 0), -- 61856 (62142, 0.744, 3, 0), -- 62142 (62057, 0.6, 3, 0), -- 62057 (62058, 0.6, 3, 0), -- 62058 (62126, 0.137779, 1.5, 0), -- 62126 (64133, 0.0465, 1.8, 0), -- 64133 (62002, 0.2832, 1.8, 0), -- 62002 (63349, 0.3519, 1.725, 0), -- 63349 (62000, 0.2832, 1.8, 0), -- 62000 (64434, 0.6511, 2.55, 0), -- 64434 (63278, 0.9, 1.35, 0), -- 63278 (63245, 0.2124, 1.35, 0), -- 63245 (63244, 0.236, 1.5, 0), -- 63244 (63213, 0.9, 1.35, 0), -- 63213 (63248, 0.3348, 1.35, 0), -- 63248 (63280, 0.9, 1.35, 0), -- 63280 (63211, 0.9, 1.35, 0), -- 63211 (63303, 0.3348, 1.35, 0), -- 63303 (63290, 0.9, 1.35, 0), -- 63290 (62114, 1, 1.5, 0), -- 62114 (62117, 1, 1.5, 0), -- 62117 (62034, 1.2, 1.8, 0), -- 62034 (62620, 0.375, 1.5, 0), -- 62620 (63083, 1, 1.5, 0), -- 63083 (62019, 1, 1.5, 0), -- 62019 (62018, 1, 1.5, 0), -- 62018 (63167, 0.75, 0.75, 0), -- 63167 (62017, 1, 1.5, 0), -- 62017 (62020, 1, 1.5, 0), -- 62020 (63084, 1, 1.5, 0), -- 63084 (62042, 15, 1.5, 0), -- 62042 (63368, 0.4, 0.4, 0), -- 63368 (63366, 0.3, 0.3, 0), -- 63366 (63365, 0.4, 0.4, 0), -- 63365 (63424, 0.591, 1.5, 0), -- 63424 (64435, 2.5, 3.125, 0), -- 64435 (64436, 2.25, 2.8125, 0), -- 64436 (64437, 2, 2.5, 0), -- 64437 (63206, 0.69, 2.76, 0), -- 63206 (61755, 0.5022, 2.025, 0), -- 61755 (61756, 0.5208, 2.1, 0), -- 61756 (61757, 0.3422, 2.175, 0), -- 61757 (64129, 0.1085, 0.35, 0), -- 64129 (61775, 0.45, 2.25, 0), -- 61775 (61776, 0.45, 2.25, 0), -- 61776 (63079, 0.6, 3, 0), -- 63079 (63080, 0.69, 3.45, 0), -- 63080 (63078, 0.9, 4.5, 0), -- 63078 (64127, 0.35, 0.35, 0), -- 64127 (63283, 0.306, 1.5, 0), -- 63283 (63150, 0.611112, 10, 0), -- 63150 (62853, 0.306, 1.5, 0), -- 62853 (63691, 0.3, 0.375, 0), -- 63691 (63718, 0.625, 1.25, 0), -- 63718 (61995, 0.306, 1.5, 0), -- 61995 (61985, 0.306, 1.5, 0), -- 61985 (61940, 1, 5, 0), -- 61940 (61943, 1, 1.5, 0); -- 61943
{ "pile_set_name": "Github" }
/* This file is part of Darling. Copyright (C) 2017 Lubos Dolezel Darling 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. Darling 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 Darling. If not, see <http://www.gnu.org/licenses/>. */ #include <Foundation/Foundation.h> @protocol HasAuxiliaryConnection @end
{ "pile_set_name": "Github" }
// DATA_TEMPLATE: empty_table oTest.fnStart( "Custom data source property - property given" ); $(document).ready( function () { var oInit = { "sAjaxSource": "../../../examples/ajax/sources/custom_prop.txt", "sAjaxDataProp": "demo" }; $('#example').dataTable( oInit ); oTest.fnWaitTest( "10 rows shown on the first page", null, function () { return $('#example tbody tr').length == 10; } ); oTest.fnTest( "Initial sort occured", null, function () { return $('#example tbody td:eq(0)').html() == "Gecko"; } ); /* Need to use the WaitTest for sorting due to the setTimeout datatables uses */ oTest.fnTest( "Sorting (first click) on second column", function () { $('#example thead th:eq(1)').click(); }, function () { return $('#example tbody td:eq(1)').html() == "All others"; } ); oTest.fnTest( "Sorting (second click) on second column", function () { $('#example thead th:eq(1)').click(); }, function () { return $('#example tbody td:eq(1)').html() == "Seamonkey 1.1"; } ); oTest.fnTest( "Sorting (third click) on second column", function () { $('#example thead th:eq(1)').click(); }, function () { return $('#example tbody td:eq(1)').html() == "All others"; } ); oTest.fnTest( "Sorting (first click) on numeric column", function () { $('#example thead th:eq(3)').click(); }, function () { return $('#example tbody td:eq(3)').html() == "-"; } ); oTest.fnTest( "Sorting (second click) on numeric column", function () { $('#example thead th:eq(3)').click(); }, function () { return $('#example tbody td:eq(3)').html() == "522.1"; } ); oTest.fnTest( "Sorting multi-column (first click)", function () { $('#example thead th:eq(0)').click(); oDispacher.click( $('#example thead th:eq(1)')[0], { 'shift': true } ); }, function () { var b = $('#example tbody td:eq(0)').html() == "Gecko" && $('#example tbody td:eq(1)').html() == "Camino 1.0"; return b; } ); oTest.fnTest( "Sorting multi-column - sorting second column only", function () { $('#example thead th:eq(1)').click(); }, function () { return $('#example tbody td:eq(1)').html() == "All others"; } ); /* Basic paging */ oTest.fnTest( "Paging to second page", function () { $('#example_next').click(); }, function () { return $('#example tbody td:eq(1)').html() == "IE Mobile"; } ); oTest.fnTest( "Paging to first page", function () { $('#example_previous').click(); }, function () { return $('#example tbody td:eq(1)').html() == "All others"; } ); oTest.fnTest( "Attempting to page back beyond the first page", function () { $('#example_previous').click(); }, function () { return $('#example tbody td:eq(1)').html() == "All others"; } ); /* Changing length */ oTest.fnTest( "Changing table length to 25 records", function () { $("select[name=example_length]").val('25').change(); }, function () { return $('#example tbody tr').length == 25; } ); oTest.fnTest( "Changing table length to 50 records", function () { $("select[name=example_length]").val('50').change(); }, function () { return $('#example tbody tr').length == 50; } ); oTest.fnTest( "Changing table length to 100 records", function () { $("select[name=example_length]").val('100').change(); }, function () { return $('#example tbody tr').length == 57; } ); oTest.fnTest( "Changing table length to 10 records", function () { $("select[name=example_length]").val('10').change(); }, function () { return $('#example tbody tr').length == 10; } ); /* * Information element */ oTest.fnTest( "Information on zero config", null, function () { return document.getElementById('example_info').innerHTML == "Showing 1 to 10 of 57 entries"; } ); oTest.fnTest( "Information on second page", function () { $('#example_next').click(); }, function () { return document.getElementById('example_info').innerHTML == "Showing 11 to 20 of 57 entries"; } ); oTest.fnTest( "Information on third page", function () { $('#example_next').click(); }, function () { return document.getElementById('example_info').innerHTML == "Showing 21 to 30 of 57 entries"; } ); oTest.fnComplete(); } );
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration" xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd"> <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"/> <cxf:bus> <cxf:features> <cxf:logging/> </cxf:features> <cxf:properties> <entry key="org.apache.cxf.jaxrs.bus.providers" value-ref="busProviders"/> </cxf:properties> </cxf:bus> <!-- providers --> <util:list id="busProviders"> <ref bean="oauthJson"/> </util:list> <bean id="oauthJson" class="org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider"/> <httpj:engine-factory id="tls-config"> <httpj:engine port="${testutil.ports.jaxrs-oauth2-filtersJwt}"> <httpj:tlsServerParameters> <sec:keyManagers keyPassword="password"> <sec:keyStore type="JKS" password="password" resource="keys/Bethal.jks"/> </sec:keyManagers> <sec:trustManagers> <sec:keyStore type="JKS" password="password" resource="keys/Truststore.jks"/> </sec:trustManagers> <sec:clientAuthentication want="true" required="true"/> </httpj:tlsServerParameters> <httpj:sessionSupport>true</httpj:sessionSupport> </httpj:engine> </httpj:engine-factory> <bean id="serviceBean" class="org.apache.cxf.systest.jaxrs.security.jose.BookStore"/> <bean id="jackson" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/> <bean id="tvServiceClientFactory" class="org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean"> <property name="address" value="https://localhost:${testutil.ports.jaxrs-oauth2-serviceJwt}/services/validate"/> <property name="headers"> <map> <entry key="Accept" value="application/json"/> <entry key="Content-Type" value="application/x-www-form-urlencoded"/> </map> </property> <property name="providers"> <list> <ref bean="jackson"/> </list> </property> <property name="username" value="service"/> <property name="password" value="service-pass"/> </bean> <bean id="tvServiceClient" factory-bean="tvServiceClientFactory" factory-method="createWebClient"/> <bean id="tvServiceClientFactory2" class="org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean"> <property name="address" value="https://localhost:${testutil.ports.jaxrs-oauth2-serviceJwt}/services2/validate"/> <property name="headers"> <map> <entry key="Accept" value="application/json"/> <entry key="Content-Type" value="application/x-www-form-urlencoded"/> </map> </property> <property name="providers"> <list> <ref bean="jackson"/> </list> </property> <property name="username" value="service"/> <property name="password" value="service-pass"/> </bean> <bean id="tvServiceClient2" factory-bean="tvServiceClientFactory2" factory-method="createWebClient"/> <bean id="remoteTokenValidator" class="org.apache.cxf.rs.security.oauth2.filters.AccessTokenValidatorClient"> <property name="tokenValidatorClient" ref="tvServiceClient"/> </bean> <bean id="oAuthFilterRemoteValidation" class="org.apache.cxf.rs.security.oauth2.filters.OAuthRequestFilter"> <property name="tokenValidator" ref="remoteTokenValidator"/> </bean> <bean id="remoteTokenValidator2" class="org.apache.cxf.rs.security.oauth2.filters.AccessTokenValidatorClient"> <property name="tokenValidatorClient" ref="tvServiceClient2"/> </bean> <bean id="oAuthFilterRemoteValidation2" class="org.apache.cxf.rs.security.oauth2.filters.OAuthRequestFilter"> <property name="tokenValidator" ref="remoteTokenValidator2"/> </bean> <jaxrs:server depends-on="tls-config" address="https://localhost:${testutil.ports.jaxrs-oauth2-filtersJwt}/secured"> <jaxrs:serviceBeans> <ref bean="serviceBean"/> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="oAuthFilterRemoteValidation"/> </jaxrs:providers> </jaxrs:server> <jaxrs:server depends-on="tls-config" address="https://localhost:${testutil.ports.jaxrs-oauth2-filtersJwt}/secured2"> <jaxrs:serviceBeans> <ref bean="serviceBean"/> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="oAuthFilterRemoteValidation2"/> </jaxrs:providers> </jaxrs:server> <bean id="jwtTokenValidator" class="org.apache.cxf.rs.security.oauth2.filters.JwtAccessTokenValidator"/> <bean id="oAuthFilterLocalValidation" class="org.apache.cxf.rs.security.oauth2.filters.OAuthRequestFilter"> <property name="tokenValidator" ref="jwtTokenValidator"/> </bean> <jaxrs:server depends-on="tls-config" address="https://localhost:${testutil.ports.jaxrs-oauth2-filtersJwt}/securedLocalValidation"> <jaxrs:serviceBeans> <ref bean="serviceBean"/> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="oAuthFilterLocalValidation"/> </jaxrs:providers> <jaxrs:properties> <entry key="rs.security.signature.in.properties" value="org/apache/cxf/systest/jaxrs/security/alice.rs.properties"/> </jaxrs:properties> </jaxrs:server> <bean id="jwsJwksJwtAccessTokenValidator" class="org.apache.cxf.rs.security.oauth2.filters.JwsJwksJwtAccessTokenValidator"> <property name="jwksURL" value="https://localhost:${testutil.ports.jaxrs-oauth2-serviceJwt}/services/keys"/> </bean> <bean id="oAuthFilterJwsJwksValidation" class="org.apache.cxf.rs.security.oauth2.filters.OAuthRequestFilter"> <property name="tokenValidator" ref="jwsJwksJwtAccessTokenValidator"/> </bean> <jaxrs:server depends-on="tls-config" address="https://localhost:${testutil.ports.jaxrs-oauth2-filtersJwt}/securedJwsJwksValidation"> <jaxrs:serviceBeans> <ref bean="serviceBean"/> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="oAuthFilterJwsJwksValidation"/> </jaxrs:providers> </jaxrs:server> <http:conduit name="https://localhost.*"> <http:client ConnectionTimeout="3000000" ReceiveTimeout="3000000"/> <http:tlsClientParameters disableCNCheck="true"> <sec:trustManagers> <sec:keyStore type="JKS" password="password" resource="keys/Truststore.jks"/> </sec:trustManagers> </http:tlsClientParameters> <http:authorization> <sec:UserName>service</sec:UserName> <sec:Password>service-pass</sec:Password> <sec:AuthorizationType>Basic</sec:AuthorizationType> </http:authorization> </http:conduit> </beans>
{ "pile_set_name": "Github" }
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.Collections.Generic; using System.Linq; using Sce.Atf.Adaptation; using Sce.Atf.Controls; namespace Sce.Atf.Applications { using TreeNode = TreeControl.Node; using NodeFilteringStatus = TreeItemRenderer.NodeFilteringStatus; /// <summary> /// Helper class to adapt a data context that implements ITreeView to support filtering items in a tree view. /// For performance reasons, it caches the full filtered tree view after applying a filter.</summary> public class FilteredTreeView : ITreeView,IItemView, IAdaptable, IDecoratable { /// <summary> /// Constructor</summary> /// <param name="treeView">Data context of ITreeView to apply a filter</param> /// <param name="filterFunc">Callback to determine if an item in the tree is filtered in (return true) or out</param> public FilteredTreeView(ITreeView treeView, Predicate<object> filterFunc) { m_treeView = treeView; m_itemView = treeView.As<IItemView>(); if (filterFunc == null) throw new ArgumentNullException("filterFunc cannot be null"); m_filterFunc = filterFunc; } /// <summary> /// Indicates whether two ITreeView instances are equal</summary> /// <param name="first">First ITreeView to compare</param> /// <param name="second">Second ITreeView to compare</param> /// <returns>True iff ITreeView instances are equal</returns> public static bool Equals(ITreeView first, ITreeView second) { FilteredTreeView f1 = first.As<FilteredTreeView>(); if (f1 != null) first = f1.m_treeView; FilteredTreeView f2 = second.As<FilteredTreeView>(); if (f2 != null) second = f2.m_treeView; return first == second; } #region ITreeView Members /// <summary> /// Gets tree root</summary> public object Root { get { return m_treeView.Root; } } /// <summary> /// Gets parent's children</summary> /// <param name="parent">Parent</param> /// <returns>Children objects</returns> public IEnumerable<object> GetChildren(object parent) { var unfiltered = m_treeView.GetChildren(parent); if (IsFiltering && !m_exemptedSet.Contains(parent)) return unfiltered.Where(item => IsMatched(item) || m_exemptedSet.Contains(item)); return unfiltered; } internal NodeFilteringStatus GetNodeFilteringStatus(TreeNode node) { NodeFilteringStatus stat = NodeFilteringStatus.Normal; if(node != null && node.Tag != null && IsFiltering) { if (!IsFullyExpaned(node.Tag)) stat |= NodeFilteringStatus.PartiallyExpanded; bool anymatched = IsMatched(node.Tag); if (anymatched) { stat |= NodeFilteringStatus.Visible; // any child mat if (m_treeView.GetChildren(node.Tag).Any(IsMatched)) stat |= NodeFilteringStatus.ChildVisible; } } return stat; } internal void SaveExpansion(TreeNode parent) { if (parent.Tag == null) return; var expandedItems = new List<object>(); foreach (var node in GetSubtree(parent)) if (node.Tag != null && node.Expanded) expandedItems.Add(node.Tag); if (expandedItems.Count > 0) m_expandedNodeMap[parent.Tag] = expandedItems; } internal void RestoreExpansion(TreeControl.Node parent, TreeControlAdapter treeAdapter) { if (parent.Tag == null) return; List<object> expandedItems; if (m_expandedNodeMap.TryGetValue(parent.Tag, out expandedItems)) { m_expandedNodeMap.Remove(parent.Tag); expandedItems.ForEach(item => treeAdapter.Expand(item)); } } /// <summary> /// Clears matched set. /// Must be called when filter changes.</summary> internal void ClearCache() { m_matchedNodes.Clear(); m_exemptedSet.Clear(); } internal bool IsMatched(object node) { // if not filtering or the node is already in the matched set. if (!IsFiltering || m_matchedNodes.Contains(node)) return true; bool result = false; try { m_matching = true; // perform a post-order traversal starting from node. // when match found add the matched node and all its ancestors to the m_matchedNodes set // and return true otherwise return false. // m_matchedNodes is used for speedup future lookups. m_tmpNodelist.Clear(); result = MatchRecv(node); } finally { m_matching = false; } return result; } // temp list used to hold path when traversing tree. private List<object> m_tmpNodelist = new List<object>(); private bool MatchRecv(object node) { bool result = false; m_tmpNodelist.Add(node); foreach (object child in m_treeView.GetChildren(node)) { result = MatchRecv(child); if (result )break; } if (!result && m_filterFunc(node)) { for (int i = m_tmpNodelist.Count - 1; i >= 0; i--) if (!m_matchedNodes.Add(m_tmpNodelist[i])) break; result = true; } m_tmpNodelist.RemoveAt(m_tmpNodelist.Count - 1); return result; } /// <summary> /// Check whether calling GetChildren(object parent) will return /// all the children. /// GetChildren(object parent) could return all if every child /// either passed the filter or exempt from filtering</summary> /// <param name="parent">parent item</param> /// <returns>true if all the children will returned</returns> internal bool IsFullyExpaned(object parent) { return m_exemptedSet.Contains(parent) || !m_treeView.GetChildren(parent).Any(child => !IsMatched(child) && !m_exemptedSet.Contains(child)); } /// <summary> /// Add any child fails the filter to exempted set.</summary> /// <param name="parent">parent node</param> internal void AddToExemptSet(object parent) { m_exemptedSet.Add(parent); foreach (object child in m_treeView.GetChildren(parent)) if (!IsMatched(child)) m_exemptedSet.Add(child); } /// <summary> /// Remove children from from exempted set</summary> /// <param name="parent">parent node</param> internal void RemoveFromExemptSet(object parent) { m_exemptedSet.Remove(parent); m_treeView.GetChildren(parent).ForEach(child => m_exemptedSet.Remove(child)); } #endregion #region IItemView Members public void GetInfo(object item, ItemInfo info) { m_itemView.GetInfo(item, info); // Call the filtered GetChildren() // to determine if node is leaf or not. if (!m_matching && !info.IsLeaf) info.IsLeaf = !GetChildren(item).Any(); } #endregion #region IAdaptable Members /// <summary> /// Gets an adapter of the specified type or null</summary> /// <param name="type">Adapter type</param> /// <returns>Adapter of the specified type or null</returns> public object GetAdapter(Type type) { if (typeof(FilteredTreeView).IsAssignableFrom(type)) return this; object converted = m_treeView.As(type); if (converted != null) return converted; return m_treeView; } #endregion #region IDecoratable Members /// <summary> /// Gets all decorators of the specified type</summary> /// <param name="type">Decorator type</param> /// <returns>Enumeration of non-null decorators that are of the specified type. The enumeration may be empty.</returns> public IEnumerable<object> GetDecorators(Type type) { object adapter = GetAdapter(type); if (adapter != null) yield return adapter; } #endregion /// <summary> /// Gets or sets whether filtering is activated</summary> public bool IsFiltering { get; set; } private IEnumerable<TreeControl.Node> GetSubtree(TreeControl.Node parent) { yield return parent; foreach (TreeControl.Node child in parent.Children) foreach (TreeControl.Node decendent in GetSubtree(child)) yield return decendent; } private readonly ITreeView m_treeView; private readonly IItemView m_itemView; private readonly Predicate<object> m_filterFunc; //re-entry guard private bool m_matching; // exempted from filtering. // used for caching all the items that are exempt from filtering. // the items in this set will be not filtered out. // This dynamic set items will be added and removed // as the user interact with TreeControl. private HashSet<object> m_exemptedSet = new HashSet<object>(); // Used for caching all the nodes that matches current filter. // it must be cleared whenever search pattern changeds. private HashSet<object> m_matchedNodes = new HashSet<object>(); // Maps subtree item to list of expanded items in the subtree. // This map used for restoring the expansion staste of a subtree. private Dictionary<object, List<object>> m_expandedNodeMap = new Dictionary<object, List<object>>(); } }
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2010-2014 Intel Corporation */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <sched.h> #include <pthread_np.h> #include <sys/queue.h> #include <sys/thr.h> #include <rte_debug.h> #include <rte_atomic.h> #include <rte_launch.h> #include <rte_log.h> #include <rte_memory.h> #include <rte_per_lcore.h> #include <rte_eal.h> #include <rte_lcore.h> #include <rte_eal_trace.h> #include "eal_private.h" #include "eal_thread.h" /* * Send a message to a slave lcore identified by slave_id to call a * function f with argument arg. Once the execution is done, the * remote lcore switch in FINISHED state. */ int rte_eal_remote_launch(int (*f)(void *), void *arg, unsigned slave_id) { int n; char c = 0; int m2s = lcore_config[slave_id].pipe_master2slave[1]; int s2m = lcore_config[slave_id].pipe_slave2master[0]; int rc = -EBUSY; if (lcore_config[slave_id].state != WAIT) goto finish; lcore_config[slave_id].f = f; lcore_config[slave_id].arg = arg; /* send message */ n = 0; while (n == 0 || (n < 0 && errno == EINTR)) n = write(m2s, &c, 1); if (n < 0) rte_panic("cannot write on configuration pipe\n"); /* wait ack */ do { n = read(s2m, &c, 1); } while (n < 0 && errno == EINTR); if (n <= 0) rte_panic("cannot read on configuration pipe\n"); rc = 0; finish: rte_eal_trace_thread_remote_launch(f, arg, slave_id, rc); return rc; } /* main loop of threads */ __rte_noreturn void * eal_thread_loop(__rte_unused void *arg) { char c; int n, ret; unsigned lcore_id; pthread_t thread_id; int m2s, s2m; char cpuset[RTE_CPU_AFFINITY_STR_LEN]; thread_id = pthread_self(); /* retrieve our lcore_id from the configuration structure */ RTE_LCORE_FOREACH_SLAVE(lcore_id) { if (thread_id == lcore_config[lcore_id].thread_id) break; } if (lcore_id == RTE_MAX_LCORE) rte_panic("cannot retrieve lcore id\n"); m2s = lcore_config[lcore_id].pipe_master2slave[0]; s2m = lcore_config[lcore_id].pipe_slave2master[1]; __rte_thread_init(lcore_id, &lcore_config[lcore_id].cpuset); ret = eal_thread_dump_current_affinity(cpuset, sizeof(cpuset)); RTE_LOG(DEBUG, EAL, "lcore %u is ready (tid=%p;cpuset=[%s%s])\n", lcore_id, thread_id, cpuset, ret == 0 ? "" : "..."); rte_eal_trace_thread_lcore_ready(lcore_id, cpuset); /* read on our pipe to get commands */ while (1) { void *fct_arg; /* wait command */ do { n = read(m2s, &c, 1); } while (n < 0 && errno == EINTR); if (n <= 0) rte_panic("cannot read on configuration pipe\n"); lcore_config[lcore_id].state = RUNNING; /* send ack */ n = 0; while (n == 0 || (n < 0 && errno == EINTR)) n = write(s2m, &c, 1); if (n < 0) rte_panic("cannot write on configuration pipe\n"); if (lcore_config[lcore_id].f == NULL) rte_panic("NULL function pointer\n"); /* call the function and store the return value */ fct_arg = lcore_config[lcore_id].arg; ret = lcore_config[lcore_id].f(fct_arg); lcore_config[lcore_id].ret = ret; rte_wmb(); lcore_config[lcore_id].state = FINISHED; } /* never reached */ /* pthread_exit(NULL); */ /* return NULL; */ } /* require calling thread tid by gettid() */ int rte_sys_gettid(void) { long lwpid; thr_self(&lwpid); return (int)lwpid; } int rte_thread_setname(pthread_t id, const char *name) { /* this BSD function returns no error */ pthread_set_name_np(id, name); return 0; } int rte_thread_getname(pthread_t id, char *name, size_t len) { RTE_SET_USED(id); RTE_SET_USED(name); RTE_SET_USED(len); return -ENOTSUP; }
{ "pile_set_name": "Github" }
define(function (require) { return function (seriesType, ecModel, api) { ecModel.eachSeriesByType(seriesType, function (seriesModel) { var data = seriesModel.getData(); var coordSys = seriesModel.coordinateSystem; if (coordSys) { var dims = coordSys.dimensions; data.each(dims, function (x, y, idx) { var point; if (!isNaN(x) && !isNaN(y)) { point = coordSys.dataToPoint([x, y]); } else { // Also {Array.<number>}, not undefined to avoid if...else... statement point = [NaN, NaN]; } data.setItemLayout(idx, point); }, true); } }); }; });
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('treemap', '0041_search_by_user'), ] operations = [ migrations.AlterField( model_name='mapfeature', name='updated_by', field=models.ForeignKey(verbose_name='Last Updated By', blank=True, to=settings.AUTH_USER_MODEL, null=True), ), ]
{ "pile_set_name": "Github" }
<?php /** * Generic utility functions. * * @author Pressbooks <[email protected]> * @license GPLv3 (or any later version) */ namespace Pressbooks\Utility; /** * Return a value for a given key even if not set * * @param mixed $arr either an array or a string that points to an array in $GLOBALS * @param string $key * @param mixed $default * * @return mixed */ function getset( $arr, $key, $default = null ) { // Get from array if ( is_array( $arr ) ) { return isset( $arr[ $key ] ) ? $arr[ $key ] : $default; } // Get from a global or superglobal if ( is_string( $arr ) && isset( $GLOBALS[ $arr ] ) && is_array( $GLOBALS[ $arr ] ) ) { return isset( $GLOBALS[ $arr ][ $key ] ) ? $GLOBALS[ $arr ][ $key ] : $default; } return $default; } /** * Scan a directory and return the files (not directories!) ordered by date, newest first. * * @param $dir * * @return array */ function scandir_by_date( $dir ) { $ignored = [ '.', '..', '.svn', '.git', '.htaccess' ]; $dir = untrailingslashit( $dir ) . '/'; $files = []; if ( is_dir( $dir ) ) { foreach ( scandir( $dir ) as $file ) { if ( in_array( $file, $ignored, true ) || is_dir( $dir . $file ) ) { continue; } $files[ $file ] = filemtime( $dir . $file ); } arsort( $files ); $files = array_keys( $files ); } return ( $files ) ? $files : []; } /** * Scan the exports directory, return the files grouped into intervals of 3 minutes, newest first. * * @param string $dir fullpath to the Exports folder. (optional) * * @return array */ function group_exports( $dir = null ) { $ignored = [ '.', '..', '.svn', '.git', '.htaccess' ]; if ( ! $dir ) { $dir = \Pressbooks\Modules\Export\Export::getExportFolder(); } else { $dir = rtrim( $dir, '/' ) . '/'; } $files = []; foreach ( scandir( $dir ) as $file ) { if ( in_array( $file, $ignored, true ) || is_dir( $dir . $file ) ) { continue; } $files[ $file ] = filemtime( $dir . $file ); } arsort( $files ); $interval = 3 * MINUTE_IN_SECONDS; // Three minutes $pos = 0; $output = []; foreach ( $files as $file => $timestamp ) { if ( 0 === $pos ) { $pos = $timestamp; } if ( $pos - $timestamp > $interval ) { $pos = $timestamp; } $output[ $pos ][] = $file; } return $output; } /** * Truncate the exports directory, delete old files. * * @param int $max * @param string $dir fullpath to the Exports fo * lder. (optional) */ function truncate_exports( $max, $dir = null ) { if ( ! $dir ) { $dir = \Pressbooks\Modules\Export\Export::getExportFolder(); } else { $dir = rtrim( $dir, '/' ) . '/'; } $max = absint( $max ); $files = group_exports( $dir ); $i = 1; foreach ( $files as $date => $exports ) { if ( $i > $max ) { foreach ( $exports as $export ) { $export = realpath( $dir . $export ); unlink( $export ); } } ++$i; } } /** * Return the full path to the directory containing media * Checks for `ms_files_rewriting` site option; uses /wp-content/blogs.dir/ if present, otherwise uses WordPress 3.5+ standard * * @return string path */ function get_media_prefix() { if ( get_site_option( 'ms_files_rewriting' ) ) { return WP_CONTENT_DIR . '/blogs.dir/' . get_current_blog_id() . '/files/'; } else { return trailingslashit( get_generated_content_path( '', false ) ); } } /** * Returns the full path to a media file, given its guid * Used for adding cover images to an EPUB file and for ajax deletion of uploaded cover images * * @param string $guid The guid of a media file (usually image) * * @return string the full path to the media file on the filesystem */ function get_media_path( $guid ) { $parts = wp_parse_url( $guid ); $path = $parts['path']; $beginning = strpos( $path, 'files' ); if ( $beginning ) { $path = substr( $path, $beginning ); return WP_CONTENT_DIR . '/blogs.dir/' . get_current_blog_id() . '/' . $path; } else { $beginning = strpos( $path, 'uploads' ); $path = substr( $path, $beginning ); return WP_CONTENT_DIR . '/' . $path; } } /** * Scan the export directory, return latest of each file type * * @author Brad Payne <[email protected]> * @copyright 2014 Brad Payne * @since 3.8.0 * @return array */ function latest_exports() { $filetypes = \Pressbooks\Modules\Export\filetypes(); $dir = \Pressbooks\Modules\Export\Export::getExportFolder(); $files = []; // group by extension, sort by date newest first foreach ( \Pressbooks\Utility\scandir_by_date( $dir ) as $file ) { // only interested in the part of filename starting with the timestamp if ( preg_match( '/-\d{10,11}(.*)/', $file, $matches ) ) { // grab the first captured parenthisized subpattern $ext = $matches[1]; $files[ $ext ][] = $file; } } // get only one of the latest of each type $latest = []; foreach ( $filetypes as $type => $ext ) { if ( array_key_exists( $ext, $files ) ) { $latest[ $type ] = $files[ $ext ][0]; } } return $latest; } /** * Add sitemap to robots.txt */ function add_sitemap_to_robots_txt() { if ( 1 === absint( get_option( 'blog_public' ) ) ) { echo 'Sitemap: ' . get_option( 'siteurl' ) . "/?feed=sitemap.xml\n\n"; } } /** * Echo a sitemap */ function do_sitemap() { if ( 1 === absint( get_option( 'blog_public' ) ) ) { $template = untrailingslashit( PB_PLUGIN_DIR ) . '/templates/pb-sitemap.php'; load_template( $template ); } else { status_header( 404 ); nocache_headers(); echo '<h1>404 Not Found</h1>'; echo 'The page that you have requested could not be found.'; } } /** * Create a temporary file that automatically gets deleted when PHP ends. * * @param string $resource_key (optional) * * @return string Path to temporary file */ function create_tmp_file( $resource_key = '' ) { if ( empty( $resource_key ) ) { $resource_key = uniqid( 'tmpfile-', true ); } $stream = stream_get_meta_data( $GLOBALS[ $resource_key ] = tmpfile() ); // @codingStandardsIgnoreLine return $stream['uri']; } /** * Lightweight check to see if the Epubcheck executable is installed and up to date. * * @return boolean */ function check_epubcheck_install() { if ( ! defined( 'PB_EPUBCHECK_COMMAND' ) ) { // @see wp-config.php define( 'PB_EPUBCHECK_COMMAND', '/usr/bin/java -jar /opt/epubcheck/epubcheck.jar' ); } $output = []; $return_val = 0; exec( PB_EPUBCHECK_COMMAND . ' -h 2>&1', $output, $return_val ); $output = $output[0]; if ( preg_match( '/(?:EPUBCheck\sv)*(([0-9]+.?)+)/i', $output, $matches ) ) { // Command found. $version = $matches[1]; if ( version_compare( $version, '4.0.0' ) >= 0 ) { return true; } } return apply_filters( 'pb_epub_has_dependencies', false ); } /** * Lightweight check to see if the Kindlegen executable is installed and up to date. * * @return boolean */ function check_kindlegen_install() { if ( ! defined( 'PB_KINDLEGEN_COMMAND' ) ) { // @see wp-config.php define( 'PB_KINDLEGEN_COMMAND', '/opt/kindlegen/kindlegen' ); } $output = []; $return_val = 0; exec( PB_KINDLEGEN_COMMAND . ' 2>&1', $output, $return_val ); if ( isset( $output[2] ) && false !== strpos( $output[2], 'kindlegen' ) ) { // Command found. $output = explode( ' V', $output[2] ); $output = explode( ' build', $output[1] ); $version = $output[0]; if ( version_compare( $version, '2.9' ) >= 0 ) { return true; } } return false; } /** * Lightweight check to see if the Prince executable is installed and up to date. * * @return boolean */ function check_prince_install() { if ( ! defined( 'PB_PRINCE_COMMAND' ) ) { // @see wp-config.php define( 'PB_PRINCE_COMMAND', '/usr/bin/prince' ); } $output = []; $return_val = 0; exec( PB_PRINCE_COMMAND . ' --version 2>&1', $output, $return_val ); $output = $output[0]; if ( false !== strpos( $output, 'Prince' ) ) { // Command found. $output = explode( 'Prince ', $output ); $version = $output[1]; if ( version_compare( $version, '11' ) >= 0 ) { return true; } } return false; } /** * Lightweight check to see if the xmllint executable is installed and up to date. * * @return boolean */ function check_xmllint_install() { if ( ! defined( 'PB_XMLLINT_COMMAND' ) ) { // @see wp-config.php define( 'PB_XMLLINT_COMMAND', '/usr/bin/xmllint' ); } $output = []; $return_val = 0; exec( PB_XMLLINT_COMMAND . ' --version 2>&1', $output, $return_val ); $output = $output[0]; if ( false !== strpos( $output, 'libxml' ) ) { // Command found. $output = explode( PB_XMLLINT_COMMAND . ': using libxml version ', $output ); $version = $output[1]; if ( version_compare( $version, '20706' ) >= 0 ) { return true; } } return false; } /** * Lightweight check to see if the Saxon-HE executable is installed and up to date. * * @return boolean */ function check_saxonhe_install() { if ( ! defined( 'PB_SAXON_COMMAND' ) ) { // @see wp-config.php define( 'PB_SAXON_COMMAND', '/usr/bin/java -jar /opt/saxon-he/saxon-he.jar' ); } $output = []; $return_val = 0; exec( PB_SAXON_COMMAND . ' -? 2>&1', $output, $return_val ); $output = $output[0]; if ( false !== strpos( $output, 'Saxon-HE ' ) ) { // Command found. $output = explode( 'Saxon-HE ', $output ); $version = explode( 'J from Saxonica', $output[1] )[0]; if ( version_compare( $version, '9.7.0-10' ) >= 0 ) { return true; } } /** * @since 3.9.8 * * Allows the SaxonHE dependency error to be disabled. * * @param bool $value */ return apply_filters( 'pb_odt_has_dependencies', false ); } /** * Function to determine whether or not experimental features should be visible to users. * * @param $host string * * @return boolean */ function show_experimental_features( $host = '' ) { if ( ! $host ) { $host = wp_parse_url( network_home_url(), PHP_URL_HOST ); } // hosts where experimental features should be hidden $hosts_for_hiding = [ 'pressbooks.com', 'pressbooks.pub', ]; foreach ( $hosts_for_hiding as $host_for_hiding ) { if ( $host === $host_for_hiding || strpos( $host, $host_for_hiding ) ) { return false; } } return true; } /** * Include plugins in /symbionts * * @since 2.5.1 */ function include_plugins() { $plugins = [ 'custom-metadata/custom_metadata.php' => 1, ]; $plugins = filter_plugins( $plugins ); if ( ! empty( $plugins ) ) { foreach ( $plugins as $key => $val ) { require_once( PB_PLUGIN_DIR . 'symbionts/' . $key ); } } // Disable comments if ( true === disable_comments() ) { require_once( PB_PLUGIN_DIR . 'symbionts/disable-comments-mu/disable-comments-mu.php' ); } } /** * Filters out active plugins, to avoid collisions with plugins already installed. * * @since 2.5.1 * * @param array $plugins An array of plugins, key/values paired like so: 'pressbooks/pressbooks.php' => 1 * * @return array */ function filter_plugins( $plugins ) { $already_active = get_option( 'active_plugins' ); $network_already_active = get_site_option( 'active_sitewide_plugins' ); // Don't include plugins already active at the site level or network level. if ( ! empty( $plugins ) ) { foreach ( $plugins as $key => $val ) { if ( in_array( $key, $already_active, true ) || array_key_exists( $key, $network_already_active ) ) { unset( $plugins[ $key ] ); } } } // Don't include plugins we are trying to activate right now! if ( isset( $_REQUEST['action'] ) ) { if ( 'activate' === $_REQUEST['action'] && ! empty( $_REQUEST['plugin'] ) ) { $key = (string) $_REQUEST['plugin']; unset( $plugins[ $key ] ); } elseif ( 'activate-selected' === $_REQUEST['action'] && is_array( $_REQUEST['checked'] ) ) { foreach ( $_REQUEST['checked'] as $key ) { unset( $plugins[ $key ] ); } } } return $plugins; } /** * Check if we should disable comments. * * @return bool */ function disable_comments() { if ( ! \Pressbooks\Book::isBook() ) { /** * Allows comments to be enabled on the root blog by adding a function to this filter that returns false. * * @since 3.9.6 * * @param bool $value */ return apply_filters( 'pb_disable_root_comments', true ); } $old_option = get_option( 'disable_comments_options' ); $new_option = get_option( 'pressbooks_sharingandprivacy_options', [ 'disable_comments' => 1, ] ); if ( false === (bool) $old_option ) { $retval = (bool) $new_option['disable_comments']; } elseif ( is_array( $old_option['disabled_post_types'] ) && in_array( 'chapter', $old_option['disabled_post_types'], true ) && in_array( 'front-matter', $old_option['disabled_post_types'], true ) && in_array( 'front-matter', $old_option['disabled_post_types'], true ) ) { $retval = true; $new_option['disable_comments'] = 1; update_option( 'pressbooks_sharingandprivacy_options', $new_option ); delete_option( 'disable_comments_options' ); } else { $retval = false; $new_option['disable_comments'] = 0; update_option( 'pressbooks_sharingandprivacy_options', $new_option ); delete_option( 'disable_comments_options' ); } return $retval; } /** * Remove the Featured tab, change order on the others so that Recommended is first. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * * @since 4.0.0 * @author Joey Kudish <[email protected]> * @author Nick Hamze <[email protected]> * * @param array $tabs The Plugin Installer tabs. * * @return array */ function install_plugins_tabs( $tabs ) { unset( $tabs['featured'] ); unset( $tabs['popular'] ); unset( $tabs['favorites'] ); $tabs['popular'] = _x( 'Popular', 'Plugin Installer' ); $tabs['favorites'] = _x( 'Favorites', 'Plugin Installer' ); return $tabs; } /** * Replace the core Recommended tab with ours. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * * @since 4.0.0 * @author Joey Kudish <[email protected]> * @author Nick Hamze <[email protected]> * * @param false|object|array $res The result object or array. Default false. * @param string $action The type of information being requested from the Plugin Install API. * @param object $args Plugin API arguments. * * @return object */ function hijack_recommended_tab( $res, $action, $args ) { if ( ! isset( $args->browse ) || 'recommended' !== $args->browse ) { return $res; } $res = get_site_transient( 'pressbooks_recommended_plugins_data' ); if ( ! $res || ! isset( $res->plugins ) ) { $res = \Pressbooks\Utility\fetch_recommended_plugins(); if ( isset( $res->plugins ) ) { set_site_transient( 'pressbooks_recommended_plugins_data', $res, HOUR_IN_SECONDS ); } } return $res; } /** * Fetch recommended plugins from our server. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * * @since 4.0.0 * @author Joey Kudish <[email protected]> * @author Nick Hamze <[email protected]> * * @return object */ function fetch_recommended_plugins() { /** * Filter the URL of the Pressbooks Recommended Plugins server. * * @since 4.0.0 * * @param string $value */ $http_url = apply_filters( 'pb_recommended_plugins_url', 'https://pressbooks-plugins.now.sh' ) . '/api/plugin-recommendations'; $url = $http_url; $ssl = wp_http_supports( [ 'ssl' ] ); if ( $ssl ) { $url = set_url_scheme( $url, 'https' ); } $request = wp_remote_get( $url, [ 'timeout' => 15, ] ); if ( $ssl && is_wp_error( $request ) ) { // @codingStandardsIgnoreLine trigger_error( __( 'An unexpected error occurred. Something may be wrong with the plugin recommendations server or your site&#8217;s server&#8217;s configuration.', 'pressbooks' ) . ' ' . __( '(Pressbooks could not establish a secure connection to the plugin recommendations server. Please contact your server administrator.)', 'pressbooks' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE ); $request = wp_remote_get( $http_url, [ 'timeout' => 15, ] ); } if ( is_wp_error( $request ) ) { $res = new \WP_Error( 'plugins_api_failed', __( 'An unexpected error occurred. Something may be wrong with the plugin recommendations server or your site&#8217;s server&#8217;s configuration.', 'pressbooks' ), $request->get_error_message() ); } else { $res = json_decode( wp_remote_retrieve_body( $request ) ); $res->info = (array) $res->info; // WP wants this as an array... foreach ( $res->plugins as $k => $plugin ) { if ( ! empty( $plugin->error ) ) { unset( $res->plugins[ $k ] ); } else { $res->plugins[ $k ]->icons = (array) $plugin->icons; // WP wants this as an array... } } if ( ! is_object( $res ) && ! is_array( $res ) ) { $res = new \WP_Error( 'plugins_api_failed', __( 'An unexpected error occurred. Something may be wrong with the plugin recommendations server or your site&#8217;s server&#8217;s configuration.', 'pressbooks' ), wp_remote_retrieve_body( $request ) ); } } return $res; } /** * Replace the description on the Recommended tab. * Adapted from https://github.com/secretpizzaparty/better-plugin-recommendations * * @since 4.0.0 * @author Joey Kudish <[email protected]> * @author Nick Hamze <[email protected]> * * @param string $translation * @param string $text * @param string $domain * * @return string */ function change_recommendations_sentence( $translation, $text, $domain ) { if ( 'These suggestions are based on the plugins you and other users have installed.' === $text ) { return __( 'These plugins have been created and/or recommended by the Pressbooks community.', 'pressbooks' ); } return $translation; } /** * Function to return a string representing max import size by comparing values of upload_max_filesize, post_max_size * Uses parse_size helper function since the values in php.ini are strings like 64M and 128K * @return string */ function file_upload_max_size() { static $return_val = false; // This function is adapted from Drupal and http://stackoverflow.com/questions/13076480/php-get-actual-maximum-upload-size if ( false === $return_val ) { $post_max_size_str = ini_get( 'post_max_size' ); $upload_max_filesize_str = ini_get( 'upload_max_filesize' ); $post_max_size = parse_size( $post_max_size_str ); $upload_max_filesize = parse_size( $upload_max_filesize_str ); // If upload_max_size is less, then reduce. Except if upload_max_size is // zero, which indicates no limit. $return_val = $post_max_size_str; if ( $upload_max_filesize > 0 && $upload_max_filesize < $post_max_size ) { $return_val = $upload_max_filesize_str; } } return $return_val; } /** * parse_size converts php.ini values from strings (like 128M or 64K) into actual numbers that can be compared * * @param string $size * * @return float */ function parse_size( $size ) { $unit = preg_replace( '/[^bkmgtpezy]/i', '', $size ); // Remove the non-unit characters from the size. $size = preg_replace( '/[^0-9\.]/', '', $size ); // Remove the non-numeric characters from the size. if ( $unit ) { // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round( $size * pow( 1024, stripos( 'bkmgtpezy', $unit[0] ) ) ); } else { return round( $size ); } } /** * format_bytes converts an byte value supplied as an integer into a string suffixed with the appropriate unit of measurement. * * @param float $bytes * @param int $precision * * @return string */ function format_bytes( $bytes, $precision = 2 ) { $units = [ 'B', 'KB', 'MB', 'GB', 'TB' ]; $bytes = max( $bytes, 0 ); $pow = floor( ( $bytes ? log( $bytes ) : 0 ) / log( 1024 ) ); $pow = min( $pow, count( $units ) - 1 ); $bytes /= ( 1 << ( 10 * $pow ) ); return round( $bytes, $precision ) . ' ' . $units[ $pow ]; } /** * @param $message * @param null $message_type */ function debug_error_log( $message, $message_type = null ) { if ( defined( 'WP_TESTS_MULTISITE' ) === false && WP_DEBUG ) { \error_log( $message, $message_type ); // @codingStandardsIgnoreLine } } /** * Email error to an array of recipients * * @param array $emails * @param string $subject * @param string $message */ function email_error_log( $emails, $subject, $message ) { // ------------------------------------------------------------------------------------------------------------ // Write to generic error log to be safe debug_error_log( $subject . "\n" . $message ); // ------------------------------------------------------------------------------------------------------------ // Email logs add_filter( 'wp_mail_from', function ( $from_email ) { return str_replace( 'wordpress@', 'pressbooks@', $from_email ); } ); add_filter( 'wp_mail_from_name', function ( $from_name ) { return 'Pressbooks'; } ); /** * Filter an array of email addresses error logs are sent to * * @since 4.3.3 * * @param array $emails */ $emails = apply_filters( 'pb_error_log_emails', $emails ); foreach ( $emails as $email ) { // Call pluggable \wp_mail( $email, $subject, $message ); } } /** * Simple template system. * * @param string $path * @param array $vars (optional) * * @return string */ function template( $path, array $vars = [] ) { if ( ! file_exists( $path ) ) { throw new \InvalidArgumentException( "File not found: $path" ); } ob_start(); extract( $vars ); // @codingStandardsIgnoreLine include( $path ); $output = ob_get_contents(); ob_end_clean(); return $output; } /** * If we get error code 400, retry wp_remote_get() * * @param string $url * @param array $args * @param int $retry * @param int $attempts * @param array $response * * @return array|\WP_Error */ function remote_get_retry( $url, $args, $retry = 3, $attempts = 0, $response = [] ) { $completed = false; if ( $attempts >= $retry ) { $completed = true; } if ( $completed ) { return $response; } $attempts++; $response = wp_remote_get( $url, $args ); /** * Filter the array of response codes which should prompt a retry. * * @since 4.3.0 */ $retry_response_codes = apply_filters( 'pb_remote_get_retry_response_codes', /** * Filter the array of response codes which should prompt a retry. * * @since 3.9.6 * @deprecated 4.3.0 Use pb_remote_get_retry_response_codes isntead. * * @param array $value */ apply_filters( 'pressbooks_remote_get_retry_response_codes', [ 400 ] ) ); if ( ! is_array( $response ) || ! in_array( $response['response']['code'], $retry_response_codes, true ) ) { return $response; } /** * Filter the sleep time for a retry. * * @since 4.3.0 */ $sleep = apply_filters( 'pb_remote_get_retry_wait_time', /** * Filter the sleep time for a retry. * * @since 3.9.6 * @deprecated 4.3.0 Use pb_remote_get_retry_wait_time isntead. * * @param int $value */ apply_filters( 'pressbooks_remote_get_retry_wait_time', 1000 ) ); usleep( $sleep ); return remote_get_retry( $url, $args, $retry, $attempts, $response ); } /** * Set the wp_mail sender address * * @since 3.9.7 * * @param string $email The default email address * * @return string */ function mail_from( $email ) { if ( defined( 'WP_MAIL_FROM' ) ) { $email = WP_MAIL_FROM; } else { $sitename = strtolower( $_SERVER['SERVER_NAME'] ); if ( substr( $sitename, 0, 4 ) === 'www.' ) { $sitename = substr( $sitename, 4 ); } $email = 'pressbooks@' . $sitename; } return $email; } /** * Set the wp_mail sender name * * @since 3.9.7 * * @param string $name The default sender name * * @return string */ function mail_from_name( $name ) { if ( defined( 'WP_MAIL_FROM_NAME' ) ) { $name = WP_MAIL_FROM_NAME; } else { $name = 'Pressbooks'; } return $name; } /** * Recursive directory copy. Props to https://ben.lobaugh.net/blog/864/php-5-recursively-move-or-copy-files * * @since 3.9.8 * @author Ben Lobaugh <[email protected]> * * @param string $src * @param string $dest * @param array $excludes (optional, supports shell wildcard patterns, add a unix like trailing slash for folders) * @param array $includes (optional, supports shell wildcard patterns, add a unis like trailing slash for folders) * * @return bool */ function rcopy( $src, $dest, $excludes = [], $includes = [] ) { // Remove trailing slashes $src = rtrim( $src, '\\/' ); $dest = rtrim( $dest, '\\/' ); if ( ! is_dir( $src ) ) { return false; } if ( ! is_dir( $dest ) ) { if ( ! mkdir( $dest ) ) { return false; } } $i = new \DirectoryIterator( $src ); foreach ( $i as $f ) { $include_this_file = ( empty( $includes ) ? true : false ); if ( $f->isFile() ) { // File foreach ( $excludes as $exclude ) { if ( fnmatch( $exclude, "$f" ) ) { continue 2; // Excluded, go to next file } } foreach ( $includes as $include ) { if ( fnmatch( $include, "$f" ) ) { $include_this_file = true; break; } } if ( $include_this_file ) { if ( false === copy( $f->getRealPath(), "$dest/$f" ) ) { return false; } } } elseif ( ! $f->isDot() && $f->isDir() ) { // Directory foreach ( $excludes as $exclude ) { if ( str_ends_with( $exclude, '/' ) ) { if ( fnmatch( rtrim( $exclude, '/' ), "$f" ) ) { continue 2; // Excluded, go to next file } } } $dir_pattern_count = 0; foreach ( $includes as $include ) { if ( str_ends_with( $include, '/' ) ) { $dir_pattern_count++; if ( fnmatch( rtrim( $include, '/' ), "$f" ) ) { $include_this_file = true; break; } } } if ( $include_this_file || $dir_pattern_count === 0 ) { \Pressbooks\Utility\rcopy( $f->getRealPath(), "$dest/$f", $excludes, $includes ); } } } return true; } /** * @param string $haystack * @param string $needle * * @return bool */ function str_starts_with( $haystack, $needle ) { $length = strlen( $needle ); return ( substr( $haystack, 0, $length ) === $needle ); } /** * @param string $haystack * @param string $needle * * @return bool */ function str_ends_with( $haystack, $needle ) { $length = strlen( $needle ); if ( $length === 0 ) { return true; } return ( substr( $haystack, -$length ) === $needle ); } /** * Remove a string from the beginning of a string * * @param $haystack * @param $prefix * * @return bool|string */ function str_remove_prefix( $haystack, $prefix ) { if ( substr( $haystack, 0, strlen( $prefix ) ) === $prefix ) { $haystack = substr( $haystack, strlen( $prefix ) ); } return $haystack; } /** * Replace last occurrence of a String * * @param string $search * @param string $replace * @param string $subject * * @return string */ function str_lreplace( $search, $replace, $subject ) { $pos = strrpos( $subject, $search ); if ( $pos !== false ) { $subject = substr_replace( $subject, $replace, $pos, strlen( $search ) ); } return (string) $subject; } /** * Search a comma delimited string for a match * * @param string $haystack * @param string $needle * * @return bool */ function comma_delimited_string_search( $haystack, $needle ) { $haystack = explode( ',', $haystack ); foreach ( $haystack as $hay ) { if ( trim( $needle ) === trim( $hay ) ) { return true; } } return false; } /** * @param string $content * * @return int */ function word_count( $content ) { $n = 0; $content = wp_strip_all_tags( $content, true ); // Is this chinese? if ( preg_match( '/[\x{4e00}-\x{9fa5}]+/u', $content ) ) { $content = preg_replace( '/[!,。?、]/', ' ', $content ); // Remove chinese punctuation $content = preg_replace( '/[\x80-\xff]{1,3}/', ' ', $content, -1, $n ); // Count chinese characters, replace $n } if ( ! empty( trim( $content ) ) ) { $n += count( preg_split( '/\s+/', $content ) ); // Count between spaces } return $n; } /** * Because realpath() does not work on files that do not exist... Handles paths and URLs * * @param string $path * * @return string */ function absolute_path( $path ) { if ( filter_var( $path, FILTER_VALIDATE_URL ) !== false ) { $url = $path; $path = wp_parse_url( $path, PHP_URL_PATH ); } $new_path = str_replace( '\\', '/', $path ); $parts = array_filter( explode( '/', $new_path ), 'strlen' ); $absolutes = []; foreach ( $parts as $part ) { if ( '.' === $part ) { continue; } if ( '..' === $part ) { array_pop( $absolutes ); } else { $absolutes[] = $part; } } $new_path = '/' . implode( '/', $absolutes ); if ( isset( $url ) ) { $new_path = str_lreplace( $path, $new_path, $url ); } return $new_path; } /** * Compare URL domain names (not subdomain) * * @param string $url1 * @param string $url2 * * @return bool */ function urls_have_same_host( $url1, $url2 ) { $host1 = wp_parse_url( $url1, PHP_URL_HOST ); $host2 = wp_parse_url( $url2, PHP_URL_HOST ); if ( ! $host1 || ! $host2 ) { return false; } $host_names1 = explode( '.', $host1 ); if ( count( $host_names1 ) > 1 ) { $bottom_host_name1 = $host_names1[ count( $host_names1 ) - 2 ] . '.' . $host_names1[ count( $host_names1 ) - 1 ]; } else { $bottom_host_name1 = $host1; } $host_names2 = explode( '.', $host2 ); if ( count( $host_names2 ) > 1 ) { $bottom_host_name2 = $host_names2[ count( $host_names2 ) - 2 ] . '.' . $host_names2[ count( $host_names2 ) - 1 ]; } else { $bottom_host_name2 = $host2; } $same_host = ( $bottom_host_name1 === $bottom_host_name2 ); return $same_host; } /** * Namespace our generated content * * @since 5.0.0 * * @param string $suffix (optional) * @param bool $mkdir (optional) * * @return string */ function get_generated_content_path( $suffix = '', $mkdir = true ) { $path = wp_upload_dir()['basedir'] . '/pressbooks'; if ( $suffix ) { $suffix = ltrim( $suffix, '/' ); $path = absolute_path( "{$path}/{$suffix}" ); } if ( $mkdir && ! file_exists( $path ) ) { wp_mkdir_p( $path ); } return $path; } /** * Namespace our generated content * * @since 5.0.0 * * @param string $suffix (optional) * @param bool $keep_subdomain (optional) Keep subdomain in url * * @return string * */ function get_generated_content_url( $suffix = '', $keep_subdomain = false ) { $path = wp_get_upload_dir()['baseurl'] . '/pressbooks'; if ( $keep_subdomain ) { $path_parsed = wp_parse_url( $path ); global $domain; $path = $path_parsed['scheme'] . '://' . $domain . $path_parsed['path']; } if ( $suffix ) { $suffix = ltrim( $suffix, '/' ); $path = absolute_path( "{$path}/{$suffix}" ); } $path = \Pressbooks\Sanitize\maybe_https( $path ); return $path; } /** * Blade cache path * * @return string */ function get_cache_path() { return get_generated_content_path( '/cache' ); } /** * @since 5.0.0 * * @see \WP_Filesystem * @return \WP_Filesystem_Direct */ function init_direct_filesystem() { if ( ! class_exists( 'WP_Filesystem_Direct' ) ) { $abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php', 'direct' ); // Use for mocks / testing require_once( ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php' ); require_once( $abstraction_file ); // Set the permission constants if not already set. if ( ! defined( 'FS_CHMOD_DIR' ) ) { define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) ); } if ( ! defined( 'FS_CHMOD_FILE' ) ) { define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) ); } } return new \WP_Filesystem_Direct( [] ); } /** * @since 5.0.0 * * @param string $filename * * @return bool|string */ function get_contents( $filename ) { $fs = init_direct_filesystem(); return $fs->get_contents( $filename ); } /** * @since 5.0.0 * * @param string $filename * @param mixed $data * * @return bool */ function put_contents( $filename, $data ) { $fs = init_direct_filesystem(); return $fs->put_contents( $filename, $data ); } /** * Delete all contents of a directory without using `RecursiveDirectoryIterator` * (E_WARNING: Too many open files, @see https://stackoverflow.com/a/37754469 ) * * @since 5.0.0 * * @param string $dirname * @param bool $only_empty * * @return bool */ function rmrdir( $dirname, $only_empty = false ) { if ( ! is_dir( $dirname ) ) { return false; } $dscan = [ realpath( $dirname ) ]; $darr = []; while ( ! empty( $dscan ) ) { $dcur = array_pop( $dscan ); $darr[] = $dcur; $d = opendir( $dcur ); if ( $d ) { while ( $f = readdir( $d ) ) { if ( '.' === $f || '..' === $f ) { continue; } $f = $dcur . '/' . $f; if ( is_dir( $f ) ) { $dscan[] = $f; } else { unlink( $f ); } } closedir( $d ); } } $i_until = ( $only_empty ) ? 1 : 0; for ( $i = count( $darr ) - 1; $i >= $i_until; $i-- ) { if ( ! rmdir( $darr[ $i ] ) ) { trigger_error( "Warning: There was a problem deleting a temporary file in $dirname", E_USER_WARNING ); } } return ( ( $only_empty ) ? ( count( scandir( $dirname ) ) <= 2 ) : ( ! is_dir( $dirname ) ) ); } /** * Comma separated, Oxford comma, localized and between the last two items * * @since 5.0.0 * * @param array $vars * * @return string */ function oxford_comma( array $vars ) { if ( count( $vars ) === 2 ) { return $vars[0] . ' ' . __( 'and', 'pressbooks' ) . ' ' . $vars[1]; } else { $last = array_pop( $vars ); $output = implode( ', ', $vars ); if ( $output ) { $output .= ', ' . __( 'and', 'pressbooks' ) . ' '; } $output .= $last; return $output; } } /** * Explode an oxford comma seperated list of items * * @param $string * * @return array */ function oxford_comma_explode( $string ) { $results = []; if ( strpos( $string, ',' ) !== false ) { $items = explode( ',', $string ); foreach ( $items as $item ) { $item = trim( $item ); $item = str_remove_prefix( $item, __( 'and', 'pressbooks' ) . ' ' ); if ( ! empty( $item ) ) { $results[] = $item; } } } else { $items = explode( ' ' . __( 'and', 'pressbooks' ) . ' ', $string ); foreach ( $items as $item ) { $item = trim( $item ); if ( ! empty( $item ) ) { $results[] = $item; } } } return $results; } /** * Converts a space separated string, to lowercase separated by dashes * * @since 5.5.0 * * @param $string * * @return string */ function str_lowercase_dash( $string ) { $low = ''; if ( ! empty( $string ) ) { $low = strtolower( trim( $string ) ); $results = explode( ' ', $low ); if ( count( $results ) > 1 ) { $low = implode( '-', $results ); } } return $low; } /** * Check whether an array is zero-indexed and sequential * * @param mixed $arr * * @return bool */ function is_assoc( $arr ) { if ( ! is_array( $arr ) ) { return false; } if ( [] === $arr ) { return false; } return array_keys( $arr ) !== range( 0, count( $arr ) - 1 ); } /** * Like PHP empty(), but also checks if a string is just white space * * @param mixed $var * * @return bool */ function empty_space( $var ) { if ( is_string( $var ) ) { if ( ctype_space( $var ) ) { $var = ''; } $var = trim( $var ); } return empty( $var ); } /** * Best guess the main contact's email * * @return string */ function main_contact_email() { $main_site_id = get_main_site_id(); $email = get_blog_option( $main_site_id, 'pb_network_contact_email' ); // Aldine if ( empty( $email ) ) { $email = get_blog_option( $main_site_id, 'admin_email' ); // Main Site if ( empty( $email ) ) { $email = get_site_option( 'admin_email' ); // Main Network } } return $email ? $email : ''; } /** * Find a shortcode in content, look for an attribute in that shortcode, if value matches $from, change it to $to, return fixed content. * * @param string $content * @param string $tag * @param string $att * @param string $from * @param string $to * * @return string */ function shortcode_att_replace( $content, $tag, $att, $from, $to ) { $fixed_content = $content; $regex = get_shortcode_regex( [ $tag ] ); if ( preg_match_all( '/' . $regex . '/s', $content, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $shortcode ) { $shortcode_attrs = shortcode_parse_atts( $shortcode[3] ); if ( ! is_array( $shortcode_attrs ) ) { $shortcode_attrs = []; } if ( isset( $shortcode_attrs[ $att ] ) ) { if ( $shortcode_attrs[ $att ] === "&quot;{$from}&quot;" ) { $preg_from = "&quot;{$from}&quot;"; $preg_to = "&quot;{$to}&quot;"; } elseif ( $shortcode_attrs[ $att ] === '"' . $from . '"' ) { $preg_from = '"' . $from . '"'; $preg_to = '"' . $to . '"'; } elseif ( $shortcode_attrs[ $att ] === "'{$from}'" ) { $preg_from = "'{$from}'"; $preg_to = "'{$to}'"; } elseif ( (string) $shortcode_attrs[ $att ] === (string) $from ) { $preg_from = $from; $preg_to = $to; } else { continue; } $preg_from = '/(' . preg_quote( $att, '/' ) . '\s*=.*?)' . preg_quote( $preg_from, '/' ) . '/'; $preg_to = '${1}' . $preg_to; $fixed_shortcode = preg_replace( $preg_from, $preg_to, $shortcode[0] ); $fixed_content = str_replace( $shortcode[0], $fixed_shortcode, $fixed_content ); } } } return $fixed_content; } /** * This works by filtering the global $shortcode_tags, running do_shortcode(), then putting everything back as it was before. * * @since 5.6.3 * * @param string $content * @param array $tags * * @return string */ function do_shortcode_by_tags( $content, array $tags ) { global $shortcode_tags; $_tags = $shortcode_tags; foreach ( $_tags as $tag => $callback ) { if ( ! in_array( $tag, $tags, true ) ) { unset( $shortcode_tags[ $tag ] ); } } $shortcoded = do_shortcode( $content ); $shortcode_tags = $_tags; return $shortcoded; } function initialize_sentry() { try { $sentry_key = env( 'SENTRY_KEY' ) ?: ''; $sentry_organization = env( 'SENTRY_ORGANIZATION' ) ?: ''; $sentry_project = env( 'SENTRY_PROJECT' ) ?: ''; \Sentry\init( [ 'dsn' => 'https://' . $sentry_key . '@' . $sentry_organization . '.ingest.sentry.io/' . $sentry_project, 'environment' => env( 'WP_ENV' ) ?: 'staging', ] ); return true; } catch ( \Exception $exception ) { debug_error_log( 'Error initializing Sentry: ' . $exception->getMessage() ); } return false; }
{ "pile_set_name": "Github" }