answer
stringlengths
15
1.25M
# Numenta Platform for Intelligent Computing (NuPIC) # following terms and conditions apply: # This program is free software: you can redistribute it and/or modify # published by the Free Software Foundation. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. import os import ray import torch import torch.optim from ray import tune import nupic.research.frameworks.backprop_structure.dataset_managers as datasets import nupic.research.frameworks.backprop_structure.experiments as experiments import nupic.research.frameworks.backprop_structure.experiments.mixins as mixins import nupic.research.frameworks.backprop_structure.networks as networks from nupic.research.archive.dynamic_sparse.common.ray_custom_loggers import ( DEFAULT_LOGGERS, ) class <API key>(mixins.UpdateBoostStrength, mixins.TestNoise, experiments.Supervised): pass if __name__ == "__main__": ray.init() tune.run( experiments.as_ray_trainable(<API key>), name=os.path.basename(__file__).replace(".py", ""), config=dict( network_class=networks.<API key>, network_args=dict(), dataset_class=datasets.PreprocessedGSC, dataset_args={}, optim_class=torch.optim.SGD, optim_args=dict( lr=0.01, ), lr_scheduler_class=torch.optim.lr_scheduler.StepLR, lr_scheduler_args=dict( step_size=1, gamma=0.9, ), use_tqdm=False, batch_size_train=16, batch_size_test=1000, noise_test_epochs=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 99], noise_levels=[0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5], ), num_samples=1, checkpoint_freq=0, checkpoint_at_end=True, stop={"training_iteration": 100}, resources_per_trial={ "cpu": 1, "gpu": (1 if torch.cuda.is_available() else 0)}, loggers=DEFAULT_LOGGERS, verbose=1, )
package org.objectweb.proactive.core.group.topology; import org.objectweb.proactive.core.group.Group; import org.objectweb.proactive.core.mop.<API key>; /** * This one is specialy dedicaced to Fabrice ;) * * @author The ProActive Team */ public class Tetrahedron<E> extends TopologyGroup<E> { public Tetrahedron(Group<E> g, int size) throws <API key> { super(g, size); for (int i = 0; i < size; i++) { this.add(g.get(i)); } } }
@-webkit-keyframes ball-scale{0%{-webkit-transform:scale(0);transform:scale(0)}100%{-webkit-transform:scale(1);transform:scale(1);opacity:0}}@-moz-keyframes ball-scale{0%{-moz-transform:scale(0);transform:scale(0)}100%{-moz-transform:scale(1);transform:scale(1);opacity:0}}@-o-keyframes ball-scale{0%{-o-transform:scale(0);transform:scale(0)}100%{-o-transform:scale(1);transform:scale(1);opacity:0}}@keyframes ball-scale{0%{-webkit-transform:scale(0);-moz-transform:scale(0);-o-transform:scale(0);transform:scale(0)}100%{-webkit-transform:scale(1);-moz-transform:scale(1);-o-transform:scale(1);transform:scale(1);opacity:0}}.ball-scale>div{background-color:#404E67;border-radius:100%;margin:2px;display:inline-block;height:60px;width:60px;-webkit-animation:ball-scale 1s 0s ease-in-out infinite;-moz-animation:ball-scale 1s 0s ease-in-out infinite;-o-animation:ball-scale 1s 0s ease-in-out infinite;animation:ball-scale 1s 0s ease-in-out infinite}
#! /usr/bin/env python # -*- coding: utf-8 -*- # Any Indian Language to any other Indian language transliterator # This program is free software; you can redistribute it and/or modify # (at your option) any later version. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # If you find any bugs or have any suggestions email: santhosh.thottingal@gmail.com import string import os CMU_MALAYALAM_MAP = { "AA" : "ഓ", "AH" : "അ", "AE" : "ഏ", "AO" : "ഓ", "AW" : "ഔ", "AY" : "ഐ", "B" : "ബ്", "CH" : "ച്ച്", "D" : "ഡ്", "DH" : "ദ്", "EA" : "ഈ", "EH" : "എ", "ER" : "എര്‍", "EY" : "എയ്", "F" : "ഫ്", "G" : "ഗ്", "HH" : "ഹ്", "IH" : "ഇ", "IY" : "ഈ", "J" : "ജ്", "JH" : "ജ്", "K" : "ക്", "L" : "ല്‍", "M" : "മ്", "N" : "ന്‍", "NG" : "ങ്", "OW" : "ഒ", "P" : "പ്", "R" : "ര്‍", "S" : "സ്", "SH" : "ഷ്", "T" : "റ്റ്", "TH" : "ത്", "Y" : "യ്", "UW" : "ഉ", "W" : "വ്", "V" : "വ്", "Z" : "സ്", } CMU_KANNADA_MAP = { "AA" : "ಆ", "AH" : "ಅ", "AE" : "ಏ", "AO" : "ಓ", "AW" : "ಔ", "AY" : "ಐ", "B" : "ಬ್", "CH" : "ಚ್", "D" : "ಡ್", "DH" : "ದ್", "EA" : "ಈ", "EH" : "ಎ", "ER" : "ಅರ್", "EY" : "ಎಯ್", "F" : "ಫ್", "G" : "ಗ್", "HH" : "ಹ್", "IH" : "ಇ", "IY" : "ಈ", "J" : "ಜ್", "JH" : "ಜ್", "K" : "ಕ್", "L" : "ಲ್", "M" : "ಮ್", "N" : "ನ್", "NG" : "ಂಗ್", "OW" : "ಒ", "P" : "ಪ್", "R" : "ರ್", "S" : "ಸ್", "SH" : "ಷ್", "T" : "ಟ್", "TH" : "ತ್", "Y" : "ಯ್", "UW" : "ಊ", "UH":"ಉ", "W" : "ವ್", "V" : "ವ್", "Z":"ಸ್", "ZH":"ಷ್", } class CMUDict(): def __init__(self): self.dictionaryfile=os.path.join(os.path.dirname(__file__), 'cmudict.0.7a_SPHINX_40') self.cmudictionary = None def load(self): fdict = open(self.dictionaryfile, "r") flines = fdict.readlines() linecount = len(flines) self.cmudictionary = dict() for line in flines: line = line.strip() lhs = line.split()[0] rhs = line.split()[1:] self.cmudictionary[lhs] = rhs def find(self, word): if self.cmudictionary== None: self.load() return self.cmudictionary[word.upper()] def pronunciation(self,word, language): stripped_word = word.strip('!,.?:') punctuations = word[len(stripped_word):] try: cmu_pronunciation = self.find(stripped_word) except KeyError: #print "could not find the word " + stripped_word + " in dictionary" return word pronunciation_str = "" if language =="ml_IN": for syl in cmu_pronunciation: try: pronunciation_str += CMU_MALAYALAM_MAP[syl] except KeyError: pronunciation_str += syl pronunciation_str = self._fix_vowel_signs_ml(pronunciation_str) if language == "kn_IN": for symbol in cmu_pronunciation: try: pronunciation_str += CMU_KANNADA_MAP[symbol] except KeyError: pronunciation_str += symbol pronunciation_str = self._fix_vowel_signs_kn(pronunciation_str) return (pronunciation_str).decode("utf-8") + punctuations def _fix_vowel_signs_ml(self,text) : text= text.replace("്അ","") text= text.replace("്‍അ","") text= text.replace("്ആ","ാ") text= text.replace("്‍ആ","ാ") text= text.replace("്ഇ","ി") text= text.replace("്‍ഇ","ി") text= text.replace("്ഈ","ീ") text= text.replace("്‍ഈ","ീ") text= text.replace("്ഉ","ു") text= text.replace("്‍ഉ","ു") text= text.replace("്ഊ","ൂ") text= text.replace("്‍ഊ","ൂ") text= text.replace("്റ","്ര") text= text.replace("്എ","െ") text= text.replace("്‍എ","") text= text.replace("്ഏ","േ") text= text.replace("്‍ഏ","േ") text= text.replace("്ഐ","ൈ") text= text.replace("്‍ഐ","ൈ") text= text.replace("്ഒ","ൊ") text= text.replace("്‍ഒ","ൊ") text= text.replace("്ഓ","ോ") text= text.replace("്‍ഓ","ോ") text= text.replace("്ഔ","ൌ") text= text.replace("്‍ഔ","ൌ") text= text.replace("ര്ര","റ്റ") text= text.replace("റ്ര","റ്റ") text= text.replace("ന്‍റ്റ","ന്റ") return text def _fix_vowel_signs_kn(self,text) : text= text.replace("್ಅ","") text= text.replace("್ಆ","ಾ") text= text.replace("್ಇ","ಿ") text= text.replace("್ಈ","ೀ") text= text.replace("್ಉ","ು") text= text.replace("್ಊ","ೂ") text= text.replace("್ಋ","ೃ") text= text.replace("್ಎ","ೆ") text= text.replace("್ಏ","ೇ") text= text.replace("್ಐ","ೈ") text= text.replace("್ಒ","ೊ") text= text.replace("್ಓ","ೋ") text= text.replace("್ಔ","ೌ") return text
using System; using ASC.Xmpp.Core.protocol.extensions.compression; using ASC.Xmpp.Core.utils.Xml.Dom; namespace ASC.Xmpp.Core.protocol.stream.feature.compression { public class Method : Element { #region << Constructors >> public Method() { TagName = "method"; Namespace = Uri.FEATURE_COMPRESS; } public Method(CompressionMethod method) : this() { Value = method.ToString(); } #endregion public CompressionMethod CompressionMethod { get { #if CF return (CompressionMethod) util.Enum.Parse(typeof(CompressionMethod), this.Value, true); #else return (CompressionMethod) Enum.Parse(typeof (CompressionMethod), Value, true); #endif } set { Value = value.ToString(); } } } }
package org.opennms.web.graph; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.opennms.netmgt.model.OnmsResource; import org.opennms.netmgt.model.PrefabGraph; import org.opennms.netmgt.model.RrdGraphAttribute; /** * <p>Graph class.</p> * * @author ranger * @version $Id: $ * @since 1.8.1 */ public class Graph implements Comparable<Graph> { private PrefabGraph m_graph = null; private OnmsResource m_resource; private Date m_start = null; private Date m_end = null; /** * <p>Constructor for Graph.</p> * * @param graph a {@link org.opennms.netmgt.model.PrefabGraph} object. * @param resource a {@link org.opennms.netmgt.model.OnmsResource} object. * @param start a {@link java.util.Date} object. * @param end a {@link java.util.Date} object. */ public Graph(PrefabGraph graph, OnmsResource resource, Date start, Date end) { m_graph = graph; m_resource = resource; m_start = start; m_end = end; } /** * <p>getResource</p> * * @return a {@link org.opennms.netmgt.model.OnmsResource} object. */ public OnmsResource getResource() { return m_resource; } /** * <p>getStart</p> * * @return a {@link java.util.Date} object. */ public Date getStart() { return m_start; } /** * <p>getEnd</p> * * @return a {@link java.util.Date} object. */ public Date getEnd() { return m_end; } /** * <p>getName</p> * * @return a {@link java.lang.String} object. */ public String getName() { return m_graph.getName(); } /** * <p>getTitle</p> * * @return a {@link java.lang.String} object. */ public String getTitle() { return m_graph.getTitle(); } /** * <p>compareTo</p> * * @param other a {@link org.opennms.web.graph.Graph} object. * @return a int. */ @Override public int compareTo(Graph other) { if (other == null) { return -1; } return m_graph.compareTo(other.m_graph); } /** * <p>getGraphWidth</p> * * @return a {@link java.lang.Integer} object. */ public Integer getGraphWidth() { return m_graph.getGraphWidth(); } /** * <p>getGraphHeight</p> * * @return a {@link java.lang.Integer} object. */ public Integer getGraphHeight() { return m_graph.getGraphHeight(); } /** * <p>getPrefabGraph</p> * * @return a {@link org.opennms.netmgt.model.PrefabGraph} object. */ public PrefabGraph getPrefabGraph() { return m_graph; } /** * <p>getReport</p> * * @return a {@link java.lang.String} object. */ public String getReport() { return m_graph.getName(); } /** * <p><API key></p> * * @return a {@link java.util.Collection} object. */ public Collection<RrdGraphAttribute> <API key>() { Map<String, RrdGraphAttribute> available = m_resource.<API key>(); Set<RrdGraphAttribute> reqAttrs = new LinkedHashSet<RrdGraphAttribute>(); for(String attrName : m_graph.getColumns()) { RrdGraphAttribute attr = available.get(attrName); if (attr != null) { reqAttrs.add(attr); } } return reqAttrs; } }
@file @author Don Gagne <don@thegagnes.com> #include "<API key>.h" #include "<API key>.h" <API key>::<API key>(Vehicle* vehicle, AutoPilotPlugin* autopilot, QObject* parent) : VehicleComponent(vehicle, autopilot, parent) , _requiresFrameSetup(false) , _name("Airframe") { if (qobject_cast<<API key>*>(_vehicle->firmwarePlugin()) != NULL) { _requiresFrameSetup = true; MAV_TYPE vehicleType = vehicle->vehicleType(); if (vehicleType == MAV_TYPE_TRICOPTER || vehicleType == MAV_TYPE_HELICOPTER) { _requiresFrameSetup = false; } } } QString <API key>::name(void) const { return _name; } QString <API key>::description(void) const { return tr("The Airframe Component is used to select the airframe which matches your vehicle. " "This will in turn set up the various tuning values for flight parameters."); } QString <API key>::iconResource(void) const { return QStringLiteral("/qmlimages/<API key>.png"); } bool <API key>::requiresSetup(void) const { return _requiresFrameSetup; } bool <API key>::setupComplete(void) const { if (_requiresFrameSetup) { return _autopilot->getParameterFact(FactSystem::defaultComponentId, QStringLiteral("FRAME"))->rawValue().toInt() >= 0; } else { return true; } } QStringList <API key>::<API key>(void) const { QStringList list; if (_requiresFrameSetup) { list << QStringLiteral("FRAME"); } return list; } QUrl <API key>::setupSource(void) const { if (_requiresFrameSetup) { return QUrl::fromUserInput(QStringLiteral("qrc:/qml/<API key>.qml")); } else { return QUrl(); } } QUrl <API key>::summaryQmlSource(void) const { if (_requiresFrameSetup) { return QUrl::fromUserInput(QStringLiteral("qrc:/qml/<API key>.qml")); } else { return QUrl(); } } QString <API key>::prerequisiteSetup(void) const { return QString(); }
title: messages.chatsSlice description: messages_chatsSlice attributes, type and example ## Constructor: messages.chatsSlice [Back to constructors index](index.md) Attributes: | Name | Type | Required | | |count|[int](../types/int.md) | Yes| |chats|Array of [Chat](../types/Chat.md) | Yes| Type: [messages\_Chats](../types/messages_Chats.md) Example: $messages_chatsSlice = ['_' => 'messages.chatsSlice', 'count' => int, 'chats' => [Chat], ]; Or, if you're into Lua: messages_chatsSlice={_='messages.chatsSlice', count=int, chats={Chat}, }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="<API key>=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script> <script type="text/javascript" src="vendor/swag/lib/swag.js"></script> <script type="text/javascript" src="js/data.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link href="css/user.css" rel="stylesheet"> <script> $(document).ready(function(){ var template = Handlebars.compile($("#<API key>").html()); $("#content").append(template(data)); var input = document.getElementById('searchTextField'); var options = { types: ['(cities)'], <API key>: {country: "us"} }; autocomplete = new google.maps.places.Autocomplete(input,options); google.maps.event.addListener(autocomplete, 'place_changed', function () { var place = autocomplete.getPlace(); document.getElementById('state').value = place.address_components[2].short_name; document.getElementById('city').value = place.name; document.getElementById('latitude').value = place.geometry.location.lat(); document.getElementById('longitude').value = place.geometry.location.lng(); }); }); </script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<Google Api>&libraries=places"></script> <script type="text/javascript" src="js/public.js"></script> </head> <body> <div class="container"> <a href="./"><h2> <img src="img/logo.png" height="50">Affinity</h2></a> <hr> <h2>Find a local group</h2> <div class="row"> <form class="form form-inline"> <div class="form-group col-md-6 col-md-offset-4"> <input id="searchTextField" placeholder="Enter a city" type="text" class="form-control text-center" /> <input id="city" name="city" type="hidden"> <input id="state" name="state" type="hidden"> <input id="latitude" name="latitude" type="hidden"> <input id="longitude" name="longitude" type="hidden"> <button class="btn btn-primary text-center">Find a Group</button> </div> </form> </div> <hr> <div id="content"></div> <script id="<API key>" type="text/<API key>"> <h3>Groups near you</h3> {{#each groups.0.nearby_groups}} <h4><a href="{{url}}">{{name}}</a></h4> {{distance}} miles away ({{city}}) {{/each}} </script> </div> </body> </html>
{% extends "site_base.html" %} {% load staticfiles %} {% load i18n %} {% load bootstrap_tags %} {% block head_title %}{% trans "Unfold" %} {{ process.name }}{% endblock %} {% block extra_head %} <style> .title { color: firebrick; } .emph { font-weight: bold; } #focus { border: solid 1px gainsboro; background-color: beige; padding: 4px; margin-bottom: 7px; } .prevnext { border: solid 1px gainsboro; background-color: whitesmoke; padding: 4px; margin-bottom: 7px; width: 80%; } .description { font-style: italic; font-size: 8pt; } .explain { color: #9EA6AE; } .et { color: forestgreen; font-weight: bold; } .section { border: solid 1px gainsboro; margin-top: 10px; padding: 5px; } .this { color: firebrick; font-weight: bold; background-color: #FFFFD6; } .thisblock { background-color: #FFFFD6; } .details { margin-top: 10px; } </style> {% endblock %} {% block body_class %}unfold{% endblock %} {% block body_base %} <div class="container"> {% include "_messages.html" %} <div class="row-fluid"> <div class="span3"> <div class="explain"> <p>A Process takes inputs and transforms them into outputs, and may be connected to other Processes in process flows. {% if commitment %} The work of <span class="this">{{ commitment.resource_type.name }}</span> contributes to This Process. </p> {% endif %} </div> </div> <div class="span6"> <div> <span class="explain">A Process happens in an organizational Context.</span></br> <span class="emph" >{% trans "Context" %}:</span> The {{ process.context_agent.agent_type }} <a href="{{ process.context_agent.get_absolute_url }}">{{ process.context_agent.name }}</a> {% if process.context_agent.description %} <div class="description">{{ process.context_agent.description|urlize|linebreaks }}</div> {% endif %} </div> {% if process.independent_demand %} <div><span class="explain"> {% if process.next_processes or process.previous_processes %} This process is connected to other processes to fulfill a {{ process.independent_demand.<API key> }}.</br> {% else %} This process fulfills a {{ process.independent_demand.<API key> }}.</br> {% endif %}</span> <span class="emph" >{% trans "Order" %}:</span> <a href="{% url order_schedule order_id=process.independent_demand.id %}">{{ process.independent_demand }}</a> {% if process.independent_demand.description %} <div class="description">{{ process.independent_demand.description|urlize|linebreaks }}</div> {% endif %} </div> {% endif %} </div> <div class="span3"> <div><a href="{% url projects %}">{% trans "All Contexts" %}</a></div> {% if process.independent_demand %} <div><a href="{% url demand %}">{% trans "All Orders" %}</a></div> {% endif %} </div> </div> <div class="section"> <div class="row-fluid"> <div class="span3"> <div class="prevnext pull-left"> <h4 class="title">{% trans "Previous processes" %}:</h4> {% for proc in process.previous_processes %} <p><span class="process" ><a href="{% url unfold_process process_id=proc.id %}">{{ proc }}</a></span></p> {% endfor %} </div> <img class="pull-left" src="{% static 'img/right.png' %}" /> </div> <div class="span6" id="focus" > <h4 class="title">{% trans "This Process" %}:</h4> <a href="{{ process.get_absolute_url }}">{{ process }}</a> {% if process.notes %} <div class="description">{{ process.notes|urlize|linebreaks }}</div> {% endif %} <div class="row-fluid"> <div class="span6 details"> <h4>{% trans "Input requirements" %}:</h4> {% for item in process.<API key> %} <div{% if item.id == commitment.id %} class="thisblock"{% endif %}> <span class="et">{{ item.event_type }}</span> {% if item.id == commitment.id %}<span class="this">{% endif %} {{ item.resource_type }} {% if item.id == commitment.id %}</span>{% endif %} {% if item.event_type.name != "Citation" %} {{ item.quantity }} {{ item.unit_of_quantity }} {% endif %} </div> {% if item.description %} <div class="description{% if item.id == commitment.id %} thisblock{% endif %}">{{ item.description|urlize|linebreaks }}</div> {% endif %} {% endfor %} </div> <div class="span6 details"> <h4>{% trans "Output plans" %}:</h4> {% for item in process.<API key> %} <div>{{ item.resource_type }} {{ item.quantity }} {{ item.unit_of_quantity }}</div> {% if item.description %} <div class="description">{{ item.description|urlize|linebreaks }}</div> {% endif %} {% endfor %} {% if process.production_events %} <h4>{% trans "Resources created" %}:</h4> {% for item in process.production_events %} <div> <a href="{{ item.resource.get_absolute_url }}"> {{ item.resource }} </a> </div> {% endfor %} {% endif %} </div> </div> </div> <div class="span3"> <img class="pull-left" src="{% static 'img/right.png' %}" /> <div class="prevnext pull-left"> <h4 class="title">{% trans "Next processes" %}:</h4> {% for proc in process.next_processes %} <p><span class="process" ><a href="{% url unfold_process process_id=proc.id %}">{{ proc }}</a></span></p> {% endfor %} </div> </div> </div> </div> </div> {% endblock %} {% block extra_script %} <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> {% endblock %} {% block extra_body %} {{ block.super }} <script type="text/javascript"> $(document).ready(function(){ $("#connections").on( "click", "button", connect ); }); // end document.ready function connect(event) { var target = event.target; var li = target.parentNode; var nbr = parseInt(target.id[1]); nbr += 1; var lid = "#" + li.id; var nextLid = 'l' + nbr; nextLid = '"' + nextLid + '"'; var nextBid = 'c' + nbr; nextBid = '"' + nextBid + '"'; var insert = '<ul><li id=' + nextLid + '>Something else <button id='+ nextBid + ' class="btn btn-info btn-mini" >Connections</button></li></ul>'; $(lid).after(insert); } </script> {% endblock %}
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ class ForecastFlowAddEdit extends GenericAddEdit { /** * onBeforeDisplay * * @access protected * @return void */ protected function onBeforeDisplay() { // euro par default $this->formDefaults['<API key>'] = 1; $this->form->setDefaults($this->formDefaults); } /** * <API key> * * @access protected * @return void */ protected function <API key>() { $d1 = explode('-', $this->object->getBeginDate()); $d2 = explode('-', $this->object->getEndDate()); $ts1 = mktime(0,0,0, $d1[1], $d1[2], $d1[0]); $ts2 = mktime(0,0,0, $d2[1], $d2[2], $d2[0]); if($d1[1] != $d2[1] || $d1[0] != $d2[0]) { $m1 = $d1[1]; $m2 = $d2[1]; $y1 = $d1[0]; $y2 = $d2[0]; // on modifie la date de fin de la charge existante $ts = mktime(23,59,59, $m1, date('t', $ts1), $y1); $date = date('Y-m-d', $ts); $this->object->setEndDate($date); while($m1 != $m2 || $y1 != $y2) { // calule les dates $d1 = date('Y-m-d', $ts+1); $ts = mktime(23,59,59, date('m', $ts+1), date('t', $ts+1), date('Y', $ts+1)); $d2 = date('Y-m-d', $ts); $o = Tools::duplicateObject($this->object); $o->setBeginDate($d1); $o->setEndDate($d2); $o-><API key>($this->object-><API key>()); $o->save(); $d2 = explode('-', $d2); $m1 = $d2[1]; $y1 = $d2[0]; } } } } ?>
package im.actor.sdk.controllers.conversation.messages.content; import android.app.Activity; import android.graphics.Bitmap; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import com.droidkit.progress.CircularView; import im.actor.core.entity.FileReference; import im.actor.core.entity.Message; import im.actor.core.entity.Peer; import im.actor.core.entity.content.DocumentContent; import im.actor.core.entity.content.FileLocalSource; import im.actor.core.entity.content.FileRemoteSource; import im.actor.core.entity.content.PhotoContent; import im.actor.core.viewmodel.FileCallback; import im.actor.core.viewmodel.FileVM; import im.actor.core.viewmodel.FileVMCallback; import im.actor.core.viewmodel.UploadFileCallback; import im.actor.core.viewmodel.UploadFileVM; import im.actor.core.viewmodel.<API key>; import im.actor.sdk.ActorSDK; import im.actor.sdk.R; import im.actor.sdk.controllers.Intents; import im.actor.sdk.controllers.conversation.messages.MessagesAdapter; import im.actor.sdk.controllers.conversation.messages.content.preprocessor.PreprocessedData; import im.actor.sdk.util.FileTypes; import im.actor.sdk.util.images.common.ImageLoadException; import im.actor.sdk.util.images.ops.ImageLoading; import im.actor.sdk.view.TintImageView; import im.actor.runtime.files.FileSystemReference; import static im.actor.sdk.util.ActorSDKMessenger.myUid; import static im.actor.sdk.util.ViewUtils.goneView; import static im.actor.sdk.util.ViewUtils.showView; import static im.actor.sdk.util.ActorSDKMessenger.messenger; public class DocHolder extends MessageHolder { private int waitColor; private int sentColor; private int deliveredColor; private int readColor; private int errorColor; private final TintImageView stateIcon; protected final TextView time; // Basic bubble protected View menu; // Content views protected TextView fileName; protected TextView fileSize; protected TextView status; protected ImageView fileIcon; // Progress views protected TintImageView downloadIcon; protected CircularView progressView; protected TextView progressValue; // Binded model protected FileVM downloadFileVM; protected UploadFileVM uploadFileVM; protected DocumentContent document; public DocHolder(final MessagesAdapter adapter, View itemView, Peer peer) { this(adapter, itemView, false, peer); } public DocHolder(final MessagesAdapter fragment, View itemView, boolean isFullSize, Peer peer) { super(fragment, itemView, isFullSize); waitColor = ActorSDK.sharedActor().style.<API key>(); sentColor = ActorSDK.sharedActor().style.<API key>(); deliveredColor = ActorSDK.sharedActor().style.<API key>(); readColor = ActorSDK.sharedActor().style.<API key>(); errorColor = ActorSDK.sharedActor().style.<API key>(); stateIcon = (TintImageView) itemView.findViewById(R.id.stateIcon); time = (TextView) itemView.findViewById(R.id.time); time.setTextColor(ActorSDK.sharedActor().style.getConvTimeColor()); // Basic bubble View bubbleView = itemView.findViewById(R.id.bubbleContainer); bubbleView.<API key>(R.drawable.<API key>); menu = itemView.findViewById(R.id.menu); menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(fragment.getMessagesFragment().getActivity(), v); popup.getMenuInflater().inflate(R.menu.doc_popup, popup.getMenu()); popup.<API key>(new PopupMenu.<API key>() { @Override public boolean onMenuItemClick(MenuItem item) { if (currentMessage != null && currentMessage.getContent() instanceof DocumentContent) { final DocumentContent documentContent = (DocumentContent) currentMessage.getContent(); if (documentContent.getSource() instanceof FileRemoteSource) { FileRemoteSource remoteSource = (FileRemoteSource) documentContent.getSource(); messenger().requestState(remoteSource.getFileReference().getFileId(), new FileCallback() { @Override public void onNotDownloaded() { } @Override public void onDownloading(float progress) { } @Override public void onDownloaded(FileSystemReference reference) { Activity activity = getAdapter().getMessagesFragment().getActivity(); activity.startActivity(Intents.shareDoc(documentContent.getName(), reference.getDescriptor())); } }); } } return true; } }); popup.show(); } }); // Content views fileName = (TextView) itemView.findViewById(R.id.fileName); fileName.setTextColor(ActorSDK.sharedActor().style.getTextPrimaryColor()); fileSize = (TextView) itemView.findViewById(R.id.fileSize); fileSize.setTextColor(ActorSDK.sharedActor().style.getTextHintColor()); status = (TextView) itemView.findViewById(R.id.status); status.setTextColor(ActorSDK.sharedActor().style.<API key>()); fileIcon = (ImageView) itemView.findViewById(R.id.icon); // Progress views downloadIcon = (TintImageView) itemView.findViewById(R.id.downloading); downloadIcon.setTint(ActorSDK.sharedActor().style.getMainColor()); progressView = (CircularView) itemView.findViewById(R.id.progressView); progressView.setColor(ActorSDK.sharedActor().style.getMainColor()); progressValue = (TextView) itemView.findViewById(R.id.progressValue); progressValue.setTextColor(ActorSDK.sharedActor().style.<API key>()); <API key>(); } @Override protected void bindData(Message message, long readDate, long receiveDate, boolean isUpdated, PreprocessedData preprocessedData) { document = (DocumentContent) message.getContent(); // Update state if (message.getSenderId() == myUid()) { stateIcon.setVisibility(View.VISIBLE); switch (message.getMessageState()) { case ERROR: stateIcon.setResource(R.drawable.msg_error); stateIcon.setTint(errorColor); break; default: case PENDING: stateIcon.setResource(R.drawable.msg_clock); stateIcon.setTint(waitColor); break; case SENT: if (message.getSortDate() <= readDate) { stateIcon.setResource(R.drawable.msg_check_2); stateIcon.setTint(readColor); } else if (message.getSortDate() <= receiveDate) { stateIcon.setResource(R.drawable.msg_check_2); stateIcon.setTint(deliveredColor); } else { stateIcon.setResource(R.drawable.msg_check_1); stateIcon.setTint(sentColor); } break; } } else { stateIcon.setVisibility(View.GONE); } // Update time setTimeAndReactions(time); // Content data fileName.setText(document.getName()); fileSize.setText(messenger().getFormatter().formatFileSize(document.getSource().getSize()) + " " + document.getExt().toUpperCase()); //region File icon if (isUpdated) { boolean isAppliedThumb = false; if (document.getFastThumb() != null) { try { Bitmap img = ImageLoading.loadBitmap(document.getFastThumb().getImage()); fileIcon.setImageBitmap(img); fileIcon.setScaleType(ImageView.ScaleType.FIT_CENTER); isAppliedThumb = true; } catch (ImageLoadException e) { e.printStackTrace(); } } if (!isAppliedThumb) { int type = FileTypes.getType(document.getExt()); switch (type) { default: case FileTypes.TYPE_UNKNOWN: fileIcon.setImageResource(R.drawable.picker_unknown); break; case FileTypes.TYPE_APK: fileIcon.setImageResource(R.drawable.picker_apk); break; case FileTypes.TYPE_MUSIC: fileIcon.setImageResource(R.drawable.picker_music); break; case FileTypes.TYPE_PICTURE: fileIcon.setImageResource(R.drawable.picker_unknown); break; case FileTypes.TYPE_DOC: fileIcon.setImageResource(R.drawable.picker_doc); break; case FileTypes.TYPE_RAR: fileIcon.setImageResource(R.drawable.picker_rar); break; case FileTypes.TYPE_VIDEO: fileIcon.setImageResource(R.drawable.picker_video); break; case FileTypes.TYPE_ZIP: fileIcon.setImageResource(R.drawable.picker_zip); break; case FileTypes.TYPE_XLS: fileIcon.setImageResource(R.drawable.picker_xls); break; case FileTypes.TYPE_PPT: fileIcon.setImageResource(R.drawable.picker_ppt); break; case FileTypes.TYPE_CSV: fileIcon.setImageResource(R.drawable.picker_csv); break; case FileTypes.TYPE_HTM: fileIcon.setImageResource(R.drawable.picker_htm); break; case FileTypes.TYPE_HTML: fileIcon.setImageResource(R.drawable.picker_html); break; case FileTypes.TYPE_PDF: fileIcon.setImageResource(R.drawable.picker_pdf); break; } fileIcon.setScaleType(ImageView.ScaleType.CENTER); } } //endregion // Update view boolean needRebind = false; if (isUpdated) { // Resetting binding if (downloadFileVM != null) { downloadFileVM.detach(); downloadFileVM = null; } if (uploadFileVM != null) { uploadFileVM.detach(); uploadFileVM = null; } needRebind = true; } else { if (document.getSource() instanceof FileLocalSource) { if (uploadFileVM == null && downloadFileVM != null) { downloadFileVM.detach(); downloadFileVM = null; needRebind = true; } } else if (document.getSource() instanceof FileRemoteSource) { if (uploadFileVM != null && downloadFileVM == null) { uploadFileVM.detach(); uploadFileVM = null; needRebind = true; } } } if (downloadFileVM == null && uploadFileVM == null) { needRebind = true; } if (needRebind) { downloadIcon.setVisibility(View.GONE); progressView.setVisibility(View.GONE); progressValue.setVisibility(View.GONE); fileIcon.setVisibility(View.GONE); menu.setVisibility(View.GONE); status.setVisibility(View.GONE); if (document.getSource() instanceof FileRemoteSource) { FileRemoteSource remoteSource = (FileRemoteSource) document.getSource(); boolean autoDownload = remoteSource.getFileReference().getFileSize() <= 1024 * 1024 && messenger().<API key>();// < 1MB downloadFileVM = messenger().bindFile(remoteSource.getFileReference(), autoDownload, new DownloadVMCallback()); } else if (document.getSource() instanceof FileLocalSource) { uploadFileVM = messenger().bindUpload(message.getRid(), new UploadVMCallback()); } } } @Override public void onClick(final Message currentMessage) { if (document.getSource() instanceof FileRemoteSource) { FileRemoteSource remoteSource = (FileRemoteSource) document.getSource(); final FileReference location = remoteSource.getFileReference(); messenger().requestState(location.getFileId(), new FileCallback() { @Override public void onNotDownloaded() { messenger().startDownloading(location); } @Override public void onDownloading(float progress) { messenger().cancelDownloading(location.getFileId()); } @Override public void onDownloaded(final FileSystemReference reference) { im.actor.runtime.Runtime.postToMainThread(new Runnable() { @Override public void run() { if (document instanceof PhotoContent) { Intents.openMedia(getAdapter().getMessagesFragment().getActivity(), fileIcon, reference.getDescriptor(), currentMessage.getSenderId()); } else { try { Activity activity = getAdapter().getMessagesFragment().getActivity(); activity.startActivity(Intents.openDoc(document.getName(), reference.getDescriptor())); } catch (Exception e) { Toast.makeText(getAdapter().getMessagesFragment().getActivity(), R.string.toast_unable_open, Toast.LENGTH_LONG).show(); e.printStackTrace(); } } } }); } }); } else if (document.getSource() instanceof FileLocalSource) { messenger().requestUploadState(currentMessage.getRid(), new UploadFileCallback() { @Override public void onNotUploading() { messenger().resumeUpload(currentMessage.getRid()); } @Override public void onUploading(float progress) { messenger().pauseUpload(currentMessage.getRid()); } @Override public void onUploaded() { // Nothing to do } }); } } @Override public void unbind() { super.unbind(); // Unbinding model if (downloadFileVM != null) { downloadFileVM.detach(); downloadFileVM = null; } if (uploadFileVM != null) { uploadFileVM.detach(); uploadFileVM = null; } } private class DownloadVMCallback implements FileVMCallback { @Override public void onNotDownloaded() { status.setText(R.string.chat_doc_download); showView(status); goneView(menu); // File Icon goneView(fileIcon); downloadIcon.setResource(R.drawable.<API key>); showView(downloadIcon); progressView.setValue(0); goneView(progressValue); goneView(progressView); } @Override public void onDownloading(float progress) { status.setText(R.string.chat_doc_stop); showView(status); goneView(menu); goneView(fileIcon); goneView(downloadIcon); int val = (int) (progress * 100); progressView.setValue(val); progressValue.setText("" + val); showView(progressView); showView(progressValue); } @Override public void onDownloaded(FileSystemReference reference) { status.setText(R.string.chat_doc_open); showView(status); showView(menu); showView(fileIcon); goneView(downloadIcon); goneView(progressValue); goneView(progressView); } } private class UploadVMCallback implements <API key> { @Override public void onNotUploaded() { status.setText(R.string.chat_doc_send); showView(status); goneView(menu); // File Icon goneView(fileIcon); downloadIcon.setResource(R.drawable.<API key>); showView(downloadIcon); progressView.setValue(0); goneView(progressValue); goneView(progressView); } @Override public void onUploading(float progress) { status.setText(R.string.chat_doc_stop); showView(status); goneView(menu); goneView(fileIcon); goneView(downloadIcon); int val = (int) (progress * 100); progressView.setValue(val); progressValue.setText("" + val); showView(progressView); showView(progressValue); } @Override public void onUploaded() { onUploading(1); } } }
package com.esofthead.mycollab.module.crm.domain.criteria; import java.util.Arrays; import com.esofthead.mycollab.common.i18n.GenericI18Enum; import com.esofthead.mycollab.core.arguments.NumberSearchField; import com.esofthead.mycollab.core.arguments.SearchCriteria; import com.esofthead.mycollab.core.arguments.SetSearchField; import com.esofthead.mycollab.core.arguments.StringSearchField; import com.esofthead.mycollab.core.db.query.DateParam; import com.esofthead.mycollab.core.db.query.Param; import com.esofthead.mycollab.core.db.query.PropertyListParam; import com.esofthead.mycollab.core.db.query.PropertyParam; import com.esofthead.mycollab.core.db.query.StringListParam; import com.esofthead.mycollab.core.db.query.StringParam; import com.esofthead.mycollab.module.crm.CrmDataTypeFactory; import com.esofthead.mycollab.module.crm.i18n.OpportunityI18nEnum; /** * * @author MyCollab Ltd. * @since 1.0 * */ public class <API key> extends SearchCriteria { private static final long serialVersionUID = 1L; public static final Param p_opportunityName = new StringParam("opportunity-name", OpportunityI18nEnum.FORM_NAME, "m_crm_opportunity", "opportunityName"); public static final Param p_account = new PropertyParam("opportunity-account", OpportunityI18nEnum.FORM_ACCOUNT_NAME, "m_crm_opportunity", "accountid"); public static final Param p_campaign = new PropertyParam("<API key>", OpportunityI18nEnum.FORM_CAMPAIGN_NAME, "m_crm_opportunity", "campaignid"); public static final Param p_nextStep = new StringParam("<API key>", OpportunityI18nEnum.FORM_NEXT_STEP, "m_crm_opportunity", "nextStep"); public static final Param p_saleStage = new StringListParam( "<API key>", OpportunityI18nEnum.FORM_SALE_STAGE, "m_crm_opportunity", "salesStage", Arrays.asList(CrmDataTypeFactory .<API key>())); public static final Param p_leadSource = new StringListParam( "<API key>", OpportunityI18nEnum.FORM_LEAD_SOURCE, "m_crm_opportunity", "source", Arrays.asList(CrmDataTypeFactory .getLeadSourceList())); public static final Param p_type = new StringListParam("opportunity-type", OpportunityI18nEnum.FORM_TYPE, "m_crm_opportunity", "type", Arrays.asList(CrmDataTypeFactory.<API key>())); public static final Param p_assignee = new PropertyListParam( "<API key>", GenericI18Enum.FORM_ASSIGNEE, "m_crm_opportunity", "assignUser"); public static final Param <API key> = new DateParam( "<API key>", OpportunityI18nEnum.<API key>, "m_crm_opportunity", "expectedClosedDate"); public static final Param p_createdtime = new DateParam( "<API key>", GenericI18Enum.FORM_CREATED_TIME, "m_crm_opportunity", "createdTime"); public static final Param p_lastupdatedtime = new DateParam( "<API key>", GenericI18Enum.<API key>, "m_crm_opportunity", "lastUpdatedTime"); private StringSearchField opportunityName; private SetSearchField<String> assignUsers; private NumberSearchField accountId; private NumberSearchField contactId; private NumberSearchField campaignId; private SetSearchField<String> salesStages; private SetSearchField<String> leadSources; private NumberSearchField id; public StringSearchField getOpportunityName() { return opportunityName; } public void setOpportunityName(StringSearchField opportunityName) { this.opportunityName = opportunityName; } public void setAssignUsers(SetSearchField<String> assignUsers) { this.assignUsers = assignUsers; } public SetSearchField<String> getAssignUsers() { return assignUsers; } public NumberSearchField getAccountId() { return accountId; } public void setAccountId(NumberSearchField accountId) { this.accountId = accountId; } public NumberSearchField getContactId() { return contactId; } public void setContactId(NumberSearchField contactId) { this.contactId = contactId; } public NumberSearchField getCampaignId() { return campaignId; } public void setCampaignId(NumberSearchField campaignId) { this.campaignId = campaignId; } public void setSalesStages(SetSearchField<String> salesStages) { this.salesStages = salesStages; } public SetSearchField<String> getSalesStages() { return salesStages; } public void setLeadSources(SetSearchField<String> leadSources) { this.leadSources = leadSources; } public SetSearchField<String> getLeadSources() { return leadSources; } public void setId(NumberSearchField id) { this.id = id; } public NumberSearchField getId() { return id; } }
// This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #if !defined(<API key>) #define <API key> #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #ifndef <API key> #include <afxcmn.h> // MFC support for Windows Common Controls #endif // <API key> //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(<API key>)
@file @author Pritam Ghanghas <pritam.ghanghas@gmail.com> #include "<API key>.h" APMRoverMode::APMRoverMode(uint32_t mode, bool settable) : APMCustomMode(mode, settable) { QMap<uint32_t,QString> enumToString; enumToString.insert(MANUAL, "Manual"); enumToString.insert(LEARNING, "Learning"); enumToString.insert(STEERING, "Steering"); enumToString.insert(HOLD, "Hold"); enumToString.insert(AUTO, "Auto"); enumToString.insert(RTL, "RTL"); enumToString.insert(GUIDED, "Guided"); enumToString.insert(INITIALIZING, "Initializing"); <API key>(enumToString); } <API key>::<API key>(void) { QList<APMCustomMode> <API key>; <API key> << APMRoverMode(APMRoverMode::MANUAL ,true); <API key> << APMRoverMode(APMRoverMode::LEARNING ,true); <API key> << APMRoverMode(APMRoverMode::STEERING ,true); <API key> << APMRoverMode(APMRoverMode::HOLD ,true); <API key> << APMRoverMode(APMRoverMode::AUTO ,true); <API key> << APMRoverMode(APMRoverMode::RTL ,true); <API key> << APMRoverMode(APMRoverMode::GUIDED ,true); <API key> << APMRoverMode(APMRoverMode::INITIALIZING ,false); setSupportedModes(<API key>); }
# This file is part of Canvas. # Canvas is free software: you can redistribute it and/or modify it under # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # details. class <API key> < ActiveRecord::Migration[4.2] tag :predeploy def self.up add_column :collections, :followers_count, :integer, :default => 0 add_column :collections, :items_count, :integer, :default => 0 end def self.down remove_column :collections, :followers_count remove_column :collections, :items_count end end
/* Purpuse : make modifications in dbc file for ascent project to set values that are missing for spells in able to work Warning : Output result is changed in order to obtain ascent specific data. Do not try to use or interpret data for anything else Warning : SpellEntry + <API key> + SPELL_ENTRY must have the same structure !!! project status : not finished yet..not tested */ #include <stdio.h> #include <tchar.h> #include <stdlib.h> #include "dbcfile.h" #include "TaxiPathDataDefines.h" DBCFile dbc; //make this after the main void dump_as_sql(); void main() { dbc.open("TaxiPathNode.dbc"); if (!dbc.getFieldCount()) { printf("error, could not open dbc file\n"); exit(1); } else printf("Opened DBC with %u fields and %u rows\n", (int)dbc.getFieldCount(), (int)dbc.getRecordCount()); dump_as_sql(); // getch(); } void main2(); void dump_as_sql() { if (COLUMN_COUNT != dbc.getFieldCount()) { printf("error,column counts do not match update code for latest dbc format\n"); exit(1); } printf("will start dumping data into sql file (we will drop not required fields!)\n"); FILE *fsql = fopen("dbc_taxi_path_node.sql", "w"); //drop table if already exist fprintf(fsql, "%s", "DROP TABLE IF EXISTS `dbc_taxi_path_node`;\n"); //create the table fprintf(fsql, "%s", "CREATE TABLE dbc_taxi_path_node (\n"); for (int i = 0; i < COLUMN_COUNT; i++) if (<API key>[i][2][0] == '0') { if (<API key>[i][0][0] == 'u') fprintf(fsql, "\t `%s` INT (11) UNSIGNED DEFAULT '0' NOT NULL,\n", <API key>[i][1]); else if (<API key>[i][0][0] == 'i') fprintf(fsql, "\t `%s` INT (11) DEFAULT '0' NOT NULL,\n", <API key>[i][1]); else if (<API key>[i][0][0] == 'f') fprintf(fsql, "\t `%s` FLOAT DEFAULT '0' NOT NULL,\n", <API key>[i][1]); else if (<API key>[i][0][0] == 's') fprintf(fsql, "\t `%s` VARCHAR(2000),\n", <API key>[i][1]); } fprintf(fsql, "%s", "PRIMARY KEY(id), UNIQUE(id), INDEX(id));\n"); fprintf(fsql, "\n\n"); //start dumping the data from the DBC char tstr[2000]; for (unsigned int j = 0; j < dbc.getRecordCount(); j++) { //we start a new insert block if ((j % <API key>) == 0) { fprintf(fsql, "%s", "INSERT INTO dbc_taxi_path_node ("); for (int i = 0; i < COLUMN_COUNT - 1; i++) if (<API key>[i][2][0] == '0') fprintf(fsql, "`%s`,", <API key>[i][1]); fprintf(fsql, "`%s`) values \n", <API key>[COLUMN_COUNT - 1][1]); fprintf(fsql, " ("); } else fprintf(fsql, ",("); for (int i = 0; i < COLUMN_COUNT; i++) if (<API key>[i][2][0] == '0') { if (i != 0) fprintf(fsql, ","); if (<API key>[i][0][0] == 'u') fprintf(fsql, "%u", dbc.getRecord(j).getUInt(i)); else if (<API key>[i][0][0] == 'i') fprintf(fsql, "%d", dbc.getRecord(j).getInt(i)); else if (<API key>[i][0][0] == 'f') fprintf(fsql, "%f", dbc.getRecord(j).getFloat(i)); else if (<API key>[i][0][0] == 's') { const char *dstr = dbc.getRecord(j).getString(i); int otherindex = 0; for (unsigned int k = 0; k <= strlen(dstr); k++) if (dstr[k] == '\'' || dstr[k] == '"' || dstr[k] == '#' || dstr[k] == '-') { tstr[otherindex++] = '\\'; tstr[otherindex++] = dstr[k]; } else tstr[otherindex++] = dstr[k]; fprintf(fsql, "\"%s\"", tstr); } } //we need to end an insert block if (((j + 1) % <API key>) == 0) fprintf(fsql, ");\n"); else fprintf(fsql, ")\n"); } fprintf(fsql, ";"); fprintf(fsql, "\n\n"); fclose(fsql); main2(); } //make this after the main void dump_as_sql2(); void main2() { dbc.open("TaxiPath.dbc"); if (!dbc.getFieldCount()) { printf("error, could not open dbc file\n"); exit(1); } else printf("Opened DBC with %u fields and %u rows\n", (int)dbc.getFieldCount(), (int)dbc.getRecordCount()); dump_as_sql2(); // getch(); } void dump_as_sql2() { if (COLUMN_COUNT2 != dbc.getFieldCount()) { printf("error,column counts do not match update code for latest dbc format\n"); exit(1); } printf("will start dumping data into sql file (we will drop not required fields!)\n"); FILE *fsql = fopen("dbc_taxi_path.sql", "w"); //drop table if already exist fprintf(fsql, "%s", "DROP TABLE IF EXISTS `dbc_taxi_path`;\n"); //create the table fprintf(fsql, "%s", "CREATE TABLE dbc_taxi_path (\n"); for (int i = 0; i < COLUMN_COUNT2; i++) if (<API key>[i][2][0] == '0') { if (<API key>[i][0][0] == 'u') fprintf(fsql, "\t `%s` INT (11) UNSIGNED DEFAULT '0' NOT NULL,\n", <API key>[i][1]); else if (<API key>[i][0][0] == 'i') fprintf(fsql, "\t `%s` INT (11) DEFAULT '0' NOT NULL,\n", <API key>[i][1]); else if (<API key>[i][0][0] == 'f') fprintf(fsql, "\t `%s` FLOAT DEFAULT '0' NOT NULL,\n", <API key>[i][1]); else if (<API key>[i][0][0] == 's') fprintf(fsql, "\t `%s` VARCHAR(2000),\n", <API key>[i][1]); } fprintf(fsql, "%s", "PRIMARY KEY(Id), UNIQUE(id), INDEX(id));\n"); fprintf(fsql, "\n\n"); //start dumping the data from the DBC char tstr[2000]; for (unsigned int j = 0; j < dbc.getRecordCount(); j++) { //we start a new insert block if ((j % <API key>) == 0) { fprintf(fsql, "%s", "INSERT INTO dbc_taxi_path ("); for (int i = 0; i < COLUMN_COUNT2 - 1; i++) if (<API key>[i][2][0] == '0') fprintf(fsql, "`%s`,", <API key>[i][1]); fprintf(fsql, "`%s`) values \n", <API key>[COLUMN_COUNT2 - 1][1]); fprintf(fsql, " ("); } else fprintf(fsql, ",("); for (int i = 0; i < COLUMN_COUNT2; i++) if (<API key>[i][2][0] == '0') { if (i != 0) fprintf(fsql, ","); if (<API key>[i][0][0] == 'u') fprintf(fsql, "%u", dbc.getRecord(j).getUInt(i)); else if (<API key>[i][0][0] == 'i') fprintf(fsql, "%d", dbc.getRecord(j).getInt(i)); else if (<API key>[i][0][0] == 'f') fprintf(fsql, "%f", dbc.getRecord(j).getFloat(i)); else if (<API key>[i][0][0] == 's') { const char *dstr = dbc.getRecord(j).getString(i); int otherindex = 0; for (unsigned int k = 0; k <= strlen(dstr); k++) if (dstr[k] == '\'' || dstr[k] == '"' || dstr[k] == '#' || dstr[k] == '-') { tstr[otherindex++] = '\\'; tstr[otherindex++] = dstr[k]; } else tstr[otherindex++] = dstr[k]; fprintf(fsql, "\"%s\"", tstr); } } //we need to end an insert block if (((j + 1) % <API key>) == 0) fprintf(fsql, ");\n"); else fprintf(fsql, ")\n"); } fprintf(fsql, ";"); fprintf(fsql, "\n\n"); fclose(fsql); }
<?php declare(strict_types=1); namespace SWP\Bundle\ContentBundle\Tests\Loader; use SWP\Bundle\ContentBundle\Loader\ArticleMediaLoader; use SWP\Bundle\ContentBundle\Loader\<API key>; use SWP\Bundle\ContentBundle\Tests\Functional\app\Resources\fixtures\LoadArticlesData; use SWP\Bundle\ContentBundle\Tests\Functional\WebTestCase; use SWP\Component\TemplatesSystem\Gimme\Loader\LoaderInterface; use SWP\Component\TemplatesSystem\Gimme\Meta\Meta; class <API key> extends WebTestCase { /** * @var ArticleMediaLoader */ protected $<API key>; public function setUp(): void { $this->initDatabase(); $this->loadFixtures( [ LoadArticlesData::class, ] ); $this-><API key> = new <API key>( $this->getContainer()->get('swp.repository.article'), $this->getContainer()->get('swp.repository.related_article'), $this->getContainer()->get('<API key>.factory.meta_factory'), $this->getContainer()->get('<API key>') ); } public function testIfIsSupported(): void { $this->assertTrue($this-><API key>->isSupported('relatedArticles')); } public function <API key>(): void { $articleLoader = $this->getContainer()->get('swp_template_engine.loader.article'); $articleMeta = $articleLoader->load('article', ['slug' => 'test-news-article']); $relatedArticles = $this-><API key>->load('relatedArticles', ['article' => $articleMeta], [], LoaderInterface::COLLECTION); self::assertCount(2, $relatedArticles); self::assertInstanceOf(Meta::class, $relatedArticles[0]); self::assertInstanceOf(Meta::class, $relatedArticles[1]); self::assertInstanceOf(Meta::class, $relatedArticles[0]->article); self::assertInstanceOf(Meta::class, $relatedArticles[1]->article); self::assertEquals('Features', $relatedArticles[0]->article->title); self::assertEquals('Test article', $relatedArticles[1]->article->title); } public function <API key>(): void { $articleLoader = $this->getContainer()->get('swp_template_engine.loader.article'); $articleLoader->load('article', ['slug' => 'test-news-article']); $relatedArticles = $this-><API key>->load('relatedArticles', [], [], LoaderInterface::COLLECTION); self::assertCount(2, $relatedArticles); self::assertInstanceOf(Meta::class, $relatedArticles[0]); self::assertInstanceOf(Meta::class, $relatedArticles[1]); self::assertInstanceOf(Meta::class, $relatedArticles[0]->article); self::assertInstanceOf(Meta::class, $relatedArticles[1]->article); self::assertEquals('Features', $relatedArticles[0]->article->title); self::assertEquals('Test article', $relatedArticles[1]->article->title); } }
function Animator2() { var self = this; this.tweens = []; this.tweens['default'] = [1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1]; this.tweens['blast'] = [12,12,11,10,10,9,8,7,6,5,4,3,2,1]; this.tweens['fade'] = [10,10,10,10,10,10,10,10,10,10]; this.queue = []; this.queue.IDs = []; this.active = false; this.timer = null; this.createTween = function(start,end,type) { // return array of tween coordinate data (start->end) type = type||'default'; var tween = [start]; var tmp = start; var diff = end-start; var x = self.tweens[type].length; for (var i=0; i<x; i++) { tmp += diff*self.tweens[type][i]*0.01; tween[i] = new Object(); tween[i].data = tmp; tween[i].event = null; } return tween; } this.enqueue = function(o,fMethod,fOnComplete) { // add object and associated methods to animation queue // writeDebug('animator.enqueue()'); if (!fMethod) { // writeDebug('animator.enqueue(): missing fMethod'); } if (typeof(self.queue.IDs[o.oID])=='undefined') { // writeDebug('animator.enqueue(): added '+o.oID); var i = self.queue.length; self.queue.IDs[o.oID] = i; self.queue[i] = o; } else { // writeDebug('animator.enqueue(): '+o.oID+' already queued'); var i = self.queue.IDs[o.oID]; // retrieve queue index self.queue[i].active = true; self.queue[i].frame = 0; } o.active = true; // flag for animation self.queue[i]._method = fMethod; self.queue[i]._oncomplete = fOnComplete?fOnComplete:null; } this.animate = function() { var active = 0; for (var i=self.queue.length; i if (self.queue[i].active) { self.queue[i]._method(); active++; } } if (active==0 && self.timer) { // all animations finished self.stop(); } else { // writeDebug(active+' active'); } } this.start = function() { if (self.timer || self.active) { // writeDebug('animator.start(): already active'); return false; } // writeDebug('animator.start()'); // report only if started self.active = true; self.timer = setInterval(self.animate,mc.intervalRate); } this.stop = function() { // writeDebug('animator.stop()',true); clearInterval(self.timer); self.timer = null; self.active = false; self.queue = []; self.queue.IDs = []; } } function MainController() { var self = this; this.intervalRate = 20; // rate (ms) to run animation at, general best default = 20 this.DEBUG = true; // debug mode disabled by default this.oFW = null; this.isIE = (navigator.appVersion.indexOf('MSIE')+1); this.isOpera = (navigator.userAgent.toLowerCase().indexOf('opera')+1); if (this.isOpera) this.isIE = false; // no impersonation allowed here! this.animator = null; this.gOID = 0; // global object ID counter (for animation queue) this.particleTypes = 6; this.particleXY = 10; this.tweenFade = [100,90,80,70,60,50,40,30,20,10,0]; this.isSafari = (navigator.appVersion.toLowerCase().indexOf('safari')+1?1:0); this.canvasX = null; this.canvasY = null; this.screenY = null; // screen area (not entire page) self.scrollY = null; self.getWindowCoords = function() { self.canvasX = (document.documentElement.clientWidth||document.body.clientWidth||document.body.scrollWidth); self.canvasY = (document.documentElement.clientHeight||document.body.clientHeight||document.body.scrollHeight); self.screenY = self.canvasY; self.scrollY = parseInt(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop); self.canvasY += self.scrollY; } this.getWindowCoordsAlt = function() { self.canvasX = window.innerWidth; self.canvasY = window.innerHeight; self.screenY = self.canvasY; self.scrollY = parseInt(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop); self.canvasY += self.scrollY; } this.getPanX = function(x) { x = parseInt(x); var pos = x/self.canvasX; if (pos<0.4) { pos *= -1; } else if (pos >= 0.4 && pos <= 0.6) { pos = 0.5; } pos = parseInt(pos*100); // writeDebug('getPanX('+x+'): '+pos+'%'); return pos; } this.isEmpty = function(o) { // needs further hacking return (typeof(o)=='undefined'||(o==null&&o!=0)||(o==''&&o!=0)||o=='null'); } this.init = function() { // self.oFW = document.getElementById('fw'); // self.oFP = document.getElementById('fp'); // if (typeof(enableDebugMode)!='undefined' && (self.DEBUG||window.location.toString().toLowerCase().indexOf('debug')>=0)) enableDebugMode(); self.getWindowCoords(); self.animator = new Animator2(); } this.destructor = function() { /* for (var i=self.fireworks.length; i--;) { self.fireworks[i] = null; } self.fireworks = null; if (soundManager) { soundManager.destructor(); soundManager = null; } */ } if (this.isSafari || this.isOpera) this.getWindowCoords = this.getWindowCoordsAlt; } function Controller(o) { var self = this; this.o = o; this.controls = []; this.cb = []; this.options = []; this.functionExample = document.getElementById('function-example'); this.fbIE = null; this.randomize = function() { for (var i=1; i<self.controls.length; i++) { setTimeout(self.controls[i].randomize,20+(20*i+1)); } } this.cbClick = function(nIndex) { document.getElementById('controls').<API key>('dl')[nIndex].className = 'col'+(this.checked==false||this.checked==''?' disabled':''); self.updateExample(); self.updateExampleCode(); } this.updateExample = function() { if (threeSixtyPlayer) { var val = self.controls[0].value; threeSixtyPlayer.config.circleDiameter = self.controls[0].value; threeSixtyPlayer.config.circleRadius = self.controls[0].value/2; // update some stuff // set the cover width/height to match the canvas if (threeSixtyPlayer.lastSound) { // always set cover to max area? // threeSixtyPlayer.lastSound._data.oCover.style.width = 250+'px'; // threeSixtyPlayer.lastSound._data.oCover.style.height = 250+'px'; // threeSixtyPlayer.lastSound._data.oCover.style.width = threeSixtyPlayer.config.circleDiameter+'px'; // threeSixtyPlayer.lastSound._data.oCover.style.height = threeSixtyPlayer.config.circleDiameter+'px'; threeSixtyPlayer.refreshCoords(threeSixtyPlayer.lastSound); } threeSixtyPlayer.config.<API key> = (self.controls[1].value/100)*2; threeSixtyPlayer.config.<API key> = (self.controls[2].value); threeSixtyPlayer.config.eqDataLineRatio = parseInt((self.controls[3].value/100)*3*1000)/1000; threeSixtyPlayer.config.eqDataDownsample = (self.controls[4].value); threeSixtyPlayer.config.useEQData = (document.getElementById('disabled-1').checked?true:false); // radio buttons threeSixtyPlayer.config.useWaveformData=(document.getElementById('use-waveform').checked?true:false); threeSixtyPlayer.config.waveformDataOutside = document.getElementById('waveform-inside').checked?false:true; threeSixtyPlayer.config.eqDataOutside = document.getElementById('eq-inside').checked?false:true; threeSixtyPlayer.config.useAmplifier = (document.getElementById('use-amplifier').checked?true:false); // threeSixtyPlayer.refreshCoords(); } } this.updateExampleCode = function() { // set innerHTML document.getElementById('config-code').innerHTML = "\ // 360player.js, config section\n\ this.config = {\n\ playNext: <span>false</span>,\n\ autoPlay: <span>false</span>,\n\ loadRingColor: <span>'"+threeSixtyPlayer.config.loadRingColor+"'</span>,\n\ playRingColor: <span>'"+threeSixtyPlayer.config.playRingColor+"'</span>,\n\ backgroundRingColor: <span>'"+threeSixtyPlayer.config.backgroundRingColor+"'</span>,\n\ circleDiameter: <span>"+threeSixtyPlayer.config.circleDiameter+"</span>,\n\ circleRadius: <span>"+threeSixtyPlayer.config.circleRadius+"</span>,\n\ imageRoot: <span>'"+threeSixtyPlayer.config.imageRoot+"'</span>,\n\ animDuration: <span>"+threeSixtyPlayer.config.animDuration+"</span>,\n\ animTransition: <span>Animator.tx.bouncy</span>,\n\ showHMSTime: <span>"+threeSixtyPlayer.config.showHMSTime+"</span>,\n\ \n\ useWaveformData: <span>"+threeSixtyPlayer.config.useWaveformData+"</span>,\n\ waveformDataColor: <span>'"+threeSixtyPlayer.config.waveformDataColor+"'</span>,\n\ <API key>: <span>"+threeSixtyPlayer.config.<API key>+"</span>,\n\ waveformDataOutside: <span>"+threeSixtyPlayer.config.waveformDataOutside+"</span>,\n\ <API key>: <span>false</span>,\n\ <API key>: <span>"+threeSixtyPlayer.config.<API key>+"</span>,\n\ \n\ useEQData: <span>"+threeSixtyPlayer.config.useEQData+"</span>,\n\ eqDataColor: <span>'"+threeSixtyPlayer.config.eqDataColor+"'</span>,\n\ eqDataDownsample: <span>"+threeSixtyPlayer.config.eqDataDownsample+"</span>,\n\ eqDataOutside: <span>"+threeSixtyPlayer.config.eqDataOutside+"</span>,\n\ eqDataLineRatio: <span>"+threeSixtyPlayer.config.eqDataLineRatio+"</span>,\n\ \n\ usePeakData: <span>"+threeSixtyPlayer.config.usePeakData+"</span>,\n\ peakDataColor: <span>'"+threeSixtyPlayer.config.peakDataColor+"'</span>,\n\ peakDataOutside: <span>"+threeSixtyPlayer.config.peakDataOutside+"</span>,\n\ peakDataLineRatio: <span>"+threeSixtyPlayer.config.peakDataLineRatio+"</span>,\n\ \n\ useAmplifier: <span>"+threeSixtyPlayer.config.useAmplifier+"</span>\n\ \n\ }"; document.getElementById('config-code').style.display = 'block'; // weird Fx fix } this.<API key> = function() { } this.destructor = function() { for (var i=self.controls.length; i self.controls[i].destructor(); } for (i=self.cb.length; i self.cb.onclick = null; self.cb[i] = null; } for (i=self.options.length; i self.options[i] = null; } if (navigator.userAgent.match(/msie/i)) { self.fbIE.onmouseover = null; self.fbIE.onmouseout = null; self.fbIE = null; } self.cb = null; self.options = null; self.controls = null; self.functionExample = null; self.o = null; } var items = parseInt(this.o.length/3); for (var i=0; i<items; i++) { this.controls[this.controls.length] = new Slider(this.o[(3*i)+2].<API key>('div')[1],this.o[(3*i)+1],this.o[(3*i)+2].<API key>('div')[0]); } this.cb = [document.getElementById('disabled-0'),document.getElementById('disabled-1')]; /* for (i=this.cb.length; i--;) { this.cb[i]._index = i; this.cb[i].onclick = this.cbClick; } */ this.options = []; /* this.cb[1].checked = false; this.options = [document.getElementById('opt-random0'),document.getElementById('opt-random1')]; this.options[0].checked = false; this.options[1].checked = true; if (navigator.userAgent.match(/msie/i)) { this.fbIE = document.getElementById('fireButton'); this.fbIE.onmouseover = function() {this.className='hover';} this.fbIE.onmouseout = function() {this.className='';} } */ setTimeout(function(){ var values = [ 256, 65, 40, 72, 48 ]; for (var i=0; i<values.length; i++) { self.controls[i].setValue(values[i]); // defaults } },1); } function Slider(o,oV,oB) { var self = this; this.o = o; this.oV = oV; this.oB = oB; this.scale = parseInt(oV.innerHTML.toString().substr(2)); this.oID = 'sc'+(gOID++); this.offX = 0; this.x = 0; this.xMin = 0-10; this.xMax = self.o.parentNode.offsetWidth-10; this.value = 0; this.timer = null; this._className = this.o.className; this.tween = []; this.frame = 0; this.over = function() { this.className = self._className+' hover'; event.cancelBubble=true; return false; } this.out = function() { this.className = self._className; event.cancelBubble=true; return false; } this.down = function(e) { var e = e?e:event; self.offX = e.clientX-self.o.offsetLeft; addEvent(document,'mousemove',self.move); addEvent(document,'mouseup',self.up); return false; } this.barClick = function(e) { var e=e?e:event; self.slide(self.x,e.clientX-self.o.parentNode.parentNode.offsetLeft-self.o.offsetWidth); } this.move = function(e) { var e=e?e:event; var x = e.clientX-self.offX; if (x>self.xMax) { x = self.xMax; } else if (x<self.xMin) { x = self.xMin; } if (x != self.x) { self.moveTo(x); self.doUpdate(); controller.updateExample(); controller.updateExampleCode(); } e.stopPropgation?e.stopPropagation():e.cancelBubble=true; return false; } this.up = function(e) { removeEvent(document,'mousemove',self.move); removeEvent(document,'mouseup',self.up); // controller.updateExample(); controller.updateExampleCode(); } this.slide = function(x0,x1) { self.tween = mc.animator.createTween(x0,x1); mc.animator.enqueue(self,self.animate,function(){ controller.updateExample() controller.updateExampleCode(); }); mc.animator.start(); } this.moveTo = function(x) { self.x = x; self.o.style.marginLeft = x+'px'; } this.animate = function() { self.moveTo(self.tween[self.frame].data); self.doUpdate(50); controller.updateExample(); if (self.frame++>=self.tween.length-1) { self.active = false; self.frame = 0; if (self._oncomplete) self._oncomplete(); // self.doUpdate(); return false; } self.doUpdate(); return true; } this.doUpdate = function(t) { // if (!self.timer) self.timer = setTimeout(self.update,t||20); self.update(); } this.update = function() { self.timer = null; self.value = 1+parseInt(self.x/self.xMax*(self.scale-1)); if (self.value<1) self.value = 1; // if (self.oV.innerHTML != self.value) self.oV.innerHTML = self.value; // self.oV.innerHTML = self.value; } this.setValue = function(x) { self.slide(self.x,Math.min(self.xMax,x)); } this.randomize = function() { self.slide(self.x,parseInt(Math.random()*self.xMax)); } this.destructor = function() { self.o.onmouseover = null; self.o.onmouseout = null; self.o.onmousedown = null; self.o = null; self.oV = null; self.oB.onclick = null; self.oB = null; } if (soundManager.isIE) { // IE is lame, no :hover this.o.onmouseover = this.over; this.o.onmouseout = this.out; } this.o.onmousedown = this.down; this.oB.onclick = this.barClick; self.update(); } var gOID = 0; function demoInit() { controller = new Controller(document.getElementById('controls').<API key>('dd')); } function demoDestuctor() { controller.destructor(); controller = null; } var controller = null; var mc = new MainController(); // create null objects if APIs not present function createCP(oInput,oHandler) { var Event = YAHOO.util.Event; cpHandler = oHandler; if (picker != null) { // picker.showcontrols(true); var c = oInput.value.substr(1); picker.setValue(hex2decArray([c.substr(0,2),c.substr(2,2),c.substr(4,2)]),true); // be silent return false; } Event.onDOMReady(function() { picker = new YAHOO.widget.ColorPicker("cp-container", { showhsvcontrols: true, showhexcontrols: true, images: { PICKER_THUMB: "../_image/picker_thumb.png", HUE_THUMB: "../_image/hue_thumb.png" } }); // picker.showcontrols(false); //a listener for logging RGB color changes; //this will only be visible if logger is enabled: var onRgbChange = function(o) { /*o is an object { newValue: (array of R, G, B values), prevValue: (array of R, G, B values), type: "rgbChange" } */ cpHandler(o.newValue); controller.updateExampleCode(); } //subscribe to the rgbChange event; picker.on("rgbChange", onRgbChange); //use setValue to reset the value to white: Event.on("reset", "click", function(e) { picker.setValue([255, 255, 255], false); //false here means that rgbChange //wil fire; true would silence it }); //use the "get" method to get the current value //of one of the Color Picker's properties; in //this case, we'll get the hex value and write it //to the log: Event.on("gethex", "click", function(e) { console.log("Current hex value: " + picker.get("hex")); }); }); } var picker = null; cpHandler = function() { } // hex -> dec / dec -> hex function dec2hex(cval) { if (cval > 255) cval = 255; var hexascii = "0123456789ABCDEF"; var cval0 = Math.floor(cval/16); var cval1 = cval-(cval0*16); var c1 = hexascii.charAt(cval0); var c2 = hexascii.charAt(cval1); return (c1+c2); } function hex2dec(cval) { cval = cval.toUpperCase(); var tval = 0; var hexascii = "0123456789ABCDEF"; var mychar, ch; for (var c=0; c<cval.length; c++) { mychar = cval.charAt(c); for (ch=0; ch<16; ch++) { if (mychar == hexascii.charAt(ch)) { tval += ch; if (c<cval.length-1) tval *= 16; } } } return tval; } function hex2decArray(hArray) { var result = []; for (var i=0,j=hArray.length; i<j; i++) { result[i] = hex2dec(hArray[i]); } return result; } function dec2hexArray(dArray) { var result = []; for (var i=0,j=dArray.length; i<j; i++) { result[i] = dec2hex(dArray[i]); } return result; } /* threeSixtyPlayer.config.waveformDataColor = '#'+dec2hexArray([self.controls[5].value,self.controls[6].value,self.controls[7].value]).join(''); threeSixtyPlayer.config.eqDataColor = '#'+dec2hexArray([self.controls[8].value,self.controls[9].value,self.controls[10].value]).join(''); threeSixtyPlayer.config.loadRingColor = '#'+dec2hexArray([self.controls[11].value,self.controls[12].value,self.controls[13].value]).join(''); threeSixtyPlayer.config.playRingColor = '#'+dec2hexArray([self.controls[14].value,self.controls[15].value,self.controls[16].value]).join(''); threeSixtyPlayer.config.<API key> = (self.controls[1].value/100)*2; threeSixtyPlayer.config.<API key> = (self.controls[2].value); threeSixtyPlayer.config.eqDataLineRatio = (self.controls[3].value/100)*3; threeSixtyPlayer.config.eqDataDownsample = (self.controls[4].value); */ function $(sID) { return document.getElementById(sID); } function setWaveformColor(sColor) { var value = '#'+(dec2hexArray(sColor).join('')); threeSixtyPlayer.config.waveformDataColor = value; $('waveform-color').value = value; } function setEQColor(sColor) { var value = '#'+dec2hexArray(sColor).join(''); $('eq-color').value = value; threeSixtyPlayer.config.eqDataColor = value; } function setLoadedRingColor(sColor) { var value = '#'+dec2hexArray(sColor).join(''); $('loaded-ring-color').value = value; threeSixtyPlayer.config.loadRingColor = value; } function <API key>(sColor) { var value = '#'+dec2hexArray(sColor).join(''); $('progress-ring-color').value = value; threeSixtyPlayer.config.playRingColor = value; } function <API key>(sColor) { var value = '#'+dec2hexArray(sColor).join(''); $('bg-ring-color').value = value; threeSixtyPlayer.config.backgroundRingColor = value; } function addEvent(o,evtName,evtHandler) { typeof(attachEvent)=='undefined'?o.addEventListener(evtName,evtHandler,false):o.attachEvent('on'+evtName,evtHandler); } function removeEvent(o,evtName,evtHandler) { typeof(attachEvent)=='undefined'?o.removeEventListener(evtName,evtHandler,false):o.detachEvent('on'+evtName,evtHandler); } if (window.location.toString().match(/#customize/i)) { addEvent(window,'resize',mc.getWindowCoords); addEvent(window,'scroll',mc.getWindowCoords); addEvent(window,'load',mc.init); addEvent(window,'load',demoInit); }
<?php return [ 'select_company' => 'Компани сонгох', 'about_companies' => 'About Companies', '<API key>' => ' You can use companies as a simple informative field, or you can use them to restrict asset visibility and availability to users with a specific company by enabling Full Company Support in your Admin Settings.', ];
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import <API key> from 'parser/core/<API key>'; import SPELLS from 'common/SPELLS'; import { formatPercentage, formatThousands } from 'common/format'; import SpellLink from 'common/SpellLink'; import <API key> from 'interface/others/<API key>'; import Events from 'parser/core/Events'; /** * Smash the ground and shatter the armor of all enemies within 8 yds, * dealing [ 150% of Attack Power ] Physical damage and increasing damage * you deal to them by 30% for 10 sec. */ const <API key> = 0.3; class Warbreaker extends Analyzer { static dependencies = { enemies: Enemies, }; totalDamages = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.WARBREAKER_TALENT.id); this.addEventListener(Events.damage.by(SELECTED_PLAYER), this._onDamage); } _onDamage(event) { if (event.targetIsFriendly) { return; } if (event.ability.guid === SPELLS.WARBREAKER_TALENT.id) { this.totalDamages += (event.amount || 0) + (event.absorbed || 0); } const target = this.enemies.getEntity(event); if (target !== null && target.hasBuff(SPELLS.<API key>.id, event.timestamp)) { this.totalDamages += <API key>(event, <API key>); } } get dps() { return this.totalDamages / this.owner.fightDuration * 1000; } subStatistic() { return ( <<API key> title={<><SpellLink id={SPELLS.WARBREAKER_TALENT.id} /> bonus damage</>} value={`${formatThousands(this.dps)} DPS`} valueTooltip={( <> Your Warbreaker contributed {formatThousands(this.totalDamages)} total damage ({formatPercentage(this.owner.<API key>(this.totalDamages))} %).<br /> This accounts for the damage dealt by Warbreaker and the 30% increased damage from Colossus Smash debuff. </> )} /> ); } } export default Warbreaker;
#ifndef <API key> #define <API key> #include "server/zone/objects/scene/SceneObject.h" #include "CombatQueueCommand.h" class <API key> : public CombatQueueCommand { public: <API key>(const String& name, ZoneProcessServer* server) : CombatQueueCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const { if (!checkStateMask(creature)) return INVALIDSTATE; if (!<API key>(creature)) return INVALIDLOCOMOTION; if (!creature->isAiAgent()) return GENERALERROR; return doCombatAction(creature, target, arguments); } }; #endif //<API key>
package com.rapidminer.operator.ports.quickfix; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.tools.I18N; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JOptionPane; /** * @author Simon Fischer */ public abstract class AbstractQuickFix implements QuickFix { private Action action; private int rating; private boolean isInteractive; /** * @param i18nKey * is a key referencing an entry in a properties file that defines the action's text * and icon. * @param i18nArgs * arguments to pass to the text formatter */ public AbstractQuickFix(int rating, boolean isInteractive, String i18nKey, Object... i18nArgs) { this.isInteractive = isInteractive; this.rating = rating; seti18nKey(i18nKey, i18nArgs); } protected void seti18nKey(String i18nKey, Object... i18nArgs) { this.action = new AbstractAction(I18N.getMessage(I18N.getErrorBundle(), "metadata.quickfix." + i18nKey, i18nArgs)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent arg0) { try { apply(); } catch (Exception e) { // TODO: Handle exception by GUI properly JOptionPane.showMessageDialog(null, e.toString(), "Cannot apply quick fix", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } }; String iconName = I18N.getMessageOrNull(I18N.getGUIBundle(), "gui.action.quickfix." + i18nKey + ".icon"); if (iconName != null) { this.action.putValue(Action.SMALL_ICON, SwingTools.createIcon("16/" + iconName)); } } @Override public Action getAction() { return action; } @Override public int getRating() { return rating; } @Override public boolean isInteractive() { return isInteractive; } @Override public int compareTo(QuickFix arg0) { return arg0.getRating() - this.rating; } @Override public String toString() { return (String) action.getValue(Action.NAME); } }
<?php namespace OCP\Migration; use OCP\IDBConnection; /** * @since 10.0 */ interface ISqlMigration { /** * Generate an array of sql statements * * @param IDBConnection $connection * @return array of sql statements * * @since 10.0 */ public function sql(IDBConnection $connection); }
{% extends 'base.html' %} {% block wrapper_classes %} {% endblock %} {% block content %} {% block account_content %} {% endblock %} {% endblock %}
#ifndef STL_UTILS_HPP_ #define STL_UTILS_HPP_ #include <map> #include <set> #include <utility> #include <vector> #include "containers/printf_buffer.hpp" /* stl utils make some stl structures nicer to work with */ template <class K, class V> std::set<K> keys(const std::map<K, V> &); template <class container_t> bool std_contains(const container_t &, const typename container_t::key_type &); template <class K, class V> void debug_print(<API key> *buf, const std::map<K, V> &map); template <class T> void debug_print(<API key> *buf, const std::set<T> &map); template <class T> void debug_print(<API key> *buf, const std::vector<T> &vec); template <class T, class U> void debug_print(<API key> *buf, const std::pair<T, U> &p); template<class A, class B> std::map<B, A> <API key>(const std::map<A, B> &bijection); #include "stl_utils.tcc" #endif /* STL_UTILS_HPP_ */
""" Integration Tests for LMS <API key> background tasks. Runs tasks on answers to course problems to validate that code paths actually work. """ import json import logging from mock import patch from nose.plugins.attrib import attr import textwrap from celery.states import SUCCESS, FAILURE from django.contrib.auth.models import User from django.core.urlresolvers import reverse from openedx.core.djangoapps.util.testing import <API key> from capa.tests.<API key> import (<API key>, <API key>) from xmodule.modulestore.tests.factories import ItemFactory from xmodule.modulestore import ModuleStoreEnum from courseware.model_data import StudentModule from instructor_task.api import (<API key>, <API key>, <API key>, <API key>) from instructor_task.models import InstructorTask from instructor_task.tasks_helper import upload_grades_csv from instructor_task.tests.test_base import ( <API key>, TestReportMixin, OPTION_1, OPTION_2, ) from capa.responsetypes import StudentInputError from lms.djangoapps.lms_xblock.runtime import quote_slashes log = logging.getLogger(__name__) class TestIntegrationTask(<API key>): """ Base class to provide general methods used for "integration" testing of particular tasks. """ def <API key>(self, entry_id, task_type, problem_url_name, expected_message): """Confirm that expected values are stored in InstructorTask on task failure.""" instructor_task = InstructorTask.objects.get(id=entry_id) self.assertEqual(instructor_task.task_state, FAILURE) self.assertEqual(instructor_task.requester.username, 'instructor') self.assertEqual(instructor_task.task_type, task_type) task_input = json.loads(instructor_task.task_input) self.assertNotIn('student', task_input) self.assertEqual(task_input['problem_url'], <API key>.problem_location(problem_url_name).<API key>()) status = json.loads(instructor_task.task_output) self.assertEqual(status['exception'], 'ZeroDivisionError') self.assertEqual(status['message'], expected_message) # check status returned: status = <API key>.get_task_status(instructor_task.task_id) self.assertEqual(status['message'], expected_message) @attr(shard=3) class TestRescoringTask(TestIntegrationTask): """ Integration-style tests for rescoring problems in a background task. Exercises real problems with a minimum of patching. """ def setUp(self): super(TestRescoringTask, self).setUp() self.initialize_course() self.create_instructor('instructor') self.create_student('u1') self.create_student('u2') self.create_student('u3') self.create_student('u4') self.logout() # set up test user for performing test operations self.setup_user() def render_problem(self, username, problem_url_name): """ Use ajax interface to request html for a problem. """ # make sure that the requested user is logged in, so that the ajax call works # on the right problem: self.login_username(username) # make ajax call: modx_url = reverse('xblock_handler', kwargs={ 'course_id': self.course.id.<API key>(), 'usage_id': quote_slashes(<API key>.problem_location(problem_url_name).<API key>()), 'handler': 'xmodule_handler', 'suffix': 'problem_get', }) resp = self.client.post(modx_url, {}) return resp def check_state(self, username, descriptor, expected_score, expected_max_score, expected_attempts): """ Check that the StudentModule state contains the expected values. The student module is found for the test course, given the `username` and problem `descriptor`. Values checked include the number of attempts, the score, and the max score for a problem. """ module = self.get_student_module(username, descriptor) self.assertEqual(module.grade, expected_score) self.assertEqual(module.max_grade, expected_max_score) state = json.loads(module.state) attempts = state['attempts'] self.assertEqual(attempts, expected_attempts) if attempts > 0: self.assertIn('correct_map', state) self.assertIn('student_answers', state) self.assertGreater(len(state['correct_map']), 0) self.assertGreater(len(state['student_answers']), 0) def <API key>(self, instructor, problem_url_name): """Submits the particular problem for rescoring""" return <API key>(self.create_task_request(instructor), <API key>.problem_location(problem_url_name)) def <API key>(self, instructor, problem_url_name, student): """Submits the particular problem for rescoring for a particular student""" return <API key>(self.create_task_request(instructor), <API key>.problem_location(problem_url_name), student) def <API key>(self): """Run rescore scenario on option problem""" # get descriptor: problem_url_name = 'H1P1' self.<API key>(problem_url_name) location = <API key>.problem_location(problem_url_name) descriptor = self.module_store.get_item(location) # first store answers for each of the separate users: self.<API key>('u1', problem_url_name, [OPTION_1, OPTION_1]) self.<API key>('u2', problem_url_name, [OPTION_1, OPTION_2]) self.<API key>('u3', problem_url_name, [OPTION_2, OPTION_1]) self.<API key>('u4', problem_url_name, [OPTION_2, OPTION_2]) self.check_state('u1', descriptor, 2, 2, 1) self.check_state('u2', descriptor, 1, 2, 1) self.check_state('u3', descriptor, 1, 2, 1) self.check_state('u4', descriptor, 0, 2, 1) # update the data in the problem definition self.<API key>(problem_url_name) # confirm that simply rendering the problem again does not result in a change # in the grade: self.render_problem('u1', problem_url_name) self.check_state('u1', descriptor, 2, 2, 1) # rescore the problem for only one student -- only that student's grade should change: self.<API key>('instructor', problem_url_name, User.objects.get(username='u1')) self.check_state('u1', descriptor, 0, 2, 1) self.check_state('u2', descriptor, 1, 2, 1) self.check_state('u3', descriptor, 1, 2, 1) self.check_state('u4', descriptor, 0, 2, 1) # rescore the problem for all students self.<API key>('instructor', problem_url_name) self.check_state('u1', descriptor, 0, 2, 1) self.check_state('u2', descriptor, 1, 2, 1) self.check_state('u3', descriptor, 1, 2, 1) self.check_state('u4', descriptor, 2, 2, 1) def <API key>(self): """Simulate a failure in rescoring a problem""" problem_url_name = 'H1P1' self.<API key>(problem_url_name) self.<API key>('u1', problem_url_name, [OPTION_1, OPTION_1]) expected_message = "bad things happened" with patch('capa.capa_problem.LoncapaProblem.<API key>') as mock_rescore: mock_rescore.side_effect = ZeroDivisionError(expected_message) instructor_task = self.<API key>('instructor', problem_url_name) self.<API key>(instructor_task.id, 'rescore_problem', problem_url_name, expected_message) def <API key>(self): """Generate a real failure in rescoring a problem, with an answer including unicode""" # At one point, the student answers that resulted in StudentInputErrors were being # persisted (even though they were not counted as an attempt). That is not possible # now, so it's harder to generate a test for how such input is handled. problem_url_name = 'H1P1' # set up an option problem -- doesn't matter really what problem it is, but we need # it to have an answer. self.<API key>(problem_url_name) self.<API key>('u1', problem_url_name, [OPTION_1, OPTION_1]) # return an input error as if it were a numerical response, with an embedded unicode character: expected_message = u"Could not interpret '2/3\u03a9' as a number" with patch('capa.capa_problem.LoncapaProblem.<API key>') as mock_rescore: mock_rescore.side_effect = StudentInputError(expected_message) instructor_task = self.<API key>('instructor', problem_url_name) # check instructor_task returned instructor_task = InstructorTask.objects.get(id=instructor_task.id) self.assertEqual(instructor_task.task_state, 'SUCCESS') self.assertEqual(instructor_task.requester.username, 'instructor') self.assertEqual(instructor_task.task_type, 'rescore_problem') task_input = json.loads(instructor_task.task_input) self.assertNotIn('student', task_input) self.assertEqual(task_input['problem_url'], <API key>.problem_location(problem_url_name).<API key>()) status = json.loads(instructor_task.task_output) self.assertEqual(status['attempted'], 1) self.assertEqual(status['succeeded'], 0) self.assertEqual(status['total'], 1) def <API key>(self, problem_url_name): """ Define an arbitrary code-response problem. We'll end up mocking its evaluation later. """ factory = <API key>() grader_payload = json.dumps({"grader": "ps04/grade_square.py"}) problem_xml = factory.build_xml(initial_display="def square(x):", answer_display="answer", grader_payload=grader_payload, num_responses=2) ItemFactory.create(parent_location=self.problem_section.location, category="problem", display_name=str(problem_url_name), data=problem_xml) def <API key>(self): """Run rescore scenario on problem with code submission""" problem_url_name = 'H1P2' self.<API key>(problem_url_name) # we fully create the CodeResponse problem, but just pretend that we're queuing it: with patch('capa.xqueue_interface.XQueueInterface.send_to_queue') as mock_send_to_queue: mock_send_to_queue.return_value = (0, "Successfully queued") self.<API key>('u1', problem_url_name, ["answer1", "answer2"]) instructor_task = self.<API key>('instructor', problem_url_name) instructor_task = InstructorTask.objects.get(id=instructor_task.id) self.assertEqual(instructor_task.task_state, FAILURE) status = json.loads(instructor_task.task_output) self.assertEqual(status['exception'], 'NotImplementedError') self.assertEqual(status['message'], "Problem's definition does not support rescoring.") status = <API key>.get_task_status(instructor_task.task_id) self.assertEqual(status['message'], "Problem's definition does not support rescoring.") def <API key>(self, problem_url_name, redefine=False): """ Defines a custom response problem that uses a random value to determine correctness. Generated answer is also returned as the `msg`, so that the value can be used as a correct answer by a test. If the `redefine` flag is set, then change the definition of correctness (from equals to not-equals). """ factory = <API key>() script = textwrap.dedent(""" def check_func(expect, answer_given): expected = str(random.randint(0, 100)) return {'ok': answer_given %s expected, 'msg': expected} """ % ('!=' if redefine else '==')) problem_xml = factory.build_xml(script=script, cfn="check_func", expect="42", num_responses=1) if redefine: descriptor = self.module_store.get_item( <API key>.problem_location(problem_url_name) ) descriptor.data = problem_xml with self.module_store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, descriptor.location.course_key): self.module_store.update_item(descriptor, self.user.id) self.module_store.publish(descriptor.location, self.user.id) else: # Use "per-student" rerandomization so that check-problem can be called more than once. # Using "always" means we cannot check a problem twice, but we want to call once to get the # correct answer, and call a second time with that answer to confirm it's graded as correct. # Per-student rerandomization will at least generate different seeds for different users, so # we get a little more test coverage. ItemFactory.create(parent_location=self.problem_section.location, category="problem", display_name=str(problem_url_name), data=problem_xml, metadata={"rerandomize": "per_student"}) def <API key>(self): """Run rescore scenario on custom problem that uses randomize""" # First define the custom response problem: problem_url_name = 'H1P1' self.<API key>(problem_url_name) location = <API key>.problem_location(problem_url_name) descriptor = self.module_store.get_item(location) # run with more than one user userlist = ['u1', 'u2', 'u3', 'u4'] for username in userlist: # first render the problem, so that a seed will be created for this user self.render_problem(username, problem_url_name) # submit a bogus answer, in order to get the problem to tell us its real answer dummy_answer = "1000" self.<API key>(username, problem_url_name, [dummy_answer, dummy_answer]) # we should have gotten the problem wrong, since we're way out of range: self.check_state(username, descriptor, 0, 1, 1) # dig the correct answer out of the problem's message module = self.get_student_module(username, descriptor) state = json.loads(module.state) correct_map = state['correct_map'] log.info("Correct Map: %s", correct_map) # only one response, so pull it out: answer = correct_map.values()[0]['msg'] self.<API key>(username, problem_url_name, [answer, answer]) # we should now get the problem right, with a second attempt: self.check_state(username, descriptor, 1, 1, 2) # redefine the problem (as stored in Mongo) so that the definition of correct changes self.<API key>(problem_url_name, redefine=True) # confirm that simply rendering the problem again does not result in a change # in the grade (or the attempts): self.render_problem('u1', problem_url_name) self.check_state('u1', descriptor, 1, 1, 2) # rescore the problem for only one student -- only that student's grade should change # (and none of the attempts): self.<API key>('instructor', problem_url_name, User.objects.get(username='u1')) for username in userlist: self.check_state(username, descriptor, 0 if username == 'u1' else 1, 1, 2) # rescore the problem for all students self.<API key>('instructor', problem_url_name) # all grades should change to being wrong (with no change in attempts) for username in userlist: self.check_state(username, descriptor, 0, 1, 2) class <API key>(TestIntegrationTask): """ Integration-style tests for resetting problem attempts in a background task. Exercises real problems with a minimum of patching. """ userlist = ['u1', 'u2', 'u3', 'u4'] def setUp(self): super(<API key>, self).setUp() self.initialize_course() self.create_instructor('instructor') for username in self.userlist: self.create_student(username) self.logout() def get_num_attempts(self, username, descriptor): """returns number of attempts stored for `username` on problem `descriptor` for test course""" module = self.get_student_module(username, descriptor) state = json.loads(module.state) return state['attempts'] def <API key>(self, instructor, location): """Submits the current problem for resetting""" return <API key>(self.create_task_request(instructor), location) def <API key>(self): """Run reset-attempts scenario on option problem""" # get descriptor: problem_url_name = 'H1P1' self.<API key>(problem_url_name) location = <API key>.problem_location(problem_url_name) descriptor = self.module_store.get_item(location) num_attempts = 3 # first store answers for each of the separate users: for _ in range(num_attempts): for username in self.userlist: self.<API key>(username, problem_url_name, [OPTION_1, OPTION_1]) for username in self.userlist: self.assertEquals(self.get_num_attempts(username, descriptor), num_attempts) self.<API key>('instructor', location) for username in self.userlist: self.assertEquals(self.get_num_attempts(username, descriptor), 0) def test_reset_failure(self): """Simulate a failure in resetting attempts on a problem""" problem_url_name = 'H1P1' location = <API key>.problem_location(problem_url_name) self.<API key>(problem_url_name) self.<API key>('u1', problem_url_name, [OPTION_1, OPTION_1]) expected_message = "bad things happened" with patch('courseware.models.StudentModule.save') as mock_save: mock_save.side_effect = ZeroDivisionError(expected_message) instructor_task = self.<API key>('instructor', location) self.<API key>(instructor_task.id, '<API key>', problem_url_name, expected_message) def <API key>(self): """confirm that a non-problem can still be successfully reset""" location = self.problem_section.location instructor_task = self.<API key>('instructor', location) instructor_task = InstructorTask.objects.get(id=instructor_task.id) self.assertEqual(instructor_task.task_state, SUCCESS) class <API key>(TestIntegrationTask): """ Integration-style tests for deleting problem state in a background task. Exercises real problems with a minimum of patching. """ userlist = ['u1', 'u2', 'u3', 'u4'] def setUp(self): super(<API key>, self).setUp() self.initialize_course() self.create_instructor('instructor') for username in self.userlist: self.create_student(username) self.logout() def <API key>(self, instructor, location): """Submits the current problem for deletion""" return <API key>(self.create_task_request(instructor), location) def <API key>(self): """Run delete-state scenario on option problem""" # get descriptor: problem_url_name = 'H1P1' self.<API key>(problem_url_name) location = <API key>.problem_location(problem_url_name) descriptor = self.module_store.get_item(location) # first store answers for each of the separate users: for username in self.userlist: self.<API key>(username, problem_url_name, [OPTION_1, OPTION_1]) # confirm that state exists: for username in self.userlist: self.assertIsNotNone(self.get_student_module(username, descriptor)) # run delete task: self.<API key>('instructor', location) # confirm that no state can be found: for username in self.userlist: with self.assertRaises(StudentModule.DoesNotExist): self.get_student_module(username, descriptor) def test_delete_failure(self): """Simulate a failure in deleting state of a problem""" problem_url_name = 'H1P1' location = <API key>.problem_location(problem_url_name) self.<API key>(problem_url_name) self.<API key>('u1', problem_url_name, [OPTION_1, OPTION_1]) expected_message = "bad things happened" with patch('courseware.models.StudentModule.delete') as mock_delete: mock_delete.side_effect = ZeroDivisionError(expected_message) instructor_task = self.<API key>('instructor', location) self.<API key>(instructor_task.id, '<API key>', problem_url_name, expected_message) def <API key>(self): """confirm that a non-problem can still be successfully deleted""" location = self.problem_section.location instructor_task = self.<API key>('instructor', location) instructor_task = InstructorTask.objects.get(id=instructor_task.id) self.assertEqual(instructor_task.task_state, SUCCESS) class <API key>(TestReportMixin, <API key>, TestIntegrationTask): """ Test grade report in cases where there are problems contained within split tests. """ def <API key>(self, task_result): """ Verify that all students were successfully graded by `upload_grades_csv`. Arguments: task_result (dict): Return value of `upload_grades_csv`. """ self.<API key>({'attempted': 2, 'succeeded': 2, 'failed': 0}, task_result) def <API key>(self, students_grades, <API key>=False): """ Verify that the grades CSV contains the expected grades data. Arguments: students_grades (iterable): An iterable of dictionaries, where each dict maps a student to another dict representing their grades we expect to see in the CSV. For example: [student_a: {'grade': 1.0, 'HW': 1.0}] """ def merge_dicts(*dicts): """ Return the union of dicts Arguments: dicts: tuple of dicts """ return dict([item for d in dicts for item in d.items()]) def <API key>(user): """Return a dict having single key with value equals to students group in partition""" <API key> = 'Experiment Group ({})' return { <API key>.format(self.partition.name): self.partition.scheme.get_group_for_user( self.course.id, user, self.partition, track_function=None ).name } self.verify_rows_in_csv( [ merge_dicts( {'id': str(student.id), 'username': student.username, 'email': student.email}, grades, <API key>(student) ) for student_grades in students_grades for student, grades in student_grades.iteritems() ], <API key>=<API key> ) def <API key>(self): """ Verify that grade export works when each user partition receives (different) problems. Each user's grade on their particular problem should show up in the grade report. """ problem_a_url = 'problem_a_url' problem_b_url = 'problem_b_url' self.<API key>(problem_a_url, parent=self.vertical_a) self.<API key>(problem_b_url, parent=self.vertical_b) # student A will get 100%, student B will get 50% because # OPTION_1 is the correct option, and OPTION_2 is the # incorrect option self.<API key>(self.student_a.username, problem_a_url, [OPTION_1, OPTION_1]) self.<API key>(self.student_b.username, problem_b_url, [OPTION_1, OPTION_2]) with patch('instructor_task.tasks_helper._get_current_task'): result = upload_grades_csv(None, None, self.course.id, None, 'graded') self.<API key>(result) self.<API key>( [ {self.student_a: {'grade': '1.0', 'HW': '1.0'}}, {self.student_b: {'grade': '0.5', 'HW': '0.5'}} ], <API key>=True ) def <API key>(self): """ Verify that grade export works when only the Group A user partition receives a problem. We expect to see a column for the homework where student_a's entry includes their grade, and student b's entry shows a 0. """ problem_a_url = 'problem_a_url' self.<API key>(problem_a_url, parent=self.vertical_a) self.<API key>(self.student_a.username, problem_a_url, [OPTION_1, OPTION_1]) with patch('instructor_task.tasks_helper._get_current_task'): result = upload_grades_csv(None, None, self.course.id, None, 'graded') self.<API key>(result) self.<API key>( [ {self.student_a: {'grade': '1.0', 'HW': '1.0'}}, {self.student_b: {'grade': '0.0', 'HW': '0.0'}} ], <API key>=True )
<?php namespace OCA\Files_External\Service; use OCA\Files_External\Lib\StorageConfig; /** * Read mount config from legacy mount.json */ abstract class <API key> { /** @var BackendService */ protected $backendService; /** * Read legacy config data * * @return array list of mount configs */ abstract protected function readLegacyConfig(); /** * Copy legacy storage options into the given storage config object. * * @param StorageConfig $storageConfig storage config to populate * @param string $mountType mount type * @param string $applicable applicable user or group * @param array $storageOptions legacy storage options * * @return StorageConfig populated storage config */ protected function <API key>( &$storageConfig, $mountType, $applicable, $storageOptions ) { $backend = $this->backendService->getBackend($storageOptions['backend']); if (!$backend) { throw new \<API key>('Invalid backend ' . $storageOptions['backend']); } $storageConfig->setBackend($backend); if (isset($storageOptions['authMechanism']) && $storageOptions['authMechanism'] !== 'builtin::builtin') { $authMechanism = $this->backendService->getAuthMechanism($storageOptions['authMechanism']); } else { $authMechanism = $backend-><API key>($storageOptions); $storageOptions['authMechanism'] = 'null'; // to make error handling easier } if (!$authMechanism) { throw new \<API key>('Invalid authentication mechanism ' . $storageOptions['authMechanism']); } $storageConfig->setAuthMechanism($authMechanism); $storageConfig->setBackendOptions($storageOptions['options']); if (isset($storageOptions['mountOptions'])) { $storageConfig->setMountOptions($storageOptions['mountOptions']); } if (!isset($storageOptions['priority'])) { $storageOptions['priority'] = $backend->getPriority(); } $storageConfig->setPriority($storageOptions['priority']); if ($mountType === \OC_Mount_Config::MOUNT_TYPE_USER) { $applicableUsers = $storageConfig->getApplicableUsers(); if ($applicable !== 'all') { $applicableUsers[] = $applicable; $storageConfig->setApplicableUsers($applicableUsers); } } else if ($mountType === \OC_Mount_Config::MOUNT_TYPE_GROUP) { $applicableGroups = $storageConfig->getApplicableGroups(); $applicableGroups[] = $applicable; $storageConfig->setApplicableGroups($applicableGroups); } return $storageConfig; } /** * Read the external storages config * * @return StorageConfig[] map of storage id to storage config */ public function getAllStorages() { $mountPoints = $this->readLegacyConfig(); /** * Here is the how the horribly messy mount point array looks like * from the mount.json file: * * $storageOptions = $mountPoints[$mountType][$applicable][$mountPath] * * - $mountType is either "user" or "group" * - $applicable is the name of a user or group (or the current user for personal mounts) * - $mountPath is the mount point path (where the storage must be mounted) * - $storageOptions is a map of storage options: * - "priority": storage priority * - "backend": backend identifier * - "class": LEGACY backend class name * - "options": backend-specific options * - "authMechanism": authentication mechanism identifier * - "mountOptions": mount-specific options (ex: disable previews, scanner, etc) */ // group by storage id /** @var StorageConfig[] $storages */ $storages = []; // for storages without id (legacy), group by config hash for // later processing $<API key> = []; foreach ($mountPoints as $mountType => $applicables) { foreach ($applicables as $applicable => $mountPaths) { foreach ($mountPaths as $rootMountPath => $storageOptions) { $currentStorage = null; /** * Flag whether the config that was read already has an id. * If not, it will use a config hash instead and generate * a proper id later * * @var boolean */ $hasId = false; // the root mount point is in the format "/$user/files/the/mount/point" // we remove the "/$user/files" prefix $parts = explode('/', ltrim($rootMountPath, '/'), 3); if (count($parts) < 3) { // something went wrong, skip \OCP\Util::writeLog( 'files_external', 'Could not parse mount point "' . $rootMountPath . '"', \OCP\Util::ERROR ); continue; } $relativeMountPath = rtrim($parts[2], '/'); // note: we cannot do this after the loop because the decrypted config // options might be needed for the config hash $storageOptions['options'] = \OC_Mount_Config::decryptPasswords($storageOptions['options']); if (!isset($storageOptions['backend'])) { $storageOptions['backend'] = $storageOptions['class']; // legacy compat } if (!isset($storageOptions['authMechanism'])) { $storageOptions['authMechanism'] = null; // ensure config hash works } if (isset($storageOptions['id'])) { $configId = (int)$storageOptions['id']; if (isset($storages[$configId])) { $currentStorage = $storages[$configId]; } $hasId = true; } else { // missing id in legacy config, need to generate // but at this point we don't know the max-id, so use // first group it by config hash $storageOptions['mountpoint'] = $rootMountPath; $configId = \OC_Mount_Config::makeConfigHash($storageOptions); if (isset($<API key>[$configId])) { $currentStorage = $<API key>[$configId]; } } if (is_null($currentStorage)) { // create new $currentStorage = new StorageConfig($configId); $currentStorage->setMountPoint($relativeMountPath); } try { $this-><API key>( $currentStorage, $mountType, $applicable, $storageOptions ); if ($hasId) { $storages[$configId] = $currentStorage; } else { $<API key>[$configId] = $currentStorage; } } catch (\<API key> $e) { // don't die if a storage backend doesn't exist \OCP\Util::writeLog( 'files_external', 'Could not load storage: "' . $e->getMessage() . '"', \OCP\Util::ERROR ); } } } } // convert parameter values foreach ($storages as $storage) { $storage->getBackend()-><API key>($storage); $storage->getAuthMechanism()-><API key>($storage); } return $storages; } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using ThorServer; using ThorServer.Game.Users; namespace ThorHousekeeping { public partial class ReferralTool : System.Web.UI.Page { UserInfo mUser; protected void Page_Load(object sender, EventArgs e) { this.Title = "Referral Tool"; int userId = (int)Session["userid"]; mUser = InstanceManager.Game.Users.GetUser(userId); if (!InstanceManager.Game.Roles.HasRight(mUser.iRole, "<API key>")) { Response.Redirect("./Default.aspx"); } } protected void btnAction_Click(object sender, EventArgs e) { ReferralManager refManager = new ReferralManager(); if (InstanceManager.Game.Users.UserExists(txtUsername.Text)) { UserInfo user = InstanceManager.Game.Users.GetUser(txtUsername.Text); if (InstanceManager.Game.Users.UserExists(txtReferred.Text)) { UserInfo referred = InstanceManager.Game.Users.GetUser(txtReferred.Text); if (referred.LastIP != user.LastIP) { if (referred.sEmail != user.sEmail) { if (!refManager.HasBeenReferred(referred.userId)) { user.iCredits += int.Parse(UserSettings.ReferralReward); referred.iCredits += int.Parse(UserSettings.ReferredReward); InstanceManager.Game.Users.UpdateUser(user); InstanceManager.Game.Users.UpdateUser(referred); refManager.AddReferral(user.userId, referred.userId); InstanceManager.Game.Moderation.LogCommand(mUser.userId, user.userId, "referral", "Referrer: " + txtUsername.Text + "; Referred: " + txtReferred.Text, "Housekeeping"); ServerCommunicator servComm = new ServerCommunicator(); servComm.<API key>("updatecredits", mUser.userId, user.userId, "None"); servComm.<API key>("updatecredits", mUser.userId, referred.userId, "None"); lblInfo.Text = "Reward Granted."; } else { lblInfo.Text = "Whoops. User has been referred before!"; } } else { lblInfo.Text = "Whoops. Email Addresses match!"; } } else { lblInfo.Text = "Whoops. IP Addresses match!"; } } else { lblInfo.Text = "Referred user does not exist!"; } } else { lblInfo.Text = "Invalid user!"; } } } }
<?php return array( 'ad' => 'Active Directory', 'ad_domain' => 'Active Directory domain', 'ad_domain_help' => 'This is sometimes the same as your email domain, but not always.', 'is_ad' => 'This is an Active Directory server', 'alert_email' => 'Siūsti įspėjimus', 'alerts_enabled' => 'Perspėjimai įjungti', 'alert_interval' => 'Expiring Alerts Threshold (in days)', 'alert_inv_threshold' => 'Inventory Alert Threshold', 'asset_ids' => 'Įrangos ID', '<API key>' => 'Sukurti automatiškai didėjantį įragos ID nr.', '<API key>' => 'Papilomas priedėlis (pasirinktinai)', '<API key>' => 'Įjungti automatiškai didėjantį įrangos ID pirmajam suteikiant šį nr.', 'backups' => 'Atsarginė kopija', 'barcode_settings' => 'Prekės kodo nustatymai', 'confirm_purge' => 'Confirm Purge', 'confirm_purge_help' => 'Enter the text "DELETE" in the box below to purge your deleted records. This action cannot be undone.', 'custom_css' => 'Užsakytas CSS', 'custom_css_help' => 'Įveskite bet kokį užsakytą CSS peržiūrėjimo norėtumėte naudoti. Neįtraukite &lt;style>&lt;/Stilius&gt; žymės.', 'default_currency' => 'Numatytoji valiuta', 'default_eula_text' => 'Numatytasis EULA', 'default_language' => 'Numatyta kalba', '<API key>' => 'Jūs taip pat galite susieti pritaikytą EULĄ specifinėms įrangos grupėms.', 'display_asset_name' => 'Rodyti įrangos pavadinimą', '<API key>' => 'Rodyti išdavimo datą', 'display_eol' => 'Rodyti įrangos naudojimo pabaigos datas lentelės pavidalu', 'display_qr' => 'Rodyti QR kodus', 'display_alt_barcode' => 'Rodyti 1D barkodus', 'barcode_type' => '2D barkodo tipas', 'alt_barcode_type' => '1D barkodo tipas', 'eula_settings' => 'EULA nustatymai', 'eula_markdown' => 'Šis EULA leidžia <a href="https://help.github.com/articles/<API key>/">Github flavored markdown</a>.', 'general_settings' => 'Bendrieji nustatymai', 'generate_backup' => 'Atsarginė kopija', 'header_color' => 'Atraštės spalva', 'info' => 'Šie nustatymai leidžia jums pasirinkti savus diegimo nustatymus.', 'laravel' => 'Laravel versija', 'ldap_enabled' => 'LDAP įjungtas', 'ldap_integration' => 'LDAP integracija', 'ldap_settings' => 'LDAP nustatymai', 'ldap_server' => 'LDAP serveris', 'ldap_server_help' => 'This should start with ldap:// (for unencrypted or TLS) or ldaps:// (for SSL)', 'ldap_server_cert' => 'LDAP SSL sertifikato patvirtinimas', '<API key>' => 'Leisti nepatvirtintą SSL sertifikatą', '<API key>' => 'Pažymėkite jeigu naudojate savo pasirašytą SSL sertifikatą ir norite naudoti neegzistuojanti SSL sertifikatą.', 'ldap_tls' => 'Use TLS', 'ldap_tls_help' => 'This should be checked only if you are running STARTTLS on your LDAP server. ', 'ldap_uname' => 'LDAP vartotojo vardas', 'ldap_pword' => 'LDAP slaptažodis', 'ldap_basedn' => 'DN', 'ldap_filter' => 'LDAP filtras', 'ldap_pw_sync' => 'LDAP Password Sync', 'ldap_pw_sync_help' => 'Uncheck this box if you do not wish to keep LDAP passwords synced with local passwords. Disabling this means that your users may not be able to login if your LDAP server is unreachable for some reason.', 'ldap_username_field' => 'Vartotojo vardo laukelis', 'ldap_lname_field' => 'Pavardė', 'ldap_fname_field' => 'LDAP vardas', '<API key>' => 'LDAP prisijungimo užklausa', 'ldap_version' => 'LDAP versija', 'ldap_active_flag' => 'LDAP aktyvios vėliavos', 'ldap_emp_num' => 'LDAP darbuotojų skaičius', 'ldap_email' => 'LDAP el.paštas', 'load_remote_text' => 'Nuotoliniai skriptai', '<API key>' => 'Šis Snipe-IT įdiegimas gali įtraukti programinius kodus iš interneto.', 'logo' => 'Logotipas', '<API key>' => 'Apriboti vartotojai (įskaitant administratorius) priskirtus kompanijoms.', '<API key>' => 'Pilnas kelių kompanijų palaikymas', 'optional' => 'pasirinktinai', 'per_page' => 'Rezultatai puslapyje', 'php' => 'PHP versija', 'php_gd_info' => 'Jūs turite įdiegti PHP-GD, kad rodytų QR kodus, tam peržiūrėkite diegimo instrukcijas.', 'php_gd_warning' => 'PHP vaizdo apdorojimas ir GD papildinys neįdiegtas.', 'qr_help' => 'Įjungti QR kodus prieš nustatant tai', 'qr_text' => 'QR kodo tekstas', 'setting' => 'Nustatymai', 'settings' => 'Nustatymai', 'site_name' => 'Interneto puslapio pavadinimas', 'slack_botname' => 'Slack\'o boto vardas', 'slack_channel' => 'Slack\'o kanalas', 'slack_endpoint' => 'Slack\'o galutinis taškas', 'slack_integration' => 'Slack\'o nustatymai', '<API key>' => 'Slack\'o integravimas yra pasirinktinis, tačiau kanalas ir galutinis taškas reikalingas jie jūs norite juos naudoti su Slack programėle. Norėdami konfigūruoti Slack\'o integraciją pirmiausia privalote <a href=":slack_link" target="_new">sukurti įeinantį priedą</a> savo turimoje Slack\'o paskyroje.', 'snipe_version' => 'Snipe-IT versija', 'system' => 'Sistemos informacija', 'update' => 'Atnaujinti nustatymus', 'value' => 'Vertė', 'brand' => 'Prekinis ženklinimas', '<API key>' => 'Apie nustatymus', 'about_settings_text' => 'Šie nustatymai leidžia jums pasirinkti savus diegimo nustatymus.', 'labels_per_page' => 'Etikečių puslapyje', 'label_dimensions' => 'Etiketės išmatavimai (coliais)', 'page_padding' => 'Page margins (inches)', 'purge' => 'Purge Deleted Records', '<API key>' => 'Label bottom gutter', '<API key>' => 'Label side gutter', 'labels_fontsize' => 'Label font size', 'labels_pagewidth' => 'Label sheet width', 'labels_pageheight' => 'Label sheet height', 'label_gutters' => 'Label spacing (inches)', 'page_dimensions' => 'Page dimensions (inches)', 'label_fields' => 'Label visible fields', 'inches' => 'inches', 'width_w' => 'w', 'height_h' => 'h', 'text_pt' => 'pt', 'two_factor' => 'Two Factor Authentication', 'two_factor_secret' => 'Two-Factor Code', '<API key>' => 'Two-Factor Enrollment', '<API key>' => 'Enable Two Factor', 'two_factor_reset' => 'Reset Two-Factor Secret', '<API key>' => 'This will force the user to enroll their device with Google Authenticator again. This can be useful if their currently enrolled device is lost or stolen. ', '<API key>' => 'Two factor device successfully reset', '<API key>' => 'Two factor device reset failed', '<API key>' => 'Enabling two-factor if it is not currently enabled will immediately force you to authenticate with a Google Auth enrolled device. You will have the ability to enroll your device if one is not currently enrolled.', '<API key>' => 'This will turn on two-factor authentication using Google Authenticator.', 'two_factor_optional' => 'Selective (Users can enable or disable if permitted)', 'two_factor_required' => 'Required for all users', 'two_factor_disabled' => 'Disabled', '<API key>' => 'Enter Two-Factor Code', '<API key>' => 'Submit Code', '<API key>' => 'Your administrator does not permit you to edit this setting.', '<API key>' => "Two factor authentication is required, however your device has not been enrolled yet. Open your Google Authenticator app and scan the QR code below to enroll your device. Once you've enrolled your device, enter the code below", '<API key>' => 'Require Signature', '<API key>' => 'Enabling this feature will require users to physically sign off on accepting an asset.', 'left' => 'left', 'right' => 'right', 'top' => 'top', 'bottom' => 'bottom', 'vertical' => 'vertical', 'horizontal' => 'horizontal', 'zerofill_count' => 'Length of asset tags, including zerofill', );
# -*- encoding: utf-8 -*- # OpenERP, Open Source Management Solution # This program is free software: you can redistribute it and/or modify # published by the Free Software Foundation, either version 3 of the # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from openerp import models, fields class <API key>(models.Model): _name = "mgmtsystem.hazard.origin" _description = "Origin of hazard" name = fields.Char('Origin', size=50, required=True, translate=True) description = fields.Text('Description')
<?php return array( 'test_url' => 'http: 'body' => array( '//div[@class="news_details"]' ), 'strip' => array( '//div[@class="news_details"]/div/div[last()]', ), );
<?php /** * @package plugins.wowza * @subpackage api.filters */ class <API key> extends <API key> { public function getTypeListResponse(KalturaFilterPager $pager, <API key> $responseProfile = null, $type = null) { if(!$type) $type = WowzaPlugin::<API key>(<API key>::WOWZA_MEDIA_SERVER); return parent::getTypeListResponse($pager, $responseProfile, $type); } }
package nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.ble; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.<API key>; import android.bluetooth.<API key>; import android.bluetooth.BluetoothGattServer; import android.bluetooth.<API key>; import android.bluetooth.<API key>; import android.bluetooth.BluetoothManager; import android.content.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.UUID; class PebbleGATTServer extends <API key> { private static final Logger LOG = LoggerFactory.getLogger(PebbleGATTServer.class); private static final UUID <API key> = UUID.fromString("<API key>"); private static final UUID <API key> = UUID.fromString("<API key>"); private static final UUID <API key> = UUID.fromString("<API key>"); private static final UUID SERVER_SERVICE = UUID.fromString("<API key>"); private static final UUID <API key> = UUID.fromString("<API key>"); private final BluetoothDevice mBtDevice; private final PebbleLESupport mPebbleLESupport; private Context mContext; private BluetoothGattServer <API key>; private <API key> <API key>; PebbleGATTServer(PebbleLESupport pebbleLESupport, Context context, BluetoothDevice btDevice) { mContext = context; mBtDevice = btDevice; mPebbleLESupport = pebbleLESupport; } boolean initialize() { BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE); <API key> = bluetoothManager.openGattServer(mContext, this); if (<API key> == null) { return false; } <API key> pebbleGATTService = new <API key>(SERVER_SERVICE, <API key>.<API key>); pebbleGATTService.addCharacteristic(new <API key>(<API key>, <API key>.PROPERTY_READ, <API key>.PERMISSION_READ)); <API key> = new <API key>(<API key>, <API key>.<API key> | <API key>.PROPERTY_NOTIFY, <API key>.PERMISSION_WRITE); <API key>.addDescriptor(new <API key>(<API key>, <API key>.PERMISSION_WRITE)); pebbleGATTService.addCharacteristic(<API key>); <API key>.addService(pebbleGATTService); return true; } synchronized void sendDataToPebble(byte[] data) { //LOG.info("send data to pebble " + GB.hexdump(data, 0, -1)); <API key>.setValue(data.clone()); <API key>.<API key>(mBtDevice, <API key>, false); } synchronized private void sendAckToPebble(int serial) { <API key>.setValue(new byte[]{(byte) (((serial << 3) | 1) & 0xff)}); <API key>.<API key>(mBtDevice, <API key>, false); } public void <API key>(BluetoothDevice device, int requestId, int offset, <API key> characteristic) { if (!mPebbleLESupport.isExpectedDevice(device)) { return; } if (!characteristic.getUuid().equals(<API key>)) { LOG.warn("unexpected read request"); return; } LOG.info("will send response to read request from device: " + device.getAddress()); if (!this.<API key>.sendResponse(device, requestId, 0, offset, new byte[]{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})) { LOG.warn("error sending response"); } } public void <API key>(BluetoothDevice device, int requestId, <API key> characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) { if (!mPebbleLESupport.isExpectedDevice(device)) { return; } if (!characteristic.getUuid().equals(<API key>)) { LOG.warn("unexpected write request"); return; } if (!mPebbleLESupport.mIsConnected) { mPebbleLESupport.mIsConnected = true; synchronized (mPebbleLESupport) { mPebbleLESupport.notify(); } } //LOG.info("write request: offset = " + offset + " value = " + GB.hexdump(value, 0, -1)); int header = value[0] & 0xff; int command = header & 7; int serial = header >> 3; if (command == 0x01) { LOG.info("got ACK for serial = " + serial); if (mPebbleLESupport.mPPAck != null) { mPebbleLESupport.mPPAck.countDown(); } else { LOG.warn("mPPAck countdownlatch is not present but it probably should"); } } if (command == 0x02) { // some request? LOG.info("got command 0x02"); if (value.length > 1) { sendDataToPebble(new byte[]{0x03, 0x19, 0x19}); // no we don't know what that means mPebbleLESupport.<API key>(); // FIXME: maybe not here } else { sendDataToPebble(new byte[]{0x03}); // no we don't know what that means } } else if (command == 0) { // normal package LOG.info("got PPoGATT package serial = " + serial + " sending ACK"); sendAckToPebble(serial); mPebbleLESupport.<API key>(value, 1, value.length - 1); } } public void <API key>(BluetoothDevice device, int status, int newState) { if (!mPebbleLESupport.isExpectedDevice(device)) { return; } LOG.info("Connection state change for device: " + device.getAddress() + " status = " + status + " newState = " + newState); if (newState == BluetoothGattServer.STATE_DISCONNECTED) { mPebbleLESupport.close(); } } public void <API key>(BluetoothDevice device, int requestId, <API key> descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) { if (!mPebbleLESupport.isExpectedDevice(device)) { return; } if (!descriptor.getCharacteristic().getUuid().equals(<API key>)) { LOG.warn("unexpected write request"); return; } LOG.info("<API key>() notifications enabled = " + (value[0] == 1)); if (!this.<API key>.sendResponse(device, requestId, 0, offset, value)) { LOG.warn("<API key>() error sending response!"); } } public void onServiceAdded(int status, <API key> service) { LOG.info("onServiceAdded() status = " + status + " service = " + service.getUuid()); if (status == BluetoothGatt.GATT_SUCCESS && service.getUuid().equals(SERVER_SERVICE)) { final <API key> badbadService = new <API key>(<API key>, <API key>.<API key>); badbadService.addCharacteristic(new <API key>(<API key>, <API key>.PROPERTY_READ, <API key>.PERMISSION_READ)); <API key>.addService(badbadService); } } @Override public void onMtuChanged(BluetoothDevice device, int mtu) { if (!mPebbleLESupport.isExpectedDevice(device)) { return; } LOG.info("Pebble requested mtu for server: " + mtu); mPebbleLESupport.setMTU(mtu); } public void onNotificationSent(BluetoothDevice bluetoothDevice, int status) { //LOG.info("onNotificationSent() status = " + status + " to device " + mmBtDevice.getAddress()); } void close() { if (<API key> != null) { <API key>.cancelConnection(mBtDevice); <API key>.clearServices(); <API key>.close(); } } }
package unitassigner import ( "github.com/juju/errors" "github.com/juju/worker/v2" "github.com/juju/worker/v2/dependency" "github.com/juju/juju/api/base" "github.com/juju/juju/api/unitassigner" "github.com/juju/juju/cmd/jujud/agent/engine" ) // Logger represents the methods used by the worker to log details. type Logger interface { Tracef(string, ...interface{}) } // ManifoldConfig describes the resources used by a unitassigner worker. type ManifoldConfig struct { APICallerName string Logger Logger } // Manifold returns a Manifold that runs a unitassigner worker. func Manifold(config ManifoldConfig) dependency.Manifold { return engine.APIManifold( engine.APIManifoldConfig{ APICallerName: config.APICallerName, }, config.start, ) } // start returns a unitassigner worker using the supplied APICaller. func (c *ManifoldConfig) start(apiCaller base.APICaller) (worker.Worker, error) { facade := unitassigner.New(apiCaller) worker, err := New(facade, c.Logger) if err != nil { return nil, errors.Trace(err) } return worker, nil }
#ifndef <API key> #define <API key> #include <QtGlobal> #if QT_VERSION >= 0x050000 #include <QtWidgets> #else #include <QtGui> #endif const int <API key>=8; const int <API key>=1; class AdvancedFilterForm : public QDialog { Q_OBJECT public: int rows; QRadioButton* allRadio; QRadioButton* anyRadio; QCheckBox* <API key>; QHBoxLayout* caseSensitiveLayout; QPushButton* morePushButton; QPushButton* fewerPushButton; QList<QComboBox*> <API key>; QList<QComboBox*> <API key>; QList<QLineEdit*> textLineEditList; QPushButton* resetPushButton; QPushButton* okPushButton; QPushButton* cancelPushButton; QVBoxLayout* allAnyLayout; QGridLayout* filtersLayout; QHBoxLayout* moreFewerLayout; QHBoxLayout* buttonsLayout; QVBoxLayout* layout; QString atts; public: AdvancedFilterForm(QWidget* parent, bool all, QList<int> descrDetDescr, QList<int> contNCont, QStringList text, bool caseSensitive, const QString& textToSettings); ~AdvancedFilterForm(); public slots: void reset(); void more(); void fewer(); }; #endif
DELIMITER $$ DROP PROCEDURE IF EXISTS delService $$ CREATE PROCEDURE delService( IN pID MEDIUMINT, OUT pErr MEDIUMINT ) BEGIN DECLARE no_data CONDITION FOR 1329; DECLARE EXIT HANDLER FOR no_data BEGIN SET pErr = -5; DEALLOCATE PREPARE STMT; ROLLBACK; END; DECLARE EXIT HANDLER FOR sqlexception BEGIN SET pErr = -3; DEALLOCATE PREPARE STMT; ROLLBACK; END; DECLARE EXIT HANDLER FOR sqlwarning BEGIN SET pErr = -4; DEALLOCATE PREPARE STMT; ROLLBACK; END; SET @qry = "DELETE FROM tblService WHERE idService = ?"; START TRANSACTION; SET @p1 = pID; PREPARE STMT FROM @qry; EXECUTE STMT USING @p1; DEALLOCATE PREPARE STMT; SET pErr = 0; COMMIT; END $$ DELIMITER ;
<div class="page-header clearfix"> <ol ng-if="action === 'create'" class="heading"> <li><a ui-sref="main.categories"></a></li> <li><a ui-sref="main.categories.create"></a></li> </ol> <ol ng-if="action === 'update'" class="heading"> <li><a ui-sref="main.categories"></a></li> <li><a ui-sref="main.categories.update({ _id: _id })"></a></li> </ol> </div> <div class="panel panel-default"> <div class="panel-body"> <form ng-submit="saveCategory()" class="form-horizontal" id="categoryForm" name="categoryForm" novalidate> <div ng-class="{ 'has-error': categoryForm.types.$touched && categoryForm.types.$invalid}" class="form-group"> <label for="types" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <div ng-if="action === 'create'" class="btn-group" role="group" aria-label="..."> <button ng-repeat="type in $parent.types" ng-click="$parent.$parent.type = type.type" ng-disabled="transmitting" ng-class="{ 'active': $parent.$parent.type === type.type }" class="btn btn-default" id="types" type="button">{{type.name}}</button> </div> <p ng-if="action === 'update'" class="form-control-static">{{translateType(type)}}</p> </div> </div> <div ng-class="{ 'has-error': categoryForm.name.$touched && categoryForm.name.$invalid }" class="form-group"> <label for="name" class="col-sm-2 control-label">* {{type | translate: { display: 'name', same: 'type', source: types } }}</label> <div class="col-sm-10"> <input ng-model="name" ng-disabled="transmitting" class="form-control" id="name" type="text" name="name" placeholder="{{type | translate: { display: 'name', same: 'type', source: types } }}" required> </div> </div> <div ng-class="{ 'has-error': categoryForm.sort.$touched && categoryForm.sort.$invalid }" class="form-group"> <label for="sort" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input ng-model="sort" ng-disabled="transmitting" class="form-control" id="sort" type="number" name="sort" min="0" required> </div> </div> <div ng-class="{ 'has-error': categoryForm.isShow.$touched && categoryForm.isShow.$invalid }" class="form-group"> <label for="isShow" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <div class="checkbox"> <label> <input ng-model="isShow" ng-disabled="transmitting" id="isShow" type="checkbox"> </label> </div> </div> </div> <hr> <div ng-if="type === 'page' || type === 'link'" ng-class="{ 'has-error': categoryForm.parentCategory.$touched && categoryForm.parentCategory.$invalid}" class="form-group"> <label for="parentCategory" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <select ng-if="action === 'create'" ng-model="$parent.$parent.prePath" ng-options="category.path as category.name for category in $parent.$parent.$parent.categories | filter: { type: '!column' } | filter: { type: '!link'}" ng-disabled="transmitting" class="form-control" id="parentCategory" name="parentCategory"> <option value=""></option> </select> <select ng-if="action === 'update'" ng-model="$parent.$parent.prePath" ng-options="category.path as category.name for category in $parent.$parent.$parent.categories | filter: { type: '!column' } | filter: { type: '!link'} | filter: { _id: '!{{ _id }}' } | filter: { path: '!{{ oldPath }}' }" ng-disabled="transmitting" class="form-control" id="parentCategory" name="parentCategory"> <option value=""></option> </select> </div> </div> <div ng-if="type === 'column'" ng-class="{ 'has-error': categoryForm.model.$touched && categoryForm.model.$invalid}" class="form-group"> <label for="model" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <select ng-model="$parent.model" ng-options="models._id as models.name for models in $parent.models" ng-disabled="$parent.transmitting" class="form-control" id="model" name="model" required> <option value=""></option> </select> </div> </div> <div ng-if="type === 'column'" ng-class="{ 'has-error': categoryForm.parentCategory.$touched && categoryForm.parentCategory.$invalid}" class="form-group"> <label for="parentCategory" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <select ng-model="$parent.prePath" ng-options="category.path as category.name for category in $parent.$parent.categories | filter: { type: 'channel' }" ng-disabled="transmitting" class="form-control" id="parentCategory" name="parentCategory"> <option value=""></option> </select> </div> </div> <!-- categoryForm.directory.$touched--> <div ng-if="type !== 'link' && action === 'create'" ng-class="{ 'has-error': categoryForm.directory.$touched && categoryForm.directory.$invalid }" class="form-group has-feedback"> <label for="directory" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <input ng-model="$parent.directory" ng-pattern="/^[A-z0-9\-\_]+$/" nd-vdirectory pre-path="prePath" old-path="oldPath" ng-trim ng-disabled="transmitting" class="form-control text-lowercase" id="directory" type="text" name="directory" describedby="directoryStatus" placeholder="" required> <span ng-show="checkDirectorying" class="<API key>" aria-hidden="true"><i class="fa fa-refresh fa-spin"></i></span> <span id="directoryStatus" class="sr-only">()</span> <p ng-show="categoryForm.directory.$error.pattern && categoryForm.directory.$touched && categoryForm.directory.$invalid" class="help-block"></p> <p ng-show="!categoryForm.directory.$error.pattern && categoryForm.directory.$error.vdirectory && categoryForm.directory.$touched && categoryForm.directory.$invalid" class="help-block"></p> </div> </div> <!-- categoryForm.directory.$touched--> <div ng-if="type !== 'link' && action === 'update'" ng-class="{ 'has-error': categoryForm.directory.$invalid }" class="form-group has-feedback"> <label for="directory" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <input ng-model="$parent.directory" ng-pattern="/^[A-z0-9\-\_]+$/" nd-vdirectory pre-path="prePath" old-path="oldPath" ng-trim ng-disabled="transmitting" class="form-control text-lowercase" id="directory" type="text" name="directory" describedby="directoryStatus" placeholder="" required> <span ng-show="checkDirectorying" class="<API key>" aria-hidden="true"><i class="fa fa-refresh fa-spin"></i></span> <span id="directoryStatus" class="sr-only">()</span> <p ng-show="categoryForm.directory.$error.pattern && categoryForm.directory.$invalid" class="help-block"></p> <p ng-show="!categoryForm.directory.$error.pattern && categoryForm.directory.$error.vdirectory && categoryForm.directory.$invalid" class="help-block"></p> </div> </div> <div ng-if="type === 'column'" ng-class="{ 'has-error': categoryForm.pageSize.$touched && categoryForm.pageSize.$invalid }" class="form-group"> <label for="pageSize" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <input ng-model="$parent.pageSize" ng-disabled="transmitting" class="form-control" id="pageSize" type="number" min="1" name="pageSize" placeholder="" required> </div> </div> <div ng-if="type === 'link'" ng-class="{ 'has-error': categoryForm.url.$touched && categoryForm.url.$invalid }" class="form-group"> <label for="url" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <input ng-model="$parent.url" ng-disabled="transmitting" class="form-control" id="url" type="url" name="url" placeholder=" URL" required> </div> </div> <div ng-if="type !== 'link'" ng-class="{ 'has-error': categoryForm.layoutView.$touched && categoryForm.layoutView.$invalid}" class="form-group"> <label for="layoutView" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <select ng-model="$parent.views.layout" ng-options="view as view for view in $parent.viewfiles | filter: 'layout-'" ng-disabled="$parent.transmitting" class="form-control" id="layoutView" name="layoutView" required></select> </div> </div> <div ng-if="type === 'channel'" ng-class="{ 'has-error': categoryForm.channelView.$touched && categoryForm.channelView.$invalid}" class="form-group"> <label for="columnView" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <select ng-model="$parent.views.channel" ng-options="view for view in $parent.viewfiles | filter: 'channel-'" ng-disabled="$parent.transmitting" class="form-control" id="channelView" name="channelView" required></select> </div> </div> <div ng-if="type === 'column'" ng-class="{ 'has-error': categoryForm.columnView.$touched && categoryForm.columnView.$invalid}" class="form-group"> <label for="columnView" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <select ng-model="$parent.views.column" ng-options="view for view in $parent.viewfiles | filter: 'column-'" ng-disabled="$parent.transmitting" class="form-control" id="columnView" name="columnView" required></select> </div> </div> <div ng-if="type === 'column'" ng-class="{ 'has-error': categoryForm.contentView.$touched && categoryForm.contentView.$invalid}" class="form-group"> <label for="contentView" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <select ng-model="$parent.views.content" ng-options="view for view in $parent.viewfiles | filter: 'content-'" ng-disabled="$parent.transmitting" class="form-control" id="contentView" name="contentView" required></select> </div> </div> <div ng-if="type === 'page'" ng-class="{ 'has-error': categoryForm.pageView.$touched && categoryForm.pageView.$invalid}" class="form-group"> <label for="pageView" class="col-sm-2 control-label">* </label> <div class="col-sm-10"> <select ng-model="$parent.views.page" ng-options="view for view in $parent.viewfiles | filter: 'page-'" ng-disabled="$parent.transmitting" class="form-control" id="pageView" name="pageView" required></select> </div> </div> <div ng-if="type === 'page'" ng-class="{ 'has-error': categoryForm.isEdit.$touched && categoryForm.isEdit.$invalid }" class="form-group"> <label for="isEdit" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <div class="checkbox"> <label> <input ng-model="$parent.isEdit" ng-disabled="transmitting" id="isEdit" type="checkbox"> </label> </div> </div> </div> <div ng-if="type !== 'link'" class="form-group"> <label for="keywords" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input ng-model="$parent.keywords" ng-disabled="$parent.transmitting" class="form-control" id="keywords" type="text" name="keywords" placeholder="META Keywords"> </div> </div> <div ng-if="type !== 'link'" class="form-group"> <label for="description" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <textarea ng-model="$parent.description" ng-disabled="$parent.transmitting" class="form-control" id="description" name="description" rows="3" placeholder="META Description"></textarea> </div> </div> </form> </div> </div> <button ng-disabled="transmitting || inputing || categoryForm.$invalid" class="btn btn-primary pull-right" form="categoryForm" type="submit"><i class="fa fa-save"></i> </button>
# <API key>: (Apache-2.0 OR MIT) from spack import * class RCli(RPackage): """A suite of tools designed to build attractive command line interfaces ('CLIs'). Includes tools for drawing rules, boxes, trees, and 'Unicode' symbols with 'ASCII' alternatives.""" homepage = "https://github.com/r-lib/cli#readme" url = "https://cloud.r-project.org/src/contrib/cli_1.0.0.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/cli" version('2.0.2', sha256='<SHA256-like>') version('1.1.0', sha256='<SHA256-like>') version('1.0.1', sha256='<SHA256-like>') version('1.0.0', sha256='<SHA256-like>') depends_on('r@2.10:', type=('build', 'run')) depends_on('r-assertthat', type=('build', 'run')) depends_on('r-crayon@1.3.4:', type=('build', 'run')) depends_on('r-glue', when='@2:', type=('build', 'run')) depends_on('r-fansi', when='@2:', type=('build', 'run'))
#ifndef __GDK_X11_UTILS_H__ #define __GDK_X11_UTILS_H__ #if !defined (__GDKX_H_INSIDE__) && !defined (GDK_COMPILATION) #error "Only <gdk/gdkx.h> can be included directly." #endif #include <gdk/gdk.h> #include <X11/Xlib.h> #include <X11/Xutil.h> G_BEGIN_DECLS #ifndef GDK_MULTIHEAD_SAFE Window <API key> (void); Display *<API key> (void); #endif #ifndef GDK_MULTIHEAD_SAFE /** * GDK_ROOT_WINDOW: * * Obtains the Xlib window id of the root window of the current screen. */ #define GDK_ROOT_WINDOW() (<API key> ()) #endif /** * GDK_XID_TO_POINTER: * * Converts an XID into a @gpointer. This is useful with data structures * that use pointer arguments such as #GHashTable. Use GDK_POINTER_TO_XID() * to convert the argument back to an XID. */ #define GDK_XID_TO_POINTER(pointer) GUINT_TO_POINTER(pointer) /** * GDK_POINTER_TO_XID: * * Converts a @gpointer back to an XID that was previously converted * using GDK_XID_TO_POINTER(). */ #define GDK_POINTER_TO_XID(pointer) GPOINTER_TO_UINT(pointer) #ifndef GDK_MULTIHEAD_SAFE void gdk_x11_grab_server (void); void <API key> (void); #endif G_END_DECLS #endif /* __GDK_X11_UTILS_H__ */
# Link Grammar Vala Bindings If you run into an issue, please tag @kmwallio or [create an issue here](https://github.com/kmwallio/link-grammar-vapi) for direct support related to the Vala Bindings. ## Usage Place link-grammar.vapi into your project's Vapi directory and add it to your build. For meson, it would look like: meson # Find link-grammar dependency cc = meson.get_compiler('c') linkgrammar = cc.find_library('link-grammar', required: true) # Other build steps... executable( meson.project_name(), '...source_files...', c_args: c_args, dependencies: [ other dependencies..., linkgrammar ], vala_args: [ other Vala args..., meson.source_root() + '/vapi/link-grammar.vapi' ], install : true/false ) # Example Usage This is based on the [Simple Example for C](https://www.abisource.com/projects/link-grammar/api/index.html#example1). vala public static int main (string[] args) { print ("# Link Grammar Sample\n"); string[] input_strings = { "He eats cake.", "He eat cake.", "The side affects were devastating.", "The side effects were devastating." }; var opts = new ParseOptions (); var dict = new Dictionary ("en"); // Allow for null links. opts.set_max_null_count (10); if (dict == null) { warning ("Could not load dictionary"); return 1; } for (int i = 0; i < input_strings.length; i++) { var sentence = new Sentence (input_strings[i], dict); sentence.split (opts); var num_linkages = sentence.parse (opts); if (num_linkages > 0) { var linkage = new Linkage (0, sentence, opts); var diagram = linkage.print_diagram (true, 800); print ("%s\n", diagram); } } return 0; } ## Sample Output # Link Grammar Sample link-grammar: Info: Dictionary found at /usr/share/link-grammar/en/4.0.dict + + +->Wd | | | | | | LEFT-WALL he eats.v cake.n-u . RIGHT-WALL + + | | | | | LEFT-WALL [he] eat.v cake.n-u . RIGHT-WALL + + + | +Ds**c+--Ss*s-+ | | | | | | | LEFT-WALL the side.n affects.v [were] devastating.g . RIGHT-WALL + + + | + | | + | | | | | | | | LEFT-WALL the side.n effects.n were.v-d devastating.g . RIGHT-WALL
package com.swabunga.spell.engine; import java.util.List; /** * An interface for all dictionary implementations. It defines the most basic * operations on a dictionary: adding words, checking if a word is correct, and getting a list * of suggestions for misspelled words. */ public interface SpellDictionary { /** * Add a word permanently to the dictionary. * @param word The word to add to the dictionary */ public void addWord(String word); /** * Evaluates if the word is correctly spelled against the dictionary. * @param word The word to verify if it's spelling is OK. * @return Indicates if the word is present in the dictionary. */ public boolean isCorrect(String word); /** * Returns a list of Word objects that are the suggestions to any word. * If the word is correctly spelled, then this method * could return just that one word, or it could still return a list * of words with similar spellings. * <br/> * Each suggested word has a score, which is an integer * that represents how different the suggested word is from the sourceWord. * If the words are the exactly the same, then the score is 0. * You can get the dictionary to only return the most similar words by setting * an appropriately low threshold value. * If you set the threshold value too low, you may get no suggestions for a given word. * <p> * This method is only needed to provide backward compatibility. * @see #getSuggestions(String, int, int[][]) * * @param sourceWord the string that we want to get a list of spelling suggestions for * @param scoreThreshold Any words that have score less than this number are returned. * @return List a List of suggested words * @see com.swabunga.spell.engine.Word * */ public List getSuggestions(String sourceWord, int scoreThreshold); /** * Returns a list of Word objects that are the suggestions to any word. * If the word is correctly spelled, then this method * could return just that one word, or it could still return a list * of words with similar spellings. * <br/> * Each suggested word has a score, which is an integer * that represents how different the suggested word is from the sourceWord. * If the words are the exactly the same, then the score is 0. * You can get the dictionary to only return the most similar words by setting * an appropriately low threshold value. * If you set the threshold value too low, you may get no suggestions for a given word. * <p> * @param sourceWord the string that we want to get a list of spelling suggestions for * @param scoreThreshold Any words that have score less than this number are returned. * @param Two dimensional int array used to calculate edit distance. Allocating * this memory outside of the function will greatly improve efficiency. * @return List a List of suggested words * @see com.swabunga.spell.engine.Word */ public List getSuggestions(String sourceWord, int scoreThreshold , int[][] matrix); }
#include "PreCompiled.h" #ifndef _PreComp_ # include <Python.h> #endif #include <Base/Console.h> #include <Base/Interpreter.h> #include <Gui/Application.h> #include <Gui/WidgetFactory.h> #include <Gui/Language/Translator.h> #include "ViewProviderPath.h" #include "<API key>.h" #include "<API key>.h" #include "<API key>.h" // use a different name to CreateCommand() void CreatePathCommands(void); void loadPathResource() { // add resources and reloads the translators Q_INIT_RESOURCE(Path); Gui::Translator::instance()->refresh(); } namespace PathGui { extern PyObject* initModule(); } /* Python entry */ PyMODINIT_FUNC initPathGui() { if (!Gui::Application::Instance) { PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application."); return; } try { Base::Interpreter().runString("import PartGui"); Base::Interpreter().runString("import Path"); } catch(const Base::Exception& e) { PyErr_SetString(PyExc_ImportError, e.what()); return; } (void)PathGui::initModule(); Base::Console().Log("Loading GUI of Path module... done\n"); // instantiating the commands CreatePathCommands(); // addition objects PathGui::ViewProviderPath ::init(); PathGui::<API key> ::init(); PathGui::<API key> ::init(); PathGui::<API key> ::init(); PathGui::<API key> ::init(); // add resources and reloads the translators loadPathResource(); // register preferences pages new Gui::PrefPageProducer<PathGui::<API key>> ("Path"); }
/* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ #include "AuxKernel.h" //local includes #include "FEProblem.h" #include "SubProblem.h" #include "AuxiliarySystem.h" #include "MooseTypes.h" #include "Assembly.h" //libmesh includes #include "libmesh/numeric_vector.h" #include "libmesh/dof_map.h" #include "libmesh/quadrature.h" template<> InputParameters validParams<AuxKernel>() { InputParameters params = validParams<MooseObject>(); params += validParams<BlockRestrictable>(); params += validParams<<API key>>(); params += validParams<RandomInterface>(); params += validParams<<API key>>(); params += validParams<<API key>>(); // Add the SetupInterface parameter, 'execute_on', the default is 'linear' params += validParams<SetupInterface>(); params.addRequiredParam<AuxVariableName>("variable", "The name of the variable that this object applies to"); params.addParam<bool>("use_displaced_mesh", false, "Whether or not this object should use the displaced mesh for computation. Note that in the case this is true but no displacements are provided in the Mesh block the undisplaced mesh will still be used."); params.<API key>("use_displaced_mesh", "Advanced"); // This flag is set to true if the AuxKernel is being used on a boundary params.addPrivateParam<bool>("_on_boundary", false); params.declareControllable("enable"); // allows Control to enable/disable this type of object params.registerBase("AuxKernel"); return params; } AuxKernel::AuxKernel(const InputParameters & parameters) : MooseObject(parameters), BlockRestrictable(parameters), <API key>(parameters, parameters.get<AuxiliarySystem *>("_aux_sys")->getVariable(parameters.get<THREAD_ID>("_tid"), parameters.get<AuxVariableName>("variable")).isNodal()), SetupInterface(this), <API key>(this, parameters.get<AuxiliarySystem *>("_aux_sys")->getVariable(parameters.get<THREAD_ID>("_tid"), parameters.get<AuxVariableName>("variable")).isNodal()), FunctionInterface(this), UserObjectInterface(this), TransientInterface(this), <API key>(this, blockIDs(), boundaryIDs()), <API key>(this), <API key>(), RandomInterface(parameters, *parameters.get<FEProblem *>("_fe_problem"), parameters.get<THREAD_ID>("_tid"), parameters.get<AuxiliarySystem *>("_aux_sys")->getVariable(parameters.get<THREAD_ID>("_tid"), parameters.get<AuxVariableName>("variable")).isNodal()), <API key>(this), Restartable(parameters, "AuxKernels"), ZeroInterface(parameters), <API key>(parameters), <API key>(this), _subproblem(*parameters.get<SubProblem *>("_subproblem")), _sys(*parameters.get<SystemBase *>("_sys")), _nl_sys(*parameters.get<SystemBase *>("_nl_sys")), _aux_sys(*parameters.get<AuxiliarySystem *>("_aux_sys")), _tid(parameters.get<THREAD_ID>("_tid")), _assembly(_subproblem.assembly(_tid)), _var(_aux_sys.getVariable(_tid, parameters.get<AuxVariableName>("variable"))), _nodal(_var.isNodal()), _bnd(boundaryRestricted()), _mesh(_subproblem.mesh()), _q_point(_bnd ? _assembly.qPointsFace() : _assembly.qPoints()), _qrule(_bnd ? _assembly.qRuleFace() : _assembly.qRule()), _JxW(_bnd ? _assembly.JxWFace() : _assembly.JxW()), _coord(_assembly.coordTransformation()), _u(_nodal ? _var.nodalSln() : _var.sln()), _u_old(_nodal ? _var.nodalSlnOld() : _var.slnOld()), _u_older(_nodal ? _var.nodalSlnOlder() : _var.slnOlder()), _test(_var.phi()), _current_elem(_var.currentElem()), _current_side(_var.currentSide()), <API key>(_assembly.elemVolume()), <API key>(_assembly.sideElemVolume()), _current_node(_assembly.node()), _solution(_aux_sys.solution()) { _supplied_vars.insert(parameters.get<AuxVariableName>("variable")); std::map<std::string, std::vector<MooseVariable *> > coupled_vars = getCoupledVars(); for (const auto & it : coupled_vars) for (const auto & var : it.second) _depend_vars.insert(var->name()); } AuxKernel::~AuxKernel() { } const std::set<std::string> & AuxKernel::getRequestedItems() { return _depend_vars; } const std::set<std::string> & AuxKernel::getSuppliedItems() { return _supplied_vars; } const UserObject & AuxKernel::getUserObjectBase(const std::string & name) { _depend_uo.insert(_pars.get<UserObjectName>(name)); return UserObjectInterface::getUserObjectBase(name); } const PostprocessorValue & AuxKernel::<API key>(const std::string & name) { _depend_uo.insert(_pars.get<PostprocessorName>(name)); return <API key>::<API key>(name); } const PostprocessorValue & AuxKernel::<API key>(const PostprocessorName & name) { _depend_uo.insert(name); return <API key>::<API key>(name); } void AuxKernel::coupledCallback(const std::string & var_name, bool is_old) { if (is_old) { std::vector<VariableName> var_names = getParam<std::vector<VariableName> >(var_name); for (const auto & name : var_names) _depend_vars.erase(name); } } void AuxKernel::compute() { precalculateValue(); if (isNodal()) /* nodal variables */ { if (_var.isNodalDefined()) { _qp = 0; Real value = computeValue(); // update variable data, which is referenced by other kernels, so the value is up-to-date _var.setNodalValue(value); } } else /* elemental variables */ { _n_local_dofs = _var.numberOfDofs(); if (_n_local_dofs==1) { Real value = 0; for (_qp=0; _qp<_qrule->n_points(); _qp++) value += _JxW[_qp]*_coord[_qp]*computeValue(); value /= (_bnd ? <API key> : <API key>); // update the variable data refernced by other kernels. // Note that this will update the values at the quadrature points too // (because this is an Elemental variable) _var.setNodalValue(value); } else /* high-order */ { _local_re.resize(_n_local_dofs); _local_re.zero(); _local_ke.resize(_n_local_dofs, _n_local_dofs); _local_ke.zero(); // assemble the local mass matrix and the load for (unsigned int i = 0; i < _test.size(); i++) for (_qp = 0; _qp < _qrule->n_points(); _qp++) { Real t = _JxW[_qp] * _coord[_qp] * _test[i][_qp]; _local_re(i) += t * computeValue(); for (unsigned int j = 0; j < _test.size(); j++) _local_ke(i, j) += t * _test[j][_qp]; } // mass matrix is always SPD _local_sol.resize(_n_local_dofs); _local_ke.cholesky_solve(_local_re, _local_sol); _var.setNodalValue(_local_sol); } } } bool AuxKernel::isNodal() { return _nodal; } const VariableValue & AuxKernel::coupledDot(const std::string & var_name, unsigned int comp) { MooseVariable * var = getVar(var_name, comp); if (var->kind() == Moose::VAR_AUXILIARY) mooseError(name() << ": Unable to couple time derivative of an auxiliary variable into the auxiliary system."); return Coupleable::coupledDot(var_name, comp); } const VariableValue & AuxKernel::coupledDotDu(const std::string & var_name, unsigned int comp) { MooseVariable * var = getVar(var_name, comp); if (var->kind() == Moose::VAR_AUXILIARY) mooseError(name() << ": Unable to couple time derivative of an auxiliary variable into the auxiliary system."); return Coupleable::coupledDotDu(var_name, comp); }
#include "NRF24L01P.hh" #if !defined(BOARD_ATTINYX5) #include "Cosa/Power.hh" #include "Cosa/RTT.hh" #include <util/delay.h> NRF24L01P::NRF24L01P(uint16_t net, uint8_t dev, Board::DigitalPin csn, Board::DigitalPin ce, Board::<API key> irq) : SPI::Driver(csn, SPI::ACTIVE_LOW, SPI::DIV4_CLOCK, 0, SPI::MSB_ORDER, &m_irq), Wireless::Driver(net, dev), m_ce(ce, 0), m_irq(irq, ExternalInterrupt::ON_FALLING_MODE, this), m_status(0), m_state(POWER_DOWN_STATE), m_trans(0), m_retrans(0), m_drops(0) { channel(64); } uint8_t NRF24L01P::read(Command cmd) { spi.acquire(this); spi.begin(); m_status = spi.transfer(cmd); uint8_t res = spi.transfer(0); spi.end(); spi.release(); return (res); } void NRF24L01P::read(Command cmd, void* buf, size_t size) { spi.acquire(this); spi.begin(); m_status = spi.transfer(cmd); spi.read(buf, size); spi.end(); spi.release(); } void NRF24L01P::write(Command cmd) { spi.acquire(this); spi.begin(); m_status = spi.transfer(cmd); spi.end(); spi.release(); } void NRF24L01P::write(Command cmd, uint8_t data) { spi.acquire(this); spi.begin(); m_status = spi.transfer(cmd); spi.transfer(data); spi.end(); spi.release(); } void NRF24L01P::write(Command cmd, const void* buf, size_t size) { spi.acquire(this); spi.begin(); m_status = spi.transfer(cmd); spi.write(buf, size); spi.end(); spi.release(); } NRF24L01P::status_t NRF24L01P::read_status() { spi.acquire(this); spi.begin(); m_status = spi.transfer(NOP); spi.end(); spi.release(); return (m_status); } void NRF24L01P::powerup() { if (m_state != POWER_DOWN_STATE) return; m_ce.clear(); // Setup configuration for powerup and clear interrupts write(CONFIG, (_BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP))); _delay_ms(Tpd2stby_ms); m_state = STANDBY_STATE; // Flush status write(STATUS, (_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT))); write(FLUSH_TX); write(FLUSH_RX); } void NRF24L01P::receiver_mode() { // Check already in receive mode if (m_state == RX_STATE) return; // Configure primary receiver mode write(CONFIG, (_BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP) | _BV(PRIM_RX))); m_ce.set(); if (m_state == STANDBY_STATE) _delay_us(Tstby2a_us); m_state = RX_STATE; } void NRF24L01P::transmit_mode(uint8_t dest) { // Setup primary transmit address addr_t tx_addr(m_addr.network, dest); write(TX_ADDR, &tx_addr, sizeof(tx_addr)); // Trigger the transmitter mode if (m_state != TX_STATE) { m_ce.clear(); write(CONFIG, (_BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP))); m_ce.set(); } // Wait for the transmitter to become active if (m_state == STANDBY_STATE) _delay_us(Tstby2a_us); m_state = TX_STATE; } void NRF24L01P::standby() { m_ce.clear(); _delay_us(Thce_us); m_state = STANDBY_STATE; } void NRF24L01P::powerdown() { delay(32); m_ce.clear(); write(CONFIG, (_BV(EN_CRC) | _BV(CRCO))); m_state = POWER_DOWN_STATE; } bool NRF24L01P::begin(const void* config) { UNUSED(config); // Check that a device is available if (UNLIKELY(read_status().reserved)) return (false); // Setup hardware features, channel, bitrate, retransmission, dynamic payload write(FEATURE, (_BV(EN_DPL) | _BV(EN_ACK_PAY) | _BV(EN_DYN_ACK))); write(RF_CH, m_channel); write(RF_SETUP, (RF_DR_2MBPS | RF_PWR_0DBM)); write(SETUP_RETR, ((DEFAULT_ARD << ARD) | (DEFAULT_ARC << ARC))); write(DYNPD, DPL_PA); // Setup hardware receive pipes address; network (16-bit), device (8-bit) // P0: auto-acknowledge (see transmit_mode) // P1: node address<network:device> with auto-acknowledge // P2: broadcast<network:0> addr_t rx_addr = m_addr; write(SETUP_AW, AW_3BYTES); write(RX_ADDR_P1, &rx_addr, sizeof(rx_addr)); write(RX_ADDR_P2, BROADCAST); write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1))); write(EN_AA, (_BV(ENAA_P1) | _BV(ENAA_P0))); // Ready to go powerup(); spi.attach(this); m_irq.enable(); return (true); } int NRF24L01P::send(uint8_t dest, uint8_t port, const iovec_t* vec) { // Sanity check the payload size if (UNLIKELY(vec == NULL)) return (EINVAL); size_t len = iovec_size(vec); if (UNLIKELY(len > PAYLOAD_MAX)) return (EMSGSIZE); // Setting transmit destination transmit_mode(dest); // Write source address and payload to the transmit fifo // Fix: Allow larger payload(30*3) with fragmentation spi.acquire(this); spi.begin(); uint8_t command = ((dest != BROADCAST) ? W_TX_PAYLOAD : W_TX_PAYLOAD_NO_ACK); m_status = spi.transfer(command); spi.transfer(m_addr.device); spi.transfer(port); spi.write(vec); spi.end(); spi.release(); m_trans += 1; // Check for auto-acknowledge pipe(0), and address setup and enable if (dest != BROADCAST) { addr_t tx_addr(m_addr.network, dest); write(RX_ADDR_P0, &tx_addr, sizeof(tx_addr)); write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1) | _BV(ERX_P0))); } // Wait for transmission do { yield(); read_status(); } while (!m_status.tx_ds && !m_status.max_rt); bool data_sent = m_status.tx_ds; // Check for auto-acknowledge pipe(0) disable if (dest != BROADCAST) { write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1))); } // Reset status bits and read retransmission counter and update write(STATUS, _BV(MAX_RT) | _BV(TX_DS)); observe_tx_t observe = read_observe_tx(); m_retrans += observe.arc_cnt; // Check that the message was delivered if (data_sent) return (len); // Failed to delivery write(FLUSH_TX); m_drops += 1; return (EIO); } int NRF24L01P::send(uint8_t dest, uint8_t port, const void* buf, size_t len) { iovec_t vec[2]; iovec_t* vp = vec; iovec_arg(vp, buf, len); iovec_end(vp); return (send(dest, port, vec)); } bool NRF24L01P::available() { // Check the receiver fifo if (read_fifo_status().rx_empty) return (false); // Sanity check the size of the payload. Might require a flush if (read(R_RX_PL_WID) <= DEVICE_PAYLOAD_MAX) return (true); write(FLUSH_RX); return (false); } int NRF24L01P::recv(uint8_t& src, uint8_t& port, void* buf, size_t size, uint32_t ms) { // Run in receiver mode receiver_mode(); // Check if there is data available on any pipe uint32_t start = RTT::millis(); while (!available()) { if ((ms != 0) && (RTT::since(start) > ms)) return (ETIME); yield(); } m_dest = (m_status.rx_p_no == 1 ? m_addr.device : BROADCAST); write(STATUS, _BV(RX_DR)); // Check for payload error from device (Tab. 20, pp. 51, R_RX_PL_WID) uint8_t count = read(R_RX_PL_WID) - 2; if ((count > PAYLOAD_MAX) || (count > size)) { write(FLUSH_RX); return (EMSGSIZE); } // Read the source address, port and payload spi.acquire(this); spi.begin(); m_status = spi.transfer(R_RX_PAYLOAD); src = spi.transfer(0); port = spi.transfer(0); spi.read(buf, count); spi.end(); spi.release(); return (count); } void NRF24L01P::output_power_level(int8_t dBm) { uint8_t pwr = RF_PWR_0DBM; if (dBm < -12) pwr = RF_PWR_18DBM; else if (dBm < -6) pwr = RF_PWR_12DBM; else if (dBm < 0) pwr = RF_PWR_6DBM; write(RF_SETUP, (RF_DR_2MBPS | pwr)); } // Output operators for bitfield status registers IOStream& operator<<(IOStream& outs, NRF24L01P::status_t status) { outs << PSTR("RX_DR = ") << status.rx_dr << PSTR(", TX_DS = ") << status.tx_ds << PSTR(", MAX_RT = ") << status.max_rt << PSTR(", RX_P_NO = ") << status.rx_p_no << PSTR(", TX_FULL = ") << status.tx_full; return (outs); } IOStream& operator<<(IOStream& outs, NRF24L01P::observe_tx_t observe) { outs << PSTR("PLOS_CNT = ") << observe.plos_cnt << PSTR(", ARC_CNT = ") << observe.arc_cnt; return (outs); } IOStream& operator<<(IOStream& outs, NRF24L01P::fifo_status_t fifo) { outs << PSTR("RX_EMPTY = ") << fifo.rx_empty << PSTR(", RX_FULL = ") << fifo.rx_full << PSTR(", TX_EMPTY = ") << fifo.tx_empty << PSTR(", TX_FULL = ") << fifo.tx_full << PSTR(", TX_REUSE = ") << fifo.tx_reuse; return (outs); } #endif
package org.hivedb.util; import java.io.IOException; import java.io.StringWriter; import java.util.Properties; import org.apache.velocity.Template; import org.apache.velocity.app.Velocity; import org.apache.velocity.context.Context; import org.apache.velocity.exception.<API key>; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.<API key>; import org.hivedb.<API key>; public class Templater { public static String render(String templateFile, Context context) { try { Velocity.init(<API key>()); } catch (Exception e) { throw new <API key>("Failed to initialize Velocity templatng engine."); } Template template = null; try { template = Velocity.getTemplate(templateFile); } catch (<API key> e) { throw new <API key>("Unable to locate template: " + templateFile); } catch (ParseErrorException e) { throw new <API key>("Error parsing template: " + templateFile); } catch (Exception e) { throw new RuntimeException(e); } StringWriter writer = new StringWriter(); try { template.merge(context, writer); } catch (Exception e) { throw new <API key>(e); } return writer.toString(); } public static Properties <API key>() { Properties p = new Properties(); p.setProperty( "resource.loader", "class" ); p.setProperty( "class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.<API key>" ); return p; } }
#ifndef QTOPTIONSPAGE_H #define QTOPTIONSPAGE_H #include "<API key>.h" #include <coreplugin/dialogs/ioptionspage.h> #include <QWidget> #include <QIcon> QT_BEGIN_NAMESPACE class QTreeWidgetItem; QT_END_NAMESPACE namespace ProjectExplorer { class ToolChain; } namespace QtSupport { class BaseQtVersion; class QtConfigWidget; namespace Internal { namespace Ui { class QtVersionManager; class QtVersionInfo; class DebuggingHelper; } class QtOptionsPageWidget : public QWidget { Q_OBJECT public: QtOptionsPageWidget(QWidget *parent, QList<BaseQtVersion *> versions); ~QtOptionsPageWidget(); QList<BaseQtVersion *> versions() const; void finish(); QString searchKeywords() const; virtual bool eventFilter(QObject *o, QEvent *e); private: void <API key>(); void <API key>(); void updateWidgets(); void <API key>(); void fixQtVersionName(int index); int indexForTreeItem(const QTreeWidgetItem *item) const; QTreeWidgetItem *treeItemForIndex(int index) const; BaseQtVersion *currentVersion() const; int currentIndex() const; void <API key>(const QTreeWidgetItem *currentItem); const QString m_specifyNameString; Internal::Ui::QtVersionManager *m_ui; Internal::Ui::QtVersionInfo *m_versionUi; Internal::Ui::DebuggingHelper *m_debuggingHelperUi; QList<BaseQtVersion *> m_versions; int m_defaultVersion; QIcon <API key>; QIcon <API key>; QIcon m_validVersionIcon; QtConfigWidget *<API key>; private slots: void qtVersionChanged(); void versionChanged(QTreeWidgetItem *item, QTreeWidgetItem *old); void addQtDir(); void removeQtDir(); void editPath(); void updateCleanUpButton(); void updateCurrentQtName(); void <API key>(<API key>::Tools tools = <API key>::AllTools); void buildGdbHelper(); void buildQmlDump(); void <API key>(); void buildQmlObserver(); void <API key>(); void <API key>(int qtVersionId, const QString &output, <API key>::Tools tools); void cleanUpQtVersions(); void toolChainsUpdated(); void <API key>(int index); void <API key>(const Utils::FileName &qmakeCommand); void <API key>(bool expanded); private: struct ValidityInfo { QString message; QString toolTip; QIcon icon; }; ValidityInfo validInformation(const BaseQtVersion *version); QList<ProjectExplorer::ToolChain*> toolChains(const BaseQtVersion *version); QString defaultToolChainId(const BaseQtVersion *verison); }; class QtOptionsPage : public Core::IOptionsPage { Q_OBJECT public: QtOptionsPage(); QString id() const; QString displayName() const; QString category() const; QString displayCategory() const; QIcon categoryIcon() const; QWidget *createPage(QWidget *parent); void apply(); void finish() {} virtual bool matches(const QString &) const; private: QtOptionsPageWidget *m_widget; QString m_searchKeywords; }; } //namespace Internal } //namespace Qt4ProjectManager #endif // QTOPTIONSPAGE_H
# distutils/version.py # Implements multiple version numbering conventions for the # Python Module Distribution Utilities. """Provides classes to represent module version numbers (one class for each style of version numbering). There are currently two such classes implemented: StrictVersion and LooseVersion. Every version number class implements the following interface: * the 'parse' method takes a string and parses it to some internal representation; if the string is an invalid version number, 'parse' raises a ValueError exception * the class constructor takes an optional string argument which, if supplied, is passed to 'parse' * __str__ reconstructs the string that was passed to 'parse' (or an equivalent string -- ie. one that will generate an equivalent version number instance) * __repr__ generates Python code to recreate the version number instance * _cmp compares the current instance with either another instance of the same class or a string (which will be parsed to an instance of the same class, thus must follow the same rules) """ import re class Version: """Abstract base class for version numbering classes. Just provides constructor (__init__) and reproducer (__repr__), because those seem to be the same for all version numbering classes; and route rich comparisons to _cmp. """ def __init__ (self, vstring=None): if vstring: self.parse(vstring) def __repr__ (self): return "%s ('%s')" % (self.__class__.__name__, str(self)) def __eq__(self, other): c = self._cmp(other) if c is NotImplemented: return c return c == 0 def __lt__(self, other): c = self._cmp(other) if c is NotImplemented: return c return c < 0 def __le__(self, other): c = self._cmp(other) if c is NotImplemented: return c return c <= 0 def __gt__(self, other): c = self._cmp(other) if c is NotImplemented: return c return c > 0 def __ge__(self, other): c = self._cmp(other) if c is NotImplemented: return c return c >= 0 # Interface for version-number classes -- must be implemented # by the following classes (the concrete ones -- Version should # be treated as an abstract class). # __init__ (string) - create and take same action as 'parse' # (string parameter is optional) # parse (string) - convert a string representation to whatever # internal representation is appropriate for # this style of version numbering # __str__ (self) - convert back to a string; should be very similar # (if not identical to) the string supplied to parse # __repr__ (self) - generate Python code to recreate # the instance # _cmp (self, other) - compare two version numbers ('other' may # be an unparsed version string, or another # instance of your version class) class StrictVersion (Version): """Version numbering for anal retentives and software idealists. Implements the standard interface for version number classes as described above. A version number consists of two or three dot-separated numeric components, with an optional "pre-release" tag on the end. The pre-release tag consists of the letter 'a' or 'b' followed by a number. If the numeric components of two version numbers are equal, then one with a pre-release tag will always be deemed earlier (lesser) than one without. The following are valid version numbers (shown in the order that would be obtained by sorting according to the supplied cmp function): 0.4 0.4.0 (these two are equivalent) 0.4.1 0.5a1 0.5b3 0.5 0.9.6 1.0 1.0.4a3 1.0.4b1 1.0.4 The following are examples of invalid version numbers: 1 2.7.2.2 1.3.a4 1.3pl1 1.3c4 The rationale for this version numbering system will be explained in the distutils documentation. """ version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII) def parse (self, vstring): match = self.version_re.match(vstring) if not match: raise ValueError("invalid version number '%s'" % vstring) (major, minor, patch, prerelease, prerelease_num) = \ match.group(1, 2, 4, 5, 6) if patch: self.version = tuple(map(int, [major, minor, patch])) else: self.version = tuple(map(int, [major, minor])) + (0,) if prerelease: self.prerelease = (prerelease[0], int(prerelease_num)) else: self.prerelease = None def __str__ (self): if self.version[2] == 0: vstring = '.'.join(map(str, self.version[0:2])) else: vstring = '.'.join(map(str, self.version)) if self.prerelease: vstring = vstring + self.prerelease[0] + str(self.prerelease[1]) return vstring def _cmp (self, other): if isinstance(other, str): other = StrictVersion(other) if self.version != other.version: # numeric versions don't match # prerelease stuff doesn't matter if self.version < other.version: return -1 else: return 1 # have to compare prerelease # case 1: neither has prerelease; they're equal # case 2: self has prerelease, other doesn't; other is greater # case 3: self doesn't have prerelease, other does: self is greater # case 4: both have prerelease: must compare them! if (not self.prerelease and not other.prerelease): return 0 elif (self.prerelease and not other.prerelease): return -1 elif (not self.prerelease and other.prerelease): return 1 elif (self.prerelease and other.prerelease): if self.prerelease == other.prerelease: return 0 elif self.prerelease < other.prerelease: return -1 else: return 1 else: assert False, "never get here" # end class StrictVersion # The rules according to Greg Stein: # 1) a version number has 1 or more numbers separated by a period or by # sequences of letters. If only periods, then these are compared # left-to-right to determine an ordering. # 2) sequences of letters are part of the tuple for comparison and are # compared lexicographically # 3) recognize the numeric components may have leading zeroes # The LooseVersion class below implements these rules: a version number # string is split up into a tuple of integer and string components, and # comparison is a simple tuple comparison. This means that version # numbers behave in a predictable and obvious way, but a way that might # not necessarily be how people *want* version numbers to behave. There # wouldn't be a problem if people could stick to purely numeric version # numbers: just split on period and compare the numbers as tuples. # However, people insist on putting letters into their version numbers; # the most common purpose seems to be: # - indicating a "pre-release" version # ('alpha', 'beta', 'a', 'b', 'pre', 'p') # - indicating a post-release patch ('p', 'pl', 'patch') # but of course this can't cover all version number schemes, and there's # no way to know what a programmer means without asking him. # The problem is what to do with letters (and other non-numeric # characters) in a version number. The current implementation does the # obvious and predictable thing: keep them as strings and compare # lexically within a tuple comparison. This has the desired effect if # an appended letter sequence implies something "post-release": # eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002". # However, if letters in a version number imply a pre-release version, # the "obvious" thing isn't correct. Eg. you would expect that # "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison # implemented here, this just isn't so. # Two possible solutions come to mind. The first is to tie the # comparison algorithm to a particular set of semantic rules, as has # been done in the StrictVersion class above. This works great as long # as everyone can go along with bondage and discipline. Hopefully a # (large) subset of Python module programmers will agree that the # particular flavour of bondage and discipline provided by StrictVersion # provides enough benefit to be worth using, and will submit their # version numbering scheme to its domination. The free-thinking # anarchists in the lot will never give in, though, and something needs # to be done to accommodate them. # Perhaps a "moderately strict" version class could be implemented that # lets almost anything slide (syntactically), and makes some heuristic # assumptions about non-digits in version number strings. This could # sink into special-case-hell, though; if I was as talented and # idiosyncratic as Larry Wall, I'd go ahead and implement a class that # somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is # just as happy dealing with things like "2g6" and "1.13++". I don't # think I'm smart enough to do it right though. # In any case, I've coded the test suite for this module (see # ../test/test_version.py) specifically to fail on things like comparing # "1.2a2" and "1.2". That's not because the *code* is doing anything # wrong, it's because the simple, obvious design doesn't match my # complicated, hairy expectations for real-world version numbers. It # would be a snap to fix the test suite to say, "Yep, LooseVersion does # the Right Thing" (ie. the code matches the conception). But I'd rather # have a conception that matches common notions about version numbers. class LooseVersion (Version): """Version numbering for anarchists and software realists. Implements the standard interface for version number classes as described above. A version number consists of a series of numbers, separated by either periods or strings of letters. When comparing version numbers, the numeric components will be compared numerically, and the alphabetic components lexically. The following are all valid version numbers, in no particular order: 1.5.1 1.5.2b2 161 3.10a 8.02 3.4j 1996.07.12 3.2.pl0 3.1.1.6 2g6 11g 0.960923 2.2beta29 1.13++ 5.5.kw 2.0b1pl0 In fact, there is no such thing as an invalid version number under this scheme; the rules for comparison are simple and predictable, but may not always give the results you want (for some definition of "want"). """ component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) def __init__ (self, vstring=None): if vstring: self.parse(vstring) def parse (self, vstring): # I've given up on thinking I can reconstruct the version string # from the parsed tuple -- so I just store the string here for # use by __str__ self.vstring = vstring components = [x for x in self.component_re.split(vstring) if x and x != '.'] for i, obj in enumerate(components): try: components[i] = int(obj) except ValueError: pass self.version = components def __str__ (self): return self.vstring def __repr__ (self): return "LooseVersion ('%s')" % str(self) def _cmp (self, other): if isinstance(other, str): other = LooseVersion(other) if self.version == other.version: return 0 if self.version < other.version: return -1 if self.version > other.version: return 1 # end class LooseVersion
package org.pentaho.di.ui.job.entries.mail; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Random; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.Props; import org.pentaho.di.core.ResultFile; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entries.mail.JobEntryMail; import org.pentaho.di.job.entry.<API key>; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.<API key>; import org.pentaho.di.ui.core.widget.LabelText; import org.pentaho.di.ui.core.widget.LabelTextVar; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.job.dialog.JobDialog; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; /** * Dialog that allows you to edit a JobEntryMail object. * * @author Matt * @since 19-06-2003 */ public class JobEntryMailDialog extends JobEntryDialog implements <API key> { private static Class<?> PKG = JobEntryMail.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private static final String[] IMAGES_FILE_TYPES = new String[] { BaseMessages.getString(PKG, "JobMail.Filetype.Png"), BaseMessages.getString(PKG, "JobMail.Filetype.Jpeg"), BaseMessages.getString(PKG, "JobMail.Filetype.Gif"), BaseMessages.getString(PKG, "JobMail.Filetype.All") }; private LabelText wName; private FormData fdName; private LabelTextVar wDestination; private LabelTextVar wDestinationCc; private LabelTextVar wDestinationBCc; private FormData fdDestination; private FormData fdDestinationCc; private FormData fdDestinationBCc; private LabelTextVar wServer; private FormData fdServer; private LabelTextVar wPort; private FormData fdPort; private Label wlUseAuth; private Button wUseAuth; private FormData fdlUseAuth, fdUseAuth; private Label wlUseSecAuth; private Button wUseSecAuth; private FormData fdlUseSecAuth, fdUseSecAuth; private LabelTextVar wAuthUser; private FormData fdAuthUser; private LabelTextVar wAuthPass; private FormData fdAuthPass; private LabelTextVar wReply,wReplyName; private FormData fdReply,fdReplyName; private LabelTextVar wSubject; private FormData fdSubject; private Label wlAddDate; private Button wAddDate; private FormData fdlAddDate, fdAddDate; private Label wlIncludeFiles; private Button wIncludeFiles; private FormData fdlIncludeFiles, fdIncludeFiles; private Label wlTypes; private List wTypes; private FormData fdlTypes, fdTypes; private Label wlZipFiles; private Button wZipFiles; private FormData fdlZipFiles, fdZipFiles; private LabelTextVar wZipFilename; private FormData fdZipFilename; private LabelTextVar wPerson; private FormData fdPerson; private LabelTextVar wPhone; private FormData fdPhone; private Label wlComment; private Text wComment; private FormData fdlComment, fdComment; private Label wlOnlyComment, wlUseHTML, wlUsePriority; private Button wOnlyComment, wUseHTML,wUsePriority; private FormData fdlOnlyComment, fdOnlyComment, fdlUseHTML, fdUseHTML, fdUsePriority; private Label wlEncoding; private CCombo wEncoding; private FormData fdlEncoding, fdEncoding; private Label <API key>; private CCombo <API key>; private FormData <API key>, <API key>; private Label wlPriority; private CCombo wPriority; private FormData fdlPriority, fdPriority; private Label wlImportance; private CCombo wImportance; private FormData fdlImportance, fdImportance; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Shell shell; private SelectionAdapter lsDef; private JobEntryMail jobEntry; private boolean backupDate, backupChanged; private Display display; private boolean gotEncodings = false; private LabelTextVar wReplyToAddress; private FormData fdReplyToAddress; private CTabFolder wTabFolder; private Composite wGeneralComp,wContentComp,wAttachedComp,wMessageComp; private CTabItem wGeneralTab,wContentTab,wAttachedTab,wMessageTab; private FormData fdGeneralComp,fdContentComp,fdAttachedComp,fdMessageComp; private FormData fdTabFolder; private Group wDestinationGroup,wReplyGroup,wServerGroup,w<API key>,<API key>, wMessageGroup,wResultFilesGroup, <API key>; private FormData fdDestinationGroup,fdReplyGroup,fdServerGroup,fd<API key>, <API key>,fdMessageGroup,fdResultFilesGroup, <API key>; private Label wlImageFilename, wlContentID, wlFields; private Button wbImageFilename, wbaImageFilename, wbdImageFilename, wbeImageFilename; private TextVar wImageFilename, wContentID; private FormData fdlImageFilename, fdbImageFilename, fdImageFilename,fdlContentID, fdContentID, fdbaImageFilename, fdbdImageFilename, fdbeImageFilename, fdlFields, fdFields; private TableView wFields; public JobEntryMailDialog(Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta) { super(parent, jobEntryInt, rep, jobMeta); jobEntry = (JobEntryMail) jobEntryInt; } public JobEntryInterface open() { Shell parent = getParent(); display = parent.getDisplay(); shell = new Shell(parent, props.getJobsDialogStyle()); props.setLook(shell); JobDialog.setShellImage(shell, jobEntry); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { jobEntry.setChanged(); } }; backupChanged = jobEntry.hasChanged(); backupDate = jobEntry.getIncludeDate(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "JobMail.Header")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Name line wName = new LabelText(shell, BaseMessages.getString(PKG, "JobMail.NameOfEntry.Label"), BaseMessages.getString(PKG, "JobMail.NameOfEntry.Tooltip")); wName.addModifyListener(lsMod); fdName = new FormData(); fdName.top = new FormAttachment(0, 0); fdName.left = new FormAttachment(0, 0); fdName.right = new FormAttachment(100, 0); wName.setLayoutData(fdName); wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); // START OF GENERAL TAB /// wGeneralTab=new CTabItem(wTabFolder, SWT.NONE); wGeneralTab.setText(BaseMessages.getString(PKG, "JobMail.Tab.General.Label")); wGeneralComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wGeneralComp); FormLayout generalLayout = new FormLayout(); generalLayout.marginWidth = 3; generalLayout.marginHeight = 3; wGeneralComp.setLayout(generalLayout); // START OF Destination Settings GROUP wDestinationGroup = new Group(wGeneralComp, SWT.SHADOW_NONE); props.setLook(wDestinationGroup); wDestinationGroup.setText(BaseMessages.getString(PKG, "JobMail.Group.DestinationAddress.Label")); FormLayout <API key> = new FormLayout(); <API key>.marginWidth = 10; <API key>.marginHeight = 10; wDestinationGroup.setLayout(<API key>); // Destination line wDestination = new LabelTextVar(jobMeta, wDestinationGroup, BaseMessages.getString(PKG, "JobMail.DestinationAddress.Label"), BaseMessages.getString(PKG, "JobMail.DestinationAddress.Tooltip")); wDestination.addModifyListener(lsMod); fdDestination = new FormData(); fdDestination.left = new FormAttachment(0, 0); fdDestination.top = new FormAttachment(wName, margin); fdDestination.right = new FormAttachment(100, 0); wDestination.setLayoutData(fdDestination); // Destination Cc wDestinationCc = new LabelTextVar(jobMeta, wDestinationGroup, BaseMessages.getString(PKG, "JobMail.<API key>.Label"), BaseMessages.getString(PKG, "JobMail.<API key>.Tooltip")); wDestinationCc.addModifyListener(lsMod); fdDestinationCc = new FormData(); fdDestinationCc.left = new FormAttachment(0, 0); fdDestinationCc.top = new FormAttachment(wDestination, margin); fdDestinationCc.right = new FormAttachment(100, 0); wDestinationCc.setLayoutData(fdDestinationCc); // Destination BCc wDestinationBCc = new LabelTextVar(jobMeta, wDestinationGroup, BaseMessages.getString(PKG, "JobMail.<API key>.Label"), BaseMessages.getString(PKG, "JobMail.<API key>.Tooltip")); wDestinationBCc.addModifyListener(lsMod); fdDestinationBCc = new FormData(); fdDestinationBCc.left = new FormAttachment(0, 0); fdDestinationBCc.top = new FormAttachment(wDestinationCc, margin); fdDestinationBCc.right = new FormAttachment(100, 0); wDestinationBCc.setLayoutData(fdDestinationBCc); fdDestinationGroup = new FormData(); fdDestinationGroup.left = new FormAttachment(0, margin); fdDestinationGroup.top = new FormAttachment(wName, margin); fdDestinationGroup.right = new FormAttachment(100, -margin); wDestinationGroup.setLayoutData(fdDestinationGroup); // / END OF DESTINATION ADDRESS GROUP // START OF Reply Settings GROUP wReplyGroup = new Group(wGeneralComp, SWT.SHADOW_NONE); props.setLook(wReplyGroup); wReplyGroup.setText(BaseMessages.getString(PKG, "JobMail.Group.Reply.Label")); FormLayout replygroupLayout = new FormLayout(); replygroupLayout.marginWidth = 10; replygroupLayout.marginHeight = 10; wReplyGroup.setLayout(replygroupLayout); // Reply name wReplyName = new LabelTextVar(jobMeta, wReplyGroup, BaseMessages.getString(PKG, "JobMail.ReplyName.Label"), BaseMessages.getString(PKG, "JobMail.ReplyName.Tooltip")); wReplyName.addModifyListener(lsMod); fdReplyName = new FormData(); fdReplyName.left = new FormAttachment(0, 0); fdReplyName.top = new FormAttachment(wDestinationGroup, 2*margin); fdReplyName.right = new FormAttachment(100, 0); wReplyName.setLayoutData(fdReplyName); // Reply line wReply = new LabelTextVar(jobMeta, wReplyGroup, BaseMessages.getString(PKG, "JobMail.ReplyAddress.Label"), BaseMessages.getString(PKG, "JobMail.ReplyAddress.Tooltip")); wReply.addModifyListener(lsMod); fdReply = new FormData(); fdReply.left = new FormAttachment(0, 0); fdReply.top = new FormAttachment(wReplyName, margin); fdReply.right = new FormAttachment(100, 0); wReply.setLayoutData(fdReply); fdReplyGroup = new FormData(); fdReplyGroup.left = new FormAttachment(0, margin); fdReplyGroup.top = new FormAttachment(wDestinationGroup, margin); fdReplyGroup.right = new FormAttachment(100, -margin); wReplyGroup.setLayoutData(fdReplyGroup); // / END OF Replay GROUP // Reply to wReplyToAddress = new LabelTextVar(jobMeta, wGeneralComp, BaseMessages.getString(PKG, "JobMail.ReplyToAddress.Label"), BaseMessages.getString(PKG, "JobMail.ReplyToAddress.Tooltip")); wReplyToAddress.addModifyListener(lsMod); fdReplyToAddress = new FormData(); fdReplyToAddress.left = new FormAttachment(0, 0); fdReplyToAddress.top = new FormAttachment(wReplyGroup, 2*margin); fdReplyToAddress.right = new FormAttachment(100, 0); wReplyToAddress.setLayoutData(fdReplyToAddress); // Contact line wPerson = new LabelTextVar(jobMeta, wGeneralComp, BaseMessages.getString(PKG, "JobMail.ContactPerson.Label"), BaseMessages.getString(PKG, "JobMail.ContactPerson.Tooltip")); wPerson.addModifyListener(lsMod); fdPerson = new FormData(); fdPerson.left = new FormAttachment(0, 0); fdPerson.top = new FormAttachment(wReplyToAddress, 2*margin); fdPerson.right = new FormAttachment(100, 0); wPerson.setLayoutData(fdPerson); // Phone line wPhone = new LabelTextVar(jobMeta, wGeneralComp, BaseMessages.getString(PKG, "JobMail.ContactPhone.Label"), BaseMessages.getString(PKG, "JobMail.ContactPhone.Tooltip")); wPhone.addModifyListener(lsMod); fdPhone = new FormData(); fdPhone.left = new FormAttachment(0, 0); fdPhone.top = new FormAttachment(wPerson, margin); fdPhone.right = new FormAttachment(100, 0); wPhone.setLayoutData(fdPhone); fdGeneralComp=new FormData(); fdGeneralComp.left = new FormAttachment(0, 0); fdGeneralComp.top = new FormAttachment(0, 0); fdGeneralComp.right = new FormAttachment(100, 0); fdGeneralComp.bottom= new FormAttachment(500, -margin); wGeneralComp.setLayoutData(fdGeneralComp); wGeneralComp.layout(); wGeneralTab.setControl(wGeneralComp); props.setLook(wGeneralComp); END OF GENERAL TAB // START OF SERVER TAB /// wContentTab=new CTabItem(wTabFolder, SWT.NONE); wContentTab.setText(BaseMessages.getString(PKG, "JobMailDialog.Server.Label")); FormLayout contentLayout = new FormLayout (); contentLayout.marginWidth = 3; contentLayout.marginHeight = 3; wContentComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wContentComp); wContentComp.setLayout(contentLayout); // START OF SERVER GROUP wServerGroup = new Group(wContentComp, SWT.SHADOW_NONE); props.setLook(wServerGroup); wServerGroup.setText(BaseMessages.getString(PKG, "JobMail.Group.SMTPServer.Label")); FormLayout servergroupLayout = new FormLayout(); servergroupLayout.marginWidth = 10; servergroupLayout.marginHeight = 10; wServerGroup.setLayout(servergroupLayout); // Server line wServer = new LabelTextVar(jobMeta, wServerGroup, BaseMessages.getString(PKG, "JobMail.SMTPServer.Label"), BaseMessages.getString(PKG, "JobMail.SMTPServer.Tooltip")); wServer.addModifyListener(lsMod); fdServer = new FormData(); fdServer.left = new FormAttachment(0, 0); fdServer.top = new FormAttachment(0, margin); fdServer.right = new FormAttachment(100, 0); wServer.setLayoutData(fdServer); // Port line wPort = new LabelTextVar(jobMeta, wServerGroup, BaseMessages.getString(PKG, "JobMail.Port.Label"), BaseMessages.getString(PKG, "JobMail.Port.Tooltip")); wPort.addModifyListener(lsMod); fdPort = new FormData(); fdPort.left = new FormAttachment(0, 0); fdPort.top = new FormAttachment(wServer, margin); fdPort.right = new FormAttachment(100, 0); wPort.setLayoutData(fdPort); fdServerGroup = new FormData(); fdServerGroup.left = new FormAttachment(0, margin); fdServerGroup.top = new FormAttachment(wName, margin); fdServerGroup.right = new FormAttachment(100, -margin); wServerGroup.setLayoutData(fdServerGroup); // / END OF SERVER ADDRESS GROUP // START OF AUTHENTIFICATION GROUP w<API key> = new Group(wContentComp, SWT.SHADOW_NONE); props.setLook(w<API key>); w<API key>.setText(BaseMessages.getString(PKG, "JobMail.Group.Authentification.Label")); FormLayout <API key> = new FormLayout(); <API key>.marginWidth = 10; <API key>.marginHeight = 10; w<API key>.setLayout(<API key>); // Authentication? wlUseAuth = new Label(w<API key>, SWT.RIGHT); wlUseAuth.setText(BaseMessages.getString(PKG, "JobMail.UseAuthentication.Label")); props.setLook(wlUseAuth); fdlUseAuth = new FormData(); fdlUseAuth.left = new FormAttachment(0, 0); fdlUseAuth.top = new FormAttachment(wServerGroup, 2*margin); fdlUseAuth.right = new FormAttachment(middle, -margin); wlUseAuth.setLayoutData(fdlUseAuth); wUseAuth = new Button(w<API key>, SWT.CHECK); props.setLook(wUseAuth); fdUseAuth = new FormData(); fdUseAuth.left = new FormAttachment(middle, margin); fdUseAuth.top = new FormAttachment(wServerGroup, 2*margin); fdUseAuth.right = new FormAttachment(100, 0); wUseAuth.setLayoutData(fdUseAuth); wUseAuth.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setUseAuth(); jobEntry.setChanged(); } }); // AuthUser line wAuthUser = new LabelTextVar(jobMeta, w<API key>, BaseMessages.getString(PKG, "JobMail.AuthenticationUser.Label"), BaseMessages.getString(PKG, "JobMail.AuthenticationUser.Tooltip")); wAuthUser.addModifyListener(lsMod); fdAuthUser = new FormData(); fdAuthUser.left = new FormAttachment(0, 0); fdAuthUser.top = new FormAttachment(wUseAuth, margin); fdAuthUser.right = new FormAttachment(100, 0); wAuthUser.setLayoutData(fdAuthUser); // AuthPass line wAuthPass = new LabelTextVar(jobMeta, w<API key>, BaseMessages.getString(PKG, "JobMail.<API key>.Label"), BaseMessages.getString(PKG, "JobMail.<API key>.Tooltip")); wAuthPass.setEchoChar('*'); wAuthPass.addModifyListener(lsMod); fdAuthPass = new FormData(); fdAuthPass.left = new FormAttachment(0, 0); fdAuthPass.top = new FormAttachment(wAuthUser, margin); fdAuthPass.right = new FormAttachment(100, 0); wAuthPass.setLayoutData(fdAuthPass); // Use secure authentication? wlUseSecAuth = new Label(w<API key>, SWT.RIGHT); wlUseSecAuth.setText(BaseMessages.getString(PKG, "JobMail.<API key>.Label")); props.setLook(wlUseSecAuth); fdlUseSecAuth = new FormData(); fdlUseSecAuth.left = new FormAttachment(0, 0); fdlUseSecAuth.top = new FormAttachment(wAuthPass, 2*margin); fdlUseSecAuth.right = new FormAttachment(middle, -margin); wlUseSecAuth.setLayoutData(fdlUseSecAuth); wUseSecAuth = new Button(w<API key>, SWT.CHECK); props.setLook(wUseSecAuth); fdUseSecAuth = new FormData(); fdUseSecAuth.left = new FormAttachment(middle, margin); fdUseSecAuth.top = new FormAttachment(wAuthPass, 2*margin); fdUseSecAuth.right = new FormAttachment(100, 0); wUseSecAuth.setLayoutData(fdUseSecAuth); wUseSecAuth.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { <API key>(); jobEntry.setChanged(); } }); // <API key> <API key>=new Label(w<API key>, SWT.RIGHT); <API key>.setText(BaseMessages.getString(PKG, "JobMail.<API key>.Label")); props.setLook(<API key>); <API key>=new FormData(); <API key>.left = new FormAttachment(0, 0); <API key>.top = new FormAttachment(wUseSecAuth, margin); <API key>.right= new FormAttachment(middle, -margin); <API key>.setLayoutData(<API key>); <API key>=new CCombo(w<API key>, SWT.BORDER | SWT.READ_ONLY); <API key>.setEditable(true); props.setLook(<API key>); <API key>.addModifyListener(lsMod); <API key>=new FormData(); <API key>.left = new FormAttachment(middle, margin); <API key>.top = new FormAttachment(wUseSecAuth,margin); <API key>.right= new FormAttachment(100, 0); <API key>.setLayoutData(<API key>); <API key>.add("SSL"); <API key>.add("TLS"); <API key>.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { <API key>(); jobEntry.setChanged(); } }); fd<API key> = new FormData(); fd<API key>.left = new FormAttachment(0, margin); fd<API key>.top = new FormAttachment(wServerGroup, margin); fd<API key>.right = new FormAttachment(100, -margin); fd<API key>.bottom = new FormAttachment(100, -margin); w<API key>.setLayoutData(fd<API key>); // / END OF AUTHENTIFICATION GROUP fdContentComp = new FormData(); fdContentComp.left = new FormAttachment(0, 0); fdContentComp.top = new FormAttachment(0, 0); fdContentComp.right = new FormAttachment(100, 0); fdContentComp.bottom= new FormAttachment(100, 0); wContentComp.setLayoutData(wContentComp); wContentComp.layout(); wContentTab.setControl(wContentComp); END OF SERVER TAB // START OF MESSAGE TAB /// wMessageTab=new CTabItem(wTabFolder, SWT.NONE); wMessageTab.setText(BaseMessages.getString(PKG, "JobMail.Tab.Message.Label")); FormLayout messageLayout = new FormLayout (); messageLayout.marginWidth = 3; messageLayout.marginHeight = 3; wMessageComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wMessageComp); wMessageComp.setLayout(contentLayout); // START OF MESSAGE SETTINGS GROUP <API key> = new Group(wMessageComp, SWT.SHADOW_NONE); props.setLook(<API key>); <API key>.setText(BaseMessages.getString(PKG, "JobMail.Group.MessageSettings.Label")); FormLayout <API key> = new FormLayout(); <API key>.marginWidth = 10; <API key>.marginHeight = 10; <API key>.setLayout(<API key>); // Add date to logfile name? wlAddDate = new Label(<API key>, SWT.RIGHT); wlAddDate.setText(BaseMessages.getString(PKG, "JobMail.IncludeDate.Label")); props.setLook(wlAddDate); fdlAddDate = new FormData(); fdlAddDate.left = new FormAttachment(0, 0); fdlAddDate.top = new FormAttachment(0,margin); fdlAddDate.right = new FormAttachment(middle, -margin); wlAddDate.setLayoutData(fdlAddDate); wAddDate = new Button(<API key>, SWT.CHECK); props.setLook(wAddDate); fdAddDate = new FormData(); fdAddDate.left = new FormAttachment(middle, margin); fdAddDate.top = new FormAttachment(0, margin); fdAddDate.right = new FormAttachment(100, 0); wAddDate.setLayoutData(fdAddDate); wAddDate.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); // Only send the comment in the mail body wlOnlyComment = new Label(<API key>, SWT.RIGHT); wlOnlyComment.setText(BaseMessages.getString(PKG, "JobMail.OnlyCommentInBody.Label")); props.setLook(wlOnlyComment); fdlOnlyComment = new FormData(); fdlOnlyComment.left = new FormAttachment(0, 0); fdlOnlyComment.top = new FormAttachment(wAddDate, margin); fdlOnlyComment.right = new FormAttachment(middle, -margin); wlOnlyComment.setLayoutData(fdlOnlyComment); wOnlyComment = new Button(<API key>, SWT.CHECK); props.setLook(wOnlyComment); fdOnlyComment = new FormData(); fdOnlyComment.left = new FormAttachment(middle, margin); fdOnlyComment.top = new FormAttachment(wAddDate, margin ); fdOnlyComment.right = new FormAttachment(100, 0); wOnlyComment.setLayoutData(fdOnlyComment); wOnlyComment.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); // HTML format ? wlUseHTML = new Label(<API key>, SWT.RIGHT); wlUseHTML.setText(BaseMessages.getString(PKG, "JobMail.UseHTMLInBody.Label")); props.setLook(wlUseHTML); fdlUseHTML = new FormData(); fdlUseHTML.left = new FormAttachment(0, 0); fdlUseHTML.top = new FormAttachment(wOnlyComment, margin ); fdlUseHTML.right = new FormAttachment(middle, -margin); wlUseHTML.setLayoutData(fdlUseHTML); wUseHTML = new Button(<API key>, SWT.CHECK); props.setLook(wUseHTML); fdUseHTML = new FormData(); fdUseHTML.left = new FormAttachment(middle, margin); fdUseHTML.top = new FormAttachment(wOnlyComment, margin ); fdUseHTML.right = new FormAttachment(100, 0); wUseHTML.setLayoutData(fdUseHTML); wUseHTML.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { SetEnabledEncoding(); jobEntry.setChanged(); } }); // Encoding wlEncoding=new Label(<API key>, SWT.RIGHT); wlEncoding.setText(BaseMessages.getString(PKG, "JobMail.Encoding.Label")); props.setLook(wlEncoding); fdlEncoding=new FormData(); fdlEncoding.left = new FormAttachment(0, 0); fdlEncoding.top = new FormAttachment(wUseHTML, margin); fdlEncoding.right= new FormAttachment(middle, -margin); wlEncoding.setLayoutData(fdlEncoding); wEncoding=new CCombo(<API key>, SWT.BORDER | SWT.READ_ONLY); wEncoding.setEditable(true); props.setLook(wEncoding); wEncoding.addModifyListener(lsMod); fdEncoding=new FormData(); fdEncoding.left = new FormAttachment(middle, margin); fdEncoding.top = new FormAttachment(wUseHTML,margin); fdEncoding.right= new FormAttachment(100, 0); wEncoding.setLayoutData(fdEncoding); wEncoding.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); setEncodings(); shell.setCursor(null); busy.dispose(); } } ); // Use Priority ? wlUsePriority = new Label(<API key>, SWT.RIGHT); wlUsePriority.setText(BaseMessages.getString(PKG, "JobMail.UsePriority.Label")); props.setLook(wlUsePriority); fdlPriority = new FormData(); fdlPriority.left = new FormAttachment(0, 0); fdlPriority.top = new FormAttachment(wEncoding, margin ); fdlPriority.right = new FormAttachment(middle, -margin); wlUsePriority.setLayoutData(fdlPriority); wUsePriority = new Button(<API key>, SWT.CHECK); wUsePriority.setToolTipText(BaseMessages.getString(PKG, "JobMail.UsePriority.Tooltip")); props.setLook(wUsePriority); fdUsePriority = new FormData(); fdUsePriority.left = new FormAttachment(middle, margin); fdUsePriority.top = new FormAttachment(wEncoding, margin ); fdUsePriority.right = new FormAttachment(100, 0); wUsePriority.setLayoutData(fdUsePriority); wUsePriority.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { activeUsePriority(); jobEntry.setChanged(); } }); // Priority wlPriority = new Label(<API key>, SWT.RIGHT); wlPriority.setText(BaseMessages.getString(PKG, "JobMail.Priority.Label")); props.setLook(wlPriority); fdlPriority = new FormData(); fdlPriority.left = new FormAttachment(0, 0); fdlPriority.right = new FormAttachment(middle, -margin); fdlPriority.top = new FormAttachment(wUsePriority, margin); wlPriority.setLayoutData(fdlPriority); wPriority = new CCombo(<API key>, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); wPriority.add(BaseMessages.getString(PKG, "JobMail.Priority.Low.Label")); wPriority.add(BaseMessages.getString(PKG, "JobMail.Priority.Normal.Label")); wPriority.add(BaseMessages.getString(PKG, "JobMail.Priority.High.Label")); wPriority.select(1); // +1: starts at -1 props.setLook(wPriority); fdPriority = new FormData(); fdPriority.left = new FormAttachment(middle, 0); fdPriority.top = new FormAttachment(wUsePriority, margin); fdPriority.right = new FormAttachment(100, 0); wPriority.setLayoutData(fdPriority); // Importance wlImportance = new Label(<API key>, SWT.RIGHT); wlImportance.setText(BaseMessages.getString(PKG, "JobMail.Importance.Label")); props.setLook(wlImportance); fdlImportance = new FormData(); fdlImportance.left = new FormAttachment(0, 0); fdlImportance.right = new FormAttachment(middle, -margin); fdlImportance.top = new FormAttachment(wPriority, margin); wlImportance.setLayoutData(fdlImportance); wImportance = new CCombo(<API key>, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); wImportance.add(BaseMessages.getString(PKG, "JobMail.Priority.Low.Label")); wImportance.add(BaseMessages.getString(PKG, "JobMail.Priority.Normal.Label")); wImportance.add(BaseMessages.getString(PKG, "JobMail.Priority.High.Label")); wImportance.select(1); // +1: starts at -1 props.setLook(wImportance); fdImportance = new FormData(); fdImportance.left = new FormAttachment(middle, 0); fdImportance.top = new FormAttachment(wPriority, margin); fdImportance.right = new FormAttachment(100, 0); wImportance.setLayoutData(fdImportance); <API key> = new FormData(); <API key>.left = new FormAttachment(0, margin); <API key>.top = new FormAttachment(wName, margin); <API key>.right = new FormAttachment(100, -margin); <API key>.setLayoutData(<API key>); // / END OF MESSAGE SETTINGS GROUP // START OF MESSAGE GROUP wMessageGroup = new Group(wMessageComp, SWT.SHADOW_NONE); props.setLook(wMessageGroup); wMessageGroup.setText(BaseMessages.getString(PKG, "JobMail.Group.Message.Label")); FormLayout messagegroupLayout = new FormLayout(); messagegroupLayout.marginWidth = 10; messagegroupLayout.marginHeight = 10; wMessageGroup.setLayout(messagegroupLayout); // Subject line wSubject = new LabelTextVar(jobMeta, wMessageGroup, BaseMessages.getString(PKG, "JobMail.Subject.Label"), BaseMessages.getString(PKG, "JobMail.Subject.Tooltip")); wSubject.addModifyListener(lsMod); fdSubject = new FormData(); fdSubject.left = new FormAttachment(0, 0); fdSubject.top = new FormAttachment(<API key>, margin); fdSubject.right = new FormAttachment(100, 0); wSubject.setLayoutData(fdSubject); // Comment line wlComment = new Label(wMessageGroup, SWT.RIGHT); wlComment.setText(BaseMessages.getString(PKG, "JobMail.Comment.Label")); props.setLook(wlComment); fdlComment = new FormData(); fdlComment.left = new FormAttachment(0, 0); fdlComment.top = new FormAttachment(wSubject, 2*margin); fdlComment.right = new FormAttachment(middle, margin); wlComment.setLayoutData(fdlComment); wComment = new Text(wMessageGroup, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wComment); wComment.addModifyListener(lsMod); fdComment = new FormData(); fdComment.left = new FormAttachment(middle, margin); fdComment.top = new FormAttachment(wSubject, 2*margin); fdComment.right = new FormAttachment(100, 0); fdComment.bottom = new FormAttachment(100, -margin); wComment.setLayoutData(fdComment); //SelectionAdapter lsVar = <API key>.getSelectionAdapter(shell, wComment, jobMeta); wComment.addKeyListener(new <API key>(jobMeta, wComment)); fdMessageGroup = new FormData(); fdMessageGroup.left = new FormAttachment(0, margin); fdMessageGroup.top = new FormAttachment(<API key>, margin); fdMessageGroup.bottom = new FormAttachment(100, -margin); fdMessageGroup.right = new FormAttachment(100, -margin); wMessageGroup.setLayoutData(fdMessageGroup); // / END OF MESSAGE GROUP fdMessageComp = new FormData(); fdMessageComp.left = new FormAttachment(0, 0); fdMessageComp.top = new FormAttachment(0, 0); fdMessageComp.right = new FormAttachment(100, 0); fdMessageComp.bottom= new FormAttachment(100, 0); wMessageComp.setLayoutData(wMessageComp); wMessageComp.layout(); wMessageTab.setControl(wMessageComp); END OF MESSAGE TAB // START OF ATTACHED FILES TAB /// wAttachedTab=new CTabItem(wTabFolder, SWT.NONE); wAttachedTab.setText(BaseMessages.getString(PKG, "JobMail.Tab.AttachedFiles.Label")); FormLayout attachedLayout = new FormLayout (); attachedLayout.marginWidth = 3; attachedLayout.marginHeight = 3; wAttachedComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wAttachedComp); wAttachedComp.setLayout(attachedLayout); // START OF Result File GROUP wResultFilesGroup = new Group(wAttachedComp, SWT.SHADOW_NONE); props.setLook(wResultFilesGroup); wResultFilesGroup.setText(BaseMessages.getString(PKG, "JobMail.Group.AddPreviousFiles.Label")); FormLayout <API key> = new FormLayout(); <API key>.marginWidth = 10; <API key>.marginHeight = 10; wResultFilesGroup.setLayout(<API key>); // Include Files? wlIncludeFiles = new Label(wResultFilesGroup, SWT.RIGHT); wlIncludeFiles.setText(BaseMessages.getString(PKG, "JobMail.AttachFiles.Label")); props.setLook(wlIncludeFiles); fdlIncludeFiles = new FormData(); fdlIncludeFiles.left = new FormAttachment(0, 0); fdlIncludeFiles.top = new FormAttachment(0, margin); fdlIncludeFiles.right = new FormAttachment(middle, -margin); wlIncludeFiles.setLayoutData(fdlIncludeFiles); wIncludeFiles = new Button(wResultFilesGroup, SWT.CHECK); props.setLook(wIncludeFiles); fdIncludeFiles = new FormData(); fdIncludeFiles.left = new FormAttachment(middle, margin); fdIncludeFiles.top = new FormAttachment(0, margin); fdIncludeFiles.right = new FormAttachment(100, 0); wIncludeFiles.setLayoutData(fdIncludeFiles); wIncludeFiles.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // Include Files? wlTypes = new Label(wResultFilesGroup, SWT.RIGHT); wlTypes.setText(BaseMessages.getString(PKG, "JobMail.SelectFileTypes.Label")); props.setLook(wlTypes); fdlTypes = new FormData(); fdlTypes.left = new FormAttachment(0, 0); fdlTypes.top = new FormAttachment(wIncludeFiles, margin); fdlTypes.right = new FormAttachment(middle, -margin); wlTypes.setLayoutData(fdlTypes); wTypes = new List(wResultFilesGroup, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wTypes); fdTypes = new FormData(); fdTypes.left = new FormAttachment(middle, margin); fdTypes.top = new FormAttachment(wIncludeFiles, margin); fdTypes.bottom = new FormAttachment(wIncludeFiles, margin + 150); fdTypes.right = new FormAttachment(100, 0); wTypes.setLayoutData(fdTypes); for (int i = 0; i < ResultFile.getAllTypeDesc().length; i++) { wTypes.add(ResultFile.getAllTypeDesc()[i]); } // Zip Files? wlZipFiles = new Label(wResultFilesGroup, SWT.RIGHT); wlZipFiles.setText(BaseMessages.getString(PKG, "JobMail.ZipFiles.Label")); props.setLook(wlZipFiles); fdlZipFiles = new FormData(); fdlZipFiles.left = new FormAttachment(0, 0); fdlZipFiles.top = new FormAttachment(wTypes, margin); fdlZipFiles.right = new FormAttachment(middle, -margin); wlZipFiles.setLayoutData(fdlZipFiles); wZipFiles = new Button(wResultFilesGroup, SWT.CHECK); props.setLook(wZipFiles); fdZipFiles = new FormData(); fdZipFiles.left = new FormAttachment(middle, margin); fdZipFiles.top = new FormAttachment(wTypes, margin); fdZipFiles.right = new FormAttachment(100, 0); wZipFiles.setLayoutData(fdZipFiles); wZipFiles.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // ZipFilename line wZipFilename = new LabelTextVar(jobMeta, wResultFilesGroup, BaseMessages.getString(PKG, "JobMail.ZipFilename.Label"), BaseMessages.getString(PKG, "JobMail.ZipFilename.Tooltip")); wZipFilename.addModifyListener(lsMod); fdZipFilename = new FormData(); fdZipFilename.left = new FormAttachment(0, 0); fdZipFilename.top = new FormAttachment(wZipFiles, margin); fdZipFilename.right = new FormAttachment(100, 0); wZipFilename.setLayoutData(fdZipFilename); fdResultFilesGroup = new FormData(); fdResultFilesGroup.left = new FormAttachment(0, margin); fdResultFilesGroup.top = new FormAttachment(0, margin); //fdResultFilesGroup.bottom = new FormAttachment(100, -margin); fdResultFilesGroup.right = new FormAttachment(100, -margin); wResultFilesGroup.setLayoutData(fdResultFilesGroup); // / END OF RESULT FILES GROUP // START OF Embedded Images GROUP <API key>= new Group(wAttachedComp, SWT.SHADOW_NONE); props.setLook(<API key>); <API key>.setText(BaseMessages.getString(PKG, "JobMail.Group.EmbeddedImages.Label")); FormLayout <API key> = new FormLayout(); <API key>.marginWidth = 10; <API key>.marginHeight = 10; <API key>.setLayout(<API key>); // ImageFilename line wlImageFilename=new Label(<API key>, SWT.RIGHT); wlImageFilename.setText(BaseMessages.getString(PKG, "JobMail.ImageFilename.Label")); props.setLook(wlImageFilename); fdlImageFilename=new FormData(); fdlImageFilename.left = new FormAttachment(0, 0); fdlImageFilename.top = new FormAttachment(wResultFilesGroup, margin); fdlImageFilename.right= new FormAttachment(middle, -margin); wlImageFilename.setLayoutData(fdlImageFilename); wbImageFilename=new Button(<API key>, SWT.PUSH| SWT.CENTER); props.setLook(wbImageFilename); wbImageFilename.setText(BaseMessages.getString(PKG, "JobMail.BrowseFiles.Label")); fdbImageFilename=new FormData(); fdbImageFilename.right= new FormAttachment(100, 0); fdbImageFilename.top = new FormAttachment(wResultFilesGroup, margin); fdbImageFilename.right= new FormAttachment(100, -margin); wbImageFilename.setLayoutData(fdbImageFilename); wbaImageFilename=new Button(<API key>, SWT.PUSH| SWT.CENTER); props.setLook(wbaImageFilename); wbaImageFilename.setText(BaseMessages.getString(PKG, "JobMail.ImageFilenameAdd.Button")); fdbaImageFilename=new FormData(); fdbaImageFilename.right= new FormAttachment(wbImageFilename, -margin); fdbaImageFilename.top = new FormAttachment(wResultFilesGroup, margin); wbaImageFilename.setLayoutData(fdbaImageFilename); wImageFilename=new TextVar(jobMeta, <API key>, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wImageFilename); wImageFilename.addModifyListener(lsMod); fdImageFilename=new FormData(); fdImageFilename.left = new FormAttachment(middle, 0); fdImageFilename.top = new FormAttachment(wResultFilesGroup, margin); fdImageFilename.right= new FormAttachment(wbImageFilename, -40); wImageFilename.setLayoutData(fdImageFilename); wImageFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wImageFilename.setToolTipText(jobMeta.<API key>( wImageFilename.getText() ) ); } } ); wbImageFilename.<API key> ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*png;*PNG", "*jpeg;*jpg;*JPEG;*JPG", "*gif;*GIF", "*"}); if (wImageFilename.getText()!=null) { dialog.setFileName(jobMeta.<API key>(wImageFilename.getText()) ); } dialog.setFilterNames(IMAGES_FILE_TYPES); if (dialog.open()!=null) { wImageFilename.setText(dialog.getFilterPath()+Const.FILE_SEPARATOR+dialog.getFileName()); Random randomgen = new Random(); wContentID.setText(Long.toString(Math.abs(randomgen.nextLong()), 32)); } } } ); // ContentID wlContentID= new Label(<API key>, SWT.RIGHT); wlContentID.setText(BaseMessages.getString(PKG, "JobMail.ContentID.Label")); props.setLook(wlContentID); fdlContentID= new FormData(); fdlContentID.left = new FormAttachment(0, 0); fdlContentID.top = new FormAttachment(wImageFilename, margin); fdlContentID.right = new FormAttachment(middle, -margin); wlContentID.setLayoutData(fdlContentID); wContentID= new TextVar(jobMeta, <API key>, SWT.SINGLE | SWT.LEFT | SWT.BORDER, BaseMessages.getString(PKG, "JobMail.ContentID.Tooltip")); props.setLook(wContentID); wContentID.addModifyListener(lsMod); fdContentID= new FormData(); fdContentID.left = new FormAttachment(middle, 0); fdContentID.top = new FormAttachment(wImageFilename, margin); fdContentID.right= new FormAttachment(wbImageFilename, -40); wContentID.setLayoutData(fdContentID); // Buttons to the right of the screen... wbdImageFilename=new Button(<API key>, SWT.PUSH| SWT.CENTER); props.setLook(wbdImageFilename); wbdImageFilename.setText(BaseMessages.getString(PKG, "JobMail.ImageFilenameDelete.Button")); wbdImageFilename.setToolTipText(BaseMessages.getString(PKG, "JobMail.ImageFilenameDelete.Tooltip")); fdbdImageFilename=new FormData(); fdbdImageFilename.right = new FormAttachment(100, 0); fdbdImageFilename.top = new FormAttachment (wContentID, 40); wbdImageFilename.setLayoutData(fdbdImageFilename); wbeImageFilename=new Button(<API key>, SWT.PUSH| SWT.CENTER); props.setLook(wbeImageFilename); wbeImageFilename.setText(BaseMessages.getString(PKG, "JobMail.ImageFilenameEdit.Button")); wbeImageFilename.setToolTipText(BaseMessages.getString(PKG, "JobMail.ImageFilenameEdit.Tooltip")); fdbeImageFilename=new FormData(); fdbeImageFilename.right = new FormAttachment(100, 0); fdbeImageFilename.left = new FormAttachment(wbdImageFilename, 0, SWT.LEFT); fdbeImageFilename.top = new FormAttachment (wbdImageFilename, margin); wbeImageFilename.setLayoutData(fdbeImageFilename); wlFields = new Label(<API key>, SWT.NONE); wlFields.setText(BaseMessages.getString(PKG, "JobMail.Fields.Label")); props.setLook(wlFields); fdlFields = new FormData(); fdlFields.left = new FormAttachment(0, 0); fdlFields.right= new FormAttachment(middle, -margin); fdlFields.top = new FormAttachment(wContentID,margin); wlFields.setLayoutData(fdlFields); int rows = jobEntry.embeddedimages == null ? 1 : (jobEntry.embeddedimages.length == 0 ? 0 : jobEntry.embeddedimages.length); final int FieldsRows = rows; ColumnInfo[] colinf=new ColumnInfo[] { new ColumnInfo(BaseMessages.getString(PKG, "JobMail.Fields.Image.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "JobMail.Fields.ContentID.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false ), }; colinf[0].setUsingVariables(true); colinf[0].setToolTip(BaseMessages.getString(PKG, "JobMail.Fields.Image.Tooltip")); colinf[1].setUsingVariables(true); colinf[1].setToolTip(BaseMessages.getString(PKG, "JobMail.Fields.ContentID.Tooltip")); wFields = new TableView(jobMeta, <API key>, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props); fdFields = new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(wlFields, margin); fdFields.right = new FormAttachment(wbeImageFilename, -margin); fdFields.bottom = new FormAttachment(100, -margin); wFields.setLayoutData(fdFields); // Add the file to the list of files... SelectionAdapter selA = new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { wFields.add(new String[] { wImageFilename.getText(), wContentID.getText() } ); wImageFilename.setText(""); wContentID.setText(""); wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); } }; wbaImageFilename.<API key>(selA); wImageFilename.<API key>(selA); // Delete files from the list of files... wbdImageFilename.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { int idx[] = wFields.getSelectionIndices(); wFields.remove(idx); wFields.removeEmptyRows(); wFields.setRowNums(); } }); // Edit the selected file & remove from the list... wbeImageFilename.<API key>(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { int idx = wFields.getSelectionIndex(); if (idx>=0) { String string[] = wFields.getItem(idx); wImageFilename.setText(string[0]); wContentID.setText(string[1]); wFields.remove(idx); } wFields.removeEmptyRows(); wFields.setRowNums(); } }); <API key>= new FormData(); <API key>.left = new FormAttachment(0, margin); <API key>.top = new FormAttachment(wResultFilesGroup, margin); <API key>.bottom = new FormAttachment(100, -margin); <API key>.right = new FormAttachment(100, -margin); <API key>.setLayoutData(<API key>); // / END OF Embedded Images GROUP fdAttachedComp = new FormData(); fdAttachedComp.left = new FormAttachment(0, 0); fdAttachedComp.top = new FormAttachment(0, 0); fdAttachedComp.right = new FormAttachment(100, 0); fdAttachedComp.bottom= new FormAttachment(100, 0); wAttachedComp.setLayoutData(wAttachedComp); wAttachedComp.layout(); wAttachedTab.setControl(wAttachedComp); END OF FILES TAB fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.top = new FormAttachment(wName, margin); fdTabFolder.right = new FormAttachment(100, 0); fdTabFolder.bottom= new FormAttachment(100, -50); wTabFolder.setLayoutData(fdTabFolder); // Some buttons wOK = new Button(shell, SWT.PUSH); wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); BaseStepDialog.<API key>(shell, new Button[] { wOK, wCancel }, margin, wTabFolder); //setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder); // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; wOK.addListener(SWT.Selection, lsOK); wCancel.addListener(SWT.Selection, lsCancel); lsDef = new SelectionAdapter() { public void <API key>(SelectionEvent e) { ok(); } }; wName.<API key>(lsDef); wServer.<API key>(lsDef); wSubject.<API key>(lsDef); wDestination.<API key>(lsDef); wDestinationCc.<API key>(lsDef); wDestinationBCc.<API key>(lsDef); wReply.<API key>(lsDef); wPerson.<API key>(lsDef); wPhone.<API key>(lsDef); wZipFilename.<API key>(lsDef); // Detect [X] or ALT-F4 or something that kills this window... shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } }); // BaseStepDialog.setTraverseOrder(new Control[] {wName, wDestination, wServer, wUseAuth, // wAuthUser, wAuthPass, wReply, // wSubject, wAddDate, wIncludeFiles, wTypes, wZipFiles, wZipFilename, wPerson, wPhone, // wComment, wOK, wCancel }); getData(); SetEnabledEncoding(); activeUsePriority(); setFlags(); setUseAuth(); BaseStepDialog.setSize(shell); shell.open(); props.setDialogSize(shell, "JobMailDialogSize"); wTabFolder.setSelection(0); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return jobEntry; } private void activeUsePriority() { wlPriority.setEnabled(wUsePriority.getSelection()); wPriority.setEnabled(wUsePriority.getSelection()); wlImportance.setEnabled(wUsePriority.getSelection()); wImportance.setEnabled(wUsePriority.getSelection()); } private void SetEnabledEncoding () { wEncoding.setEnabled(wUseHTML.getSelection()); wlEncoding.setEnabled(wUseHTML.getSelection()); wlImageFilename.setEnabled(wUseHTML.getSelection()); wlImageFilename.setEnabled(wUseHTML.getSelection()); wbImageFilename.setEnabled(wUseHTML.getSelection()); wbaImageFilename.setEnabled(wUseHTML.getSelection()); wImageFilename.setEnabled(wUseHTML.getSelection()); wlContentID.setEnabled(wUseHTML.getSelection()); wContentID.setEnabled(wUseHTML.getSelection()); wbdImageFilename.setEnabled(wUseHTML.getSelection()); wbeImageFilename.setEnabled(wUseHTML.getSelection()); wlFields.setEnabled(wUseHTML.getSelection()); wFields.setEnabled(wUseHTML.getSelection()); } protected void <API key>() { <API key>.setEnabled(wUseSecAuth.getSelection()); <API key>.setEnabled(wUseSecAuth.getSelection()); } protected void setFlags() { wlTypes.setEnabled(wIncludeFiles.getSelection()); wTypes.setEnabled(wIncludeFiles.getSelection()); wlZipFiles.setEnabled(wIncludeFiles.getSelection()); wZipFiles.setEnabled(wIncludeFiles.getSelection()); wZipFilename.setEnabled(wIncludeFiles.getSelection() && wZipFiles.getSelection()); } protected void setUseAuth() { wAuthUser.setEnabled(wUseAuth.getSelection()); wAuthPass.setEnabled(wUseAuth.getSelection()); wUseSecAuth.setEnabled(wUseAuth.getSelection()); wlUseSecAuth.setEnabled(wUseAuth.getSelection()); if (!wUseAuth.getSelection()) { <API key>.setEnabled(false); <API key>.setEnabled(false); } else { <API key>(); } } public void dispose() { WindowProperty winprop = new WindowProperty(shell); props.setScreen(winprop); shell.dispose(); } public void getData() { if (jobEntry.getName() != null) wName.setText(jobEntry.getName()); if (jobEntry.getDestination() != null) wDestination.setText(jobEntry.getDestination()); if (jobEntry.getDestinationCc() != null) wDestinationCc.setText(jobEntry.getDestinationCc()); if (jobEntry.getDestinationBCc() != null) wDestinationBCc.setText(jobEntry.getDestinationBCc()); if (jobEntry.getServer() != null) wServer.setText(jobEntry.getServer()); if (jobEntry.getPort() != null) wPort.setText(jobEntry.getPort()); if (jobEntry.getReplyAddress() != null) wReply.setText(jobEntry.getReplyAddress()); if (jobEntry.getReplyName() != null) wReplyName.setText(jobEntry.getReplyName()); if (jobEntry.getSubject() != null) wSubject.setText(jobEntry.getSubject()); if (jobEntry.getContactPerson() != null) wPerson.setText(jobEntry.getContactPerson()); if (jobEntry.getContactPhone() != null) wPhone.setText(jobEntry.getContactPhone()); if (jobEntry.getComment() != null) wComment.setText(jobEntry.getComment()); wAddDate.setSelection(jobEntry.getIncludeDate()); wIncludeFiles.setSelection(jobEntry.isIncludingFiles()); if (jobEntry.getFileType() != null) { int types[] = jobEntry.getFileType(); wTypes.setSelection(types); } wZipFiles.setSelection(jobEntry.isZipFiles()); if (jobEntry.getZipFilename() != null) wZipFilename.setText(jobEntry.getZipFilename()); wUseAuth.setSelection(jobEntry.<API key>()); wUseSecAuth.setSelection(jobEntry.<API key>()); if (jobEntry.<API key>() != null) wAuthUser.setText(jobEntry.<API key>()); if (jobEntry.get<API key>() != null) wAuthPass.setText(jobEntry.get<API key>()); wOnlyComment.setSelection(jobEntry.isOnlySendComment()); wUseHTML.setSelection(jobEntry.isUseHTML()); if (jobEntry.getEncoding()!=null) { wEncoding.setText(""+jobEntry.getEncoding()); }else { wEncoding.setText("UTF-8");} // Secure connection type if (jobEntry.<API key>() !=null) { <API key>.setText(jobEntry.<API key>()); } else { <API key>.setText("SSL"); } wUsePriority.setSelection(jobEntry.isUsePriority()); // Priority if (jobEntry.getPriority()!=null) { if (jobEntry.getPriority().equals("low")) { wPriority.select(0); // Low } else if (jobEntry.getPriority().equals("normal")) { wPriority.select(1); // Normal } else { wPriority.select(2); // Default High } } else { wPriority.select(3); // Default High } // Importance if (jobEntry.getImportance()!=null) { if (jobEntry.getImportance().equals("low")) { wImportance.select(0); // Low } else if (jobEntry.getImportance().equals("normal")) { wImportance.select(1); // Normal } else { wImportance.select(2); // Default High } } else { wImportance.select(3); // Default High } if (jobEntry.getReplyToAddresses() != null) wReplyToAddress.setText(jobEntry.getReplyToAddresses()); if (jobEntry.embeddedimages != null) { for (int i = 0; i < jobEntry.embeddedimages.length; i++) { TableItem ti = wFields.table.getItem(i); if (jobEntry.embeddedimages[i] != null) ti.setText(1, jobEntry.embeddedimages[i]); if (jobEntry.contentids[i] != null) ti.setText(2, jobEntry.contentids[i]); } wFields.setRowNums(); wFields.optWidth(true); } } private void cancel() { jobEntry.setChanged(backupChanged); jobEntry.setIncludeDate(backupDate); jobEntry = null; dispose(); } private void ok() { if(Const.isEmpty(wName.getText())) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setText(BaseMessages.getString(PKG, "System.<API key>.Title")); mb.setMessage(BaseMessages.getString(PKG, "System.JobEntryNameMissing.Msg")); mb.open(); return; } jobEntry.setName(wName.getText()); jobEntry.setDestination(wDestination.getText()); jobEntry.setDestinationCc(wDestinationCc.getText()); jobEntry.setDestinationBCc(wDestinationBCc.getText()); jobEntry.setServer(wServer.getText()); jobEntry.setPort(wPort.getText()); jobEntry.setReplyAddress(wReply.getText()); jobEntry.setReplyName(wReplyName.getText()); jobEntry.setSubject(wSubject.getText()); jobEntry.setContactPerson(wPerson.getText()); jobEntry.setContactPhone(wPhone.getText()); jobEntry.setComment(wComment.getText()); jobEntry.setIncludeDate(wAddDate.getSelection()); jobEntry.setIncludingFiles(wIncludeFiles.getSelection()); jobEntry.setFileType(wTypes.getSelectionIndices()); jobEntry.setZipFilename(wZipFilename.getText()); jobEntry.setZipFiles(wZipFiles.getSelection()); jobEntry.<API key>(wAuthUser.getText()); jobEntry.set<API key>(wAuthPass.getText()); jobEntry.<API key>(wUseAuth.getSelection()); jobEntry.<API key>(wUseSecAuth.getSelection()); jobEntry.setOnlySendComment(wOnlyComment.getSelection()); jobEntry.setUseHTML(wUseHTML.getSelection()); jobEntry.setUsePriority(wUsePriority.getSelection()); jobEntry.setEncoding(wEncoding.getText()); jobEntry.setPriority(wPriority.getText()); // Priority if (wPriority.getSelectionIndex()==0) { jobEntry.setPriority("low"); } else if (wPriority.getSelectionIndex()==1) { jobEntry.setPriority("normal"); } else { jobEntry.setPriority("high"); } // Importance if (wImportance.getSelectionIndex()==0) { jobEntry.setImportance("low"); } else if (wImportance.getSelectionIndex()==1) { jobEntry.setImportance("normal"); } else { jobEntry.setImportance("high"); } // Secure Connection type jobEntry.<API key>(<API key>.getText()); jobEntry.setReplyToAddresses(wReplyToAddress.getText()); int nritems = wFields.nrNonEmpty(); int nr = 0; for (int i = 0; i < nritems; i++) { String arg = wFields.getNonEmpty(i).getText(1); if (arg != null && arg.length() != 0) nr++; } jobEntry.embeddedimages = new String[nr]; jobEntry.contentids = new String[nr]; nr = 0; for (int i = 0; i < nritems; i++) { String arg = wFields.getNonEmpty(i).getText(1); String wild = wFields.getNonEmpty(i).getText(2); if (arg != null && arg.length() != 0) { jobEntry.embeddedimages[nr] = arg; jobEntry.contentids[nr] = wild; nr++; } } dispose(); } private void setEncodings() { // Encoding of the text file: if (!gotEncodings) { gotEncodings = true; wEncoding.removeAll(); java.util.List<Charset> values = new ArrayList<Charset>(Charset.availableCharsets().values()); for (Charset charSet:values) { wEncoding.add( charSet.displayName() ); } // Now select the default! String defEncoding = Const.<API key>("file.encoding", "UTF-8"); int idx = Const.indexOfString(defEncoding, wEncoding.getItems() ); if (idx>=0) wEncoding.select( idx ); } } }
goog.require('goog.Timer'); goog.require('goog.events'); goog.require('ola.DmxConsole'); goog.require('ola.common.BaseUniverseTab'); goog.require('ola.common.Server'); goog.provide('ola.DmxConsoleTab'); /** * The DMX console tab. * @constructor */ ola.DmxConsoleTab = function(element) { ola.common.BaseUniverseTab.call(this, element); // setup the console this.dmx_console = new ola.DmxConsole(); this.tick_timer = new goog.Timer(1000); this.mute_events = true; goog.events.listen( this.tick_timer, goog.Timer.TICK, this.consoleChanged_, false, this); goog.events.listen( this.dmx_console, ola.DmxConsole.CHANGE_EVENT, this.consoleChanged_, false, this); }; goog.inherits(ola.DmxConsoleTab, ola.common.BaseUniverseTab); /** * Set the universe. */ ola.DmxConsoleTab.prototype.setUniverse = function(universe_id) { ola.DmxConsoleTab.superClass_.setUniverse.call(this, universe_id); this.dmx_console.resetConsole(); }; /** * Called when the tab changes visibiliy. */ ola.DmxConsoleTab.prototype.setActive = function(state) { ola.DmxConsoleTab.superClass_.setActive.call(this, state); if (this.isActive()) { this.mute_events = true; this.dmx_console.setupIfRequired(); this.dmx_console.update(); this.loadValues(); } else { this.tick_timer.stop(); } }; /** * Fetches the new DMX values. */ ola.DmxConsoleTab.prototype.loadValues = function(e) { var t = this; ola.common.Server.getInstance().getChannelValues( this.getUniverse(), function(data) { t.newValues(data['dmx']); }); }; /** * Update the console with the new values */ ola.DmxConsoleTab.prototype.newValues = function(data) { this.dmx_console.setData(data); this.mute_events = false; if (this.isActive()) this.tick_timer.start(); }; /** * Called when the console values change * @private */ ola.DmxConsoleTab.prototype.consoleChanged_ = function(e) { if (this.mute_events) { return; } this.mute_events = true; var data = this.dmx_console.getData(); var t = this; ola.common.Server.getInstance().setChannelValues( this.getUniverse(), data, function(e) { t.mute_events = false; }); };
// <auto-generated> // This code was generated by AsyncGenerator. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> using NUnit.Framework; using System.Collections.Generic; using NHibernate.Dialect; namespace NHibernate.Test.NHSpecificTest.NH1773 { using System.Threading.Tasks; [TestFixture] public class FixtureAsync : BugTestCase { [Test] public async Task <API key>() { using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { IList<PersonResult> result = await (s.CreateQuery("select new PersonResult(p, current_timestamp()) from Person p left join fetch p.Country").ListAsync<PersonResult>()); Assert.AreEqual("My Name", result[0].Person.Name); Assert.IsTrue(NHibernateUtil.IsInitialized(result[0].Person.Country)); await (tx.CommitAsync()); } } protected override bool AppliesTo(Dialect.Dialect dialect) { // Fails with MS SQL Ce due to the query generating a duplicated column alias name, which this database does not support. return TestDialect.<API key>; } protected override void OnSetUp() { using (var s = OpenSession()) using (var tx = s.BeginTransaction()) { var c = new Country { Id = 100, Name = "US" }; var p = new Person { Age = 35, Name = "My Name", Id = 1, Country = c }; s.Save(c); s.Save(p); tx.Commit(); } } protected override void OnTearDown() { using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { s.CreateQuery("delete from Person").ExecuteUpdate(); s.CreateQuery("delete from Country").ExecuteUpdate(); tx.Commit(); } } } }
#ifndef GENERALPAGE_H #define GENERALPAGE_H #include <QtGui/QWizardPage> #include "ui_generalpage.h" QT_BEGIN_NAMESPACE class GeneralPage : public QWizardPage { Q_OBJECT public: GeneralPage(QWidget *parent = 0); private: bool validatePage(); bool isComplete() const; Ui::GeneralPage m_ui; }; QT_END_NAMESPACE #endif
#ifndef <API key> #define <API key> // W A R N I N G // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // We mean it. #include "<API key>.h" #include "private/<API key>.h" #include "private/<API key>.h" #include <QtCore/qobject.h> #include <QtCore/qrect.h> #include <QtCore/qeasingcurve.h> #include <QtCore/qvariant.h> #include <QtGui/qvector2d.h> #include <QtGui/qvector3d.h> #include <QtGui/qvector4d.h> #include <QtGui/qmatrix4x4.h> #include <QtGui/qquaternion.h> #include <QtGui/qfont.h> QT_BEGIN_NAMESPACE class <API key> <API key> : public QObject { Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int) = 0; virtual void write(QObject *, int, <API key>::WriteFlags flags) = 0; virtual QVariant value() = 0; virtual void setValue(QVariant) = 0; }; class <API key> <API key> { public: <API key>(); ~<API key>(); static bool isValueType(int); static <API key> *valueType(int); static void registerValueTypes(); <API key> *operator[](int idx) const { if (idx >= (int)QVariant::UserType) return 0; else return valueTypes[idx]; } private: <API key> *valueTypes[QVariant::UserType - 1]; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal x READ x WRITE setX) Q_PROPERTY(qreal y READ y WRITE setY) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal x() const; qreal y() const; void setX(qreal); void setY(qreal); private: QPointF point; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(int x READ x WRITE setX) Q_PROPERTY(int y READ y WRITE setY) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); int x() const; int y() const; void setX(int); void setY(int); private: QPoint point; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal width READ width WRITE setWidth) Q_PROPERTY(qreal height READ height WRITE setHeight) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal width() const; qreal height() const; void setWidth(qreal); void setHeight(qreal); private: QSizeF size; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(int width READ width WRITE setWidth) Q_PROPERTY(int height READ height WRITE setHeight) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); int width() const; int height() const; void setWidth(int); void setHeight(int); private: QSize size; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal x READ x WRITE setX) Q_PROPERTY(qreal y READ y WRITE setY) Q_PROPERTY(qreal width READ width WRITE setWidth) Q_PROPERTY(qreal height READ height WRITE setHeight) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal x() const; qreal y() const; void setX(qreal); void setY(qreal); qreal width() const; qreal height() const; void setWidth(qreal); void setHeight(qreal); private: QRectF rect; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(int x READ x WRITE setX) Q_PROPERTY(int y READ y WRITE setY) Q_PROPERTY(int width READ width WRITE setWidth) Q_PROPERTY(int height READ height WRITE setHeight) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); int x() const; int y() const; void setX(int); void setY(int); int width() const; int height() const; void setWidth(int); void setHeight(int); private: QRect rect; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal x READ x WRITE setX) Q_PROPERTY(qreal y READ y WRITE setY) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal x() const; qreal y() const; void setX(qreal); void setY(qreal); private: QVector2D vector; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal x READ x WRITE setX) Q_PROPERTY(qreal y READ y WRITE setY) Q_PROPERTY(qreal z READ z WRITE setZ) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal x() const; qreal y() const; qreal z() const; void setX(qreal); void setY(qreal); void setZ(qreal); private: QVector3D vector; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal x READ x WRITE setX) Q_PROPERTY(qreal y READ y WRITE setY) Q_PROPERTY(qreal z READ z WRITE setZ) Q_PROPERTY(qreal w READ w WRITE setW) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal x() const; qreal y() const; qreal z() const; qreal w() const; void setX(qreal); void setY(qreal); void setZ(qreal); void setW(qreal); private: QVector4D vector; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal scalar READ scalar WRITE setScalar) Q_PROPERTY(qreal x READ x WRITE setX) Q_PROPERTY(qreal y READ y WRITE setY) Q_PROPERTY(qreal z READ z WRITE setZ) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal scalar() const; qreal x() const; qreal y() const; qreal z() const; void setScalar(qreal); void setX(qreal); void setY(qreal); void setZ(qreal); private: QQuaternion quaternion; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_PROPERTY(qreal m11 READ m11 WRITE setM11) Q_PROPERTY(qreal m12 READ m12 WRITE setM12) Q_PROPERTY(qreal m13 READ m13 WRITE setM13) Q_PROPERTY(qreal m14 READ m14 WRITE setM14) Q_PROPERTY(qreal m21 READ m21 WRITE setM21) Q_PROPERTY(qreal m22 READ m22 WRITE setM22) Q_PROPERTY(qreal m23 READ m23 WRITE setM23) Q_PROPERTY(qreal m24 READ m24 WRITE setM24) Q_PROPERTY(qreal m31 READ m31 WRITE setM31) Q_PROPERTY(qreal m32 READ m32 WRITE setM32) Q_PROPERTY(qreal m33 READ m33 WRITE setM33) Q_PROPERTY(qreal m34 READ m34 WRITE setM34) Q_PROPERTY(qreal m41 READ m41 WRITE setM41) Q_PROPERTY(qreal m42 READ m42 WRITE setM42) Q_PROPERTY(qreal m43 READ m43 WRITE setM43) Q_PROPERTY(qreal m44 READ m44 WRITE setM44) Q_OBJECT public: <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); qreal m11() const { return matrix(0, 0); } qreal m12() const { return matrix(0, 1); } qreal m13() const { return matrix(0, 2); } qreal m14() const { return matrix(0, 3); } qreal m21() const { return matrix(1, 0); } qreal m22() const { return matrix(1, 1); } qreal m23() const { return matrix(1, 2); } qreal m24() const { return matrix(1, 3); } qreal m31() const { return matrix(2, 0); } qreal m32() const { return matrix(2, 1); } qreal m33() const { return matrix(2, 2); } qreal m34() const { return matrix(2, 3); } qreal m41() const { return matrix(3, 0); } qreal m42() const { return matrix(3, 1); } qreal m43() const { return matrix(3, 2); } qreal m44() const { return matrix(3, 3); } void setM11(qreal value) { matrix(0, 0) = value; } void setM12(qreal value) { matrix(0, 1) = value; } void setM13(qreal value) { matrix(0, 2) = value; } void setM14(qreal value) { matrix(0, 3) = value; } void setM21(qreal value) { matrix(1, 0) = value; } void setM22(qreal value) { matrix(1, 1) = value; } void setM23(qreal value) { matrix(1, 2) = value; } void setM24(qreal value) { matrix(1, 3) = value; } void setM31(qreal value) { matrix(2, 0) = value; } void setM32(qreal value) { matrix(2, 1) = value; } void setM33(qreal value) { matrix(2, 2) = value; } void setM34(qreal value) { matrix(2, 3) = value; } void setM41(qreal value) { matrix(3, 0) = value; } void setM42(qreal value) { matrix(3, 1) = value; } void setM43(qreal value) { matrix(3, 2) = value; } void setM44(qreal value) { matrix(3, 3) = value; } private: QMatrix4x4 matrix; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_OBJECT Q_ENUMS(Type) Q_PROPERTY(<API key>::Type type READ type WRITE setType) Q_PROPERTY(qreal amplitude READ amplitude WRITE setAmplitude) Q_PROPERTY(qreal overshoot READ overshoot WRITE setOvershoot) Q_PROPERTY(qreal period READ period WRITE setPeriod) public: enum Type { Linear = QEasingCurve::Linear, InQuad = QEasingCurve::InQuad, OutQuad = QEasingCurve::OutQuad, InOutQuad = QEasingCurve::InOutQuad, OutInQuad = QEasingCurve::OutInQuad, InCubic = QEasingCurve::InCubic, OutCubic = QEasingCurve::OutCubic, InOutCubic = QEasingCurve::InOutCubic, OutInCubic = QEasingCurve::OutInCubic, InQuart = QEasingCurve::InQuart, OutQuart = QEasingCurve::OutQuart, InOutQuart = QEasingCurve::InOutQuart, OutInQuart = QEasingCurve::OutInQuart, InQuint = QEasingCurve::InQuint, OutQuint = QEasingCurve::OutQuint, InOutQuint = QEasingCurve::InOutQuint, OutInQuint = QEasingCurve::OutInQuint, InSine = QEasingCurve::InSine, OutSine = QEasingCurve::OutSine, InOutSine = QEasingCurve::InOutSine, OutInSine = QEasingCurve::OutInSine, InExpo = QEasingCurve::InExpo, OutExpo = QEasingCurve::OutExpo, InOutExpo = QEasingCurve::InOutExpo, OutInExpo = QEasingCurve::OutInExpo, InCirc = QEasingCurve::InCirc, OutCirc = QEasingCurve::OutCirc, InOutCirc = QEasingCurve::InOutCirc, OutInCirc = QEasingCurve::OutInCirc, InElastic = QEasingCurve::InElastic, OutElastic = QEasingCurve::OutElastic, InOutElastic = QEasingCurve::InOutElastic, OutInElastic = QEasingCurve::OutInElastic, InBack = QEasingCurve::InBack, OutBack = QEasingCurve::OutBack, InOutBack = QEasingCurve::InOutBack, OutInBack = QEasingCurve::OutInBack, InBounce = QEasingCurve::InBounce, OutBounce = QEasingCurve::OutBounce, InOutBounce = QEasingCurve::InOutBounce, OutInBounce = QEasingCurve::OutInBounce, InCurve = QEasingCurve::InCurve, OutCurve = QEasingCurve::OutCurve, SineCurve = QEasingCurve::SineCurve, CosineCurve = QEasingCurve::CosineCurve }; <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); Type type() const; qreal amplitude() const; qreal overshoot() const; qreal period() const; void setType(Type); void setAmplitude(qreal); void setOvershoot(qreal); void setPeriod(qreal); private: QEasingCurve easing; }; class Q_AUTOTEST_EXPORT <API key> : public <API key> { Q_OBJECT Q_ENUMS(FontWeight) Q_ENUMS(Capitalization) Q_PROPERTY(QString family READ family WRITE setFamily) Q_PROPERTY(bool bold READ bold WRITE setBold) Q_PROPERTY(FontWeight weight READ weight WRITE setWeight) Q_PROPERTY(bool italic READ italic WRITE setItalic) Q_PROPERTY(bool underline READ underline WRITE setUnderline) Q_PROPERTY(bool overline READ overline WRITE setOverline) Q_PROPERTY(bool strikeout READ strikeout WRITE setStrikeout) Q_PROPERTY(qreal pointSize READ pointSize WRITE setPointSize) Q_PROPERTY(int pixelSize READ pixelSize WRITE setPixelSize) Q_PROPERTY(Capitalization capitalization READ capitalization WRITE setCapitalization) Q_PROPERTY(qreal letterSpacing READ letterSpacing WRITE setLetterSpacing) Q_PROPERTY(qreal wordSpacing READ wordSpacing WRITE setWordSpacing) public: enum FontWeight { Light = QFont::Light, Normal = QFont::Normal, DemiBold = QFont::DemiBold, Bold = QFont::Bold, Black = QFont::Black }; enum Capitalization { MixedCase = QFont::MixedCase, AllUppercase = QFont::AllUppercase, AllLowercase = QFont::AllLowercase, SmallCaps = QFont::SmallCaps, Capitalize = QFont::Capitalize }; <API key>(QObject *parent = 0); virtual void read(QObject *, int); virtual void write(QObject *, int, <API key>::WriteFlags); virtual QVariant value(); virtual void setValue(QVariant value); QString family() const; void setFamily(const QString &); bool bold() const; void setBold(bool b); FontWeight weight() const; void setWeight(FontWeight); bool italic() const; void setItalic(bool b); bool underline() const; void setUnderline(bool b); bool overline() const; void setOverline(bool b); bool strikeout() const; void setStrikeout(bool b); qreal pointSize() const; void setPointSize(qreal size); int pixelSize() const; void setPixelSize(int size); Capitalization capitalization() const; void setCapitalization(Capitalization); qreal letterSpacing() const; void setLetterSpacing(qreal spacing); qreal wordSpacing() const; void setWordSpacing(qreal spacing); private: QFont font; bool pixelSizeSet; bool pointSizeSet; mutable <API key><int> dpi; }; QT_END_NAMESPACE #endif // <API key>
// GRINS - General Reacting Incompressible Navier-Stokes // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // This class #include "grins/assembly_context.h" #include "grins/<API key>.h" #include "grins/<API key>.h" // libMesh #include "libmesh/quadrature.h" namespace GRINS { template<class K> <API key><K>::<API key>( const std::string& physics_name, const GetPot& input ) : <API key><K>(physics_name,input) { return; } template<class K> <API key><K>::~<API key>() { return; } template<class K> void <API key><K>::<API key>( bool compute_jacobian, AssemblyContext& context, CachedValues& /*cache*/ ) { #ifdef <API key> this->_timer->BeginTimer("<API key>::<API key>"); #endif // The number of local degrees of freedom in each variable. const unsigned int n_T_dofs = context.get_dof_indices(this->_temp_vars.T_var()).size(); const unsigned int n_u_dofs = context.get_dof_indices(this->_flow_vars.u_var()).size(); // Element Jacobian * quadrature weights for interior integration. const std::vector<libMesh::Real> &JxW = context.get_element_fe(this->_temp_vars.T_var())->get_JxW(); const std::vector<std::vector<libMesh::Real> >& u_phi = context.get_element_fe(this->_flow_vars.u_var())->get_phi(); const std::vector<std::vector<libMesh::Real> >& T_phi = context.get_element_fe(this->_temp_vars.T_var())->get_phi(); const std::vector<std::vector<libMesh::RealGradient> >& T_gradphi = context.get_element_fe(this->_temp_vars.T_var())->get_dphi(); const std::vector<std::vector<libMesh::RealTensor> >& T_hessphi = context.get_element_fe(this->_temp_vars.T_var())->get_d2phi(); /* const unsigned int n_u_dofs = context.get_dof_indices(this->_flow_vars.u_var()).size(); const std::vector<std::vector<libMesh::Real> >& u_phi = context.get_element_fe(this->_flow_vars.u_var())->get_phi(); libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(this->_flow_vars.u_var()); // R_{p} libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(this->_flow_vars.v_var()); // R_{p} libMesh::DenseSubVector<libMesh::Number> *Fw = NULL; if(this->_dim == 3) { Fw = &context.get_elem_residual(this->_flow_vars.w_var()); // R_{w} } */ libMesh::DenseSubVector<libMesh::Number> &FT = context.get_elem_residual(this->_temp_vars.T_var()); libMesh::DenseSubMatrix<libMesh::Number> &KTT = context.get_elem_jacobian(this->_temp_vars.T_var(), this->_temp_vars.T_var()); // J_{TT} libMesh::DenseSubMatrix<libMesh::Number> &KTu = context.get_elem_jacobian(this->_temp_vars.T_var(), this->_flow_vars.u_var()); // J_{Tu} libMesh::DenseSubMatrix<libMesh::Number> &KTv = context.get_elem_jacobian(this->_temp_vars.T_var(), this->_flow_vars.v_var()); // J_{Tv} libMesh::DenseSubMatrix<libMesh::Number> *KTw = NULL; if(this->_dim == 3) { KTw = &context.get_elem_jacobian (this->_temp_vars.T_var(), this->_flow_vars.w_var()); // J_{Tw} } unsigned int n_qpoints = context.get_element_qrule().n_points(); for (unsigned int qp=0; qp != n_qpoints; qp++) { libMesh::FEBase* fe = context.get_element_fe(this->_temp_vars.T_var()); libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp ); libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp ); libMesh::RealGradient U( context.interior_value( this->_flow_vars.u_var(), qp ), context.interior_value( this->_flow_vars.v_var(), qp ) ); if( this->_dim == 3 ) { U(2) = context.interior_value( this->_flow_vars.w_var(), qp ); } //libMesh::RealGradient grad_T = context.interior_gradient( this->_temp_vars.T_var(), qp ); libMesh::Real tau_E, RE_s; libMesh::Real d_tau_E_dT_rho, d_RE_s_dT; libMesh::Gradient d_tau_E_dU, d_RE_s_dgradT, d_RE_s_dU; libMesh::Tensor d_RE_s_dhessT; // Compute the conductivity at this qp libMesh::Real _k_qp = this->_k(context, qp); if (compute_jacobian) { this->_stab_helper.<API key> ( context, G, this->_rho, this->_Cp, _k_qp, U, tau_E, d_tau_E_dT_rho, d_tau_E_dU, this->_is_steady ); this->_stab_helper.<API key> ( context, qp, this->_rho, this->_Cp, _k_qp, RE_s, d_RE_s_dT, d_RE_s_dgradT, d_RE_s_dhessT, d_RE_s_dU ); } else { tau_E = this->_stab_helper.compute_tau_energy ( context, G, this->_rho, this->_Cp, _k_qp, U, this->_is_steady ); RE_s = this->_stab_helper.<API key> ( context, qp, this->_rho, this->_Cp, _k_qp ); } /* for (unsigned int i=0; i != n_u_dofs; i++) { Fu(i) += -tau_E*RE_s*this->_rho*this->_Cp*u_phi[i][qp]*grad_T(0)*JxW[qp]; Fv(i) += -tau_E*RE_s*this->_rho*this->_Cp*u_phi[i][qp]*grad_T(1)*JxW[qp]; if( this->_dim == 3 ) { (*Fw)(i) += -tau_E*RE_s*this->_rho*this->_Cp*u_phi[i][qp]*grad_T(2)*JxW[qp]; } } */ for (unsigned int i=0; i != n_T_dofs; i++) { FT(i) += -tau_E*RE_s*( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*JxW[qp]; if (compute_jacobian) { for (unsigned int j=0; j != n_T_dofs; ++j) { KTT(i,j) += -tau_E* (d_RE_s_dT*T_phi[j][qp] + d_RE_s_dgradT*T_gradphi[j][qp] + d_RE_s_dhessT.contract(T_hessphi[j][qp]) ) * ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*JxW[qp] * context.<API key>(); } for (unsigned int j=0; j != n_u_dofs; ++j) { KTu(i,j) += -tau_E*RE_s* ( this->_rho*this->_Cp*u_phi[j][qp]*T_gradphi[i][qp](0) )*JxW[qp] * context.<API key>(); KTu(i,j) += -(tau_E*d_RE_s_dU(0)+d_tau_E_dU(0)*RE_s)*u_phi[j][qp]* ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*JxW[qp] * context.<API key>(); KTv(i,j) += -tau_E*RE_s* ( this->_rho*this->_Cp*u_phi[j][qp]*T_gradphi[i][qp](1) )*JxW[qp] * context.<API key>(); KTv(i,j) += -(tau_E*d_RE_s_dU(1)+d_tau_E_dU(1)*RE_s)*u_phi[j][qp]* ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*JxW[qp] * context.<API key>(); } if(this->_dim == 3) { for (unsigned int j=0; j != n_u_dofs; ++j) { (*KTw)(i,j) += -tau_E*RE_s* ( this->_rho*this->_Cp*u_phi[j][qp]*T_gradphi[i][qp](2) )*JxW[qp] * context.<API key>(); (*KTw)(i,j) += -(tau_E*d_RE_s_dU(2)+d_tau_E_dU(2)*RE_s)*u_phi[j][qp]* ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*JxW[qp] * context.<API key>(); } } } } } #ifdef <API key> this->_timer->EndTimer("<API key>::<API key>"); #endif return; } template<class K> void <API key><K>::mass_residual( bool compute_jacobian, AssemblyContext& context, CachedValues& /*cache*/ ) { #ifdef <API key> this->_timer->BeginTimer("<API key>::mass_residual"); #endif // The number of local degrees of freedom in each variable. const unsigned int n_T_dofs = context.get_dof_indices(this->_temp_vars.T_var()).size(); const unsigned int n_u_dofs = context.get_dof_indices(this->_flow_vars.u_var()).size(); // Element Jacobian * quadrature weights for interior integration. const std::vector<libMesh::Real> &JxW = context.get_element_fe(this->_temp_vars.T_var())->get_JxW(); const std::vector<std::vector<libMesh::Real> >& u_phi = context.get_element_fe(this->_flow_vars.u_var())->get_phi(); const std::vector<std::vector<libMesh::Real> >& T_phi = context.get_element_fe(this->_temp_vars.T_var())->get_phi(); const std::vector<std::vector<libMesh::RealGradient> >& T_gradphi = context.get_element_fe(this->_temp_vars.T_var())->get_dphi(); const std::vector<std::vector<libMesh::RealTensor> >& T_hessphi = context.get_element_fe(this->_temp_vars.T_var())->get_d2phi(); /* const unsigned int n_u_dofs = context.get_dof_indices(this->_flow_vars.u_var()).size(); const std::vector<std::vector<libMesh::Real> >& u_phi = context.get_element_fe(this->_flow_vars.u_var())->get_phi(); libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(this->_flow_vars.u_var()); // R_{p} libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(this->_flow_vars.v_var()); // R_{p} libMesh::DenseSubVector<libMesh::Number> *Fw = NULL; if(this->_dim == 3) { Fw = &context.get_elem_residual(this->_flow_vars.w_var()); // R_{w} } */ libMesh::DenseSubVector<libMesh::Number> &FT = context.get_elem_residual(this->_temp_vars.T_var()); libMesh::DenseSubMatrix<libMesh::Number> &KTT = context.get_elem_jacobian(this->_temp_vars.T_var(), this->_temp_vars.T_var()); // J_{TT} libMesh::DenseSubMatrix<libMesh::Number> &KTu = context.get_elem_jacobian(this->_temp_vars.T_var(), this->_flow_vars.u_var()); // J_{Tu} libMesh::DenseSubMatrix<libMesh::Number> &KTv = context.get_elem_jacobian(this->_temp_vars.T_var(), this->_flow_vars.v_var()); // J_{Tv} libMesh::DenseSubMatrix<libMesh::Number> *KTw = NULL; if(this->_dim == 3) { KTw = &context.get_elem_jacobian (this->_temp_vars.T_var(), this->_flow_vars.w_var()); // J_{Tw} } unsigned int n_qpoints = context.get_element_qrule().n_points(); for (unsigned int qp=0; qp != n_qpoints; qp++) { libMesh::FEBase* fe = context.get_element_fe(this->_temp_vars.T_var()); libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp ); libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp ); libMesh::RealGradient U( context.<API key>( this->_flow_vars.u_var(), qp ), context.<API key>( this->_flow_vars.v_var(), qp ) ); if( this->_dim == 3 ) U(2) = context.<API key>( this->_flow_vars.w_var(), qp ); //libMesh::RealGradient grad_T = context.<API key>( this->_temp_vars.T_var(), qp ); libMesh::Real tau_E, RE_t; libMesh::Real d_tau_E_d_rho, d_RE_t_dT; libMesh::Gradient d_tau_E_dU; // Compute the conductivity at this qp libMesh::Real _k_qp = this->_k(context, qp); if (compute_jacobian) { this->_stab_helper.<API key> ( context, G, this->_rho, this->_Cp, _k_qp, U, tau_E, d_tau_E_d_rho, d_tau_E_dU, false ); this->_stab_helper.<API key> ( context, qp, this->_rho, this->_Cp, RE_t, d_RE_t_dT ); } else { tau_E = this->_stab_helper.compute_tau_energy ( context, G, this->_rho, this->_Cp, _k_qp, U, false ); RE_t = this->_stab_helper.<API key> ( context, qp, this->_rho, this->_Cp ); } /* for (unsigned int i=0; i != n_u_dofs; i++) { Fu(i) += -tau_E*RE_t*this->_rho*this->_Cp*u_phi[i][qp]*grad_T(0)*JxW[qp]; Fv(i) += -tau_E*RE_t*this->_rho*this->_Cp*u_phi[i][qp]*grad_T(1)*JxW[qp]; if( this->_dim == 3 ) { (*Fw)(i) += -tau_E*RE_t*this->_rho*this->_Cp*u_phi[i][qp]*grad_T(2)*JxW[qp]; } } */ for (unsigned int i=0; i != n_T_dofs; i++) { FT(i) -= tau_E*RE_t*( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*JxW[qp]; if (compute_jacobian) { const libMesh::Real fixed_deriv = context.<API key>(); for (unsigned int j=0; j != n_T_dofs; ++j) { KTT(i,j) -= (tau_E*d_RE_t_dT)*T_phi[j][qp]* ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*JxW[qp]; } for (unsigned int j=0; j != n_u_dofs; ++j) { KTu(i,j) -= d_tau_E_dU(0)*u_phi[j][qp]*RE_t* ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*fixed_deriv*JxW[qp]; KTu(i,j) -= tau_E*RE_t* ( this->_rho*this->_Cp*u_phi[j][qp]*T_gradphi[i][qp](0)*fixed_deriv )*JxW[qp]; KTv(i,j) -= d_tau_E_dU(1)*u_phi[j][qp]*RE_t* ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*fixed_deriv*JxW[qp]; KTv(i,j) -= tau_E*RE_t* ( this->_rho*this->_Cp*u_phi[j][qp]*T_gradphi[i][qp](1)*fixed_deriv )*JxW[qp]; } if(this->_dim == 3) { for (unsigned int j=0; j != n_u_dofs; ++j) { (*KTw)(i,j) -= d_tau_E_dU(2)*u_phi[j][qp]*RE_t* ( this->_rho*this->_Cp*U*T_gradphi[i][qp] + _k_qp*(T_hessphi[i][qp](0,0) + T_hessphi[i][qp](1,1) + T_hessphi[i][qp](2,2)) )*fixed_deriv*JxW[qp]; (*KTw)(i,j) -= tau_E*RE_t* ( this->_rho*this->_Cp*u_phi[j][qp]*T_gradphi[i][qp](2)*fixed_deriv )*JxW[qp]; } } } } } #ifdef <API key> this->_timer->EndTimer("<API key>::mass_residual"); #endif return; } } // namespace GRINS // Instantiate <API key>(<API key>);
#ifdef __cplusplus extern "C" { #endif /* variable int packing */ unsigned char *vint_pack(unsigned char *dst, int i); const unsigned char *vint_unpack(const unsigned char *src, int *inout); long intpack_compress(const void *src, int size, void *dst); long intpack_decompress(const void *src, int size, void *dst); /* zerobit packing */ long zerobit_compress(const void *src, int size, void *dst); long zerobit_decompress(const void *src, int size, void *dst); #ifdef __cplusplus } #endif
struct ADC_SC1 { UNION_STRUCT_START(32); enum ADC_ADCH { ADC_ADCH_TEMP = 0b11010, ADC_ADCH_BANDGAP = 0b11011, ADC_ADCH_VREFSH = 0b11101, ADC_ADCH_VREFSL = 0b11110, ADC_ADCH_DISABLED = 0b11111 } adch : 5; uint32_t diff : 1; uint32_t aien : 1; uint32_t coco : 1; uint32_t _rsvd0 : 24; UNION_STRUCT_END; }; struct ADC { struct ADC_SC1 sc1a; struct ADC_SC1 sc1b; struct ADC_CFG1 { UNION_STRUCT_START(32); enum { ADC_CLK_BUS = 0b00, ADC_CLK_BUS_HALF = 0b01, ADC_CLK_ALTCLK = 0b10, ADC_CLK_ADACK = 0b11 } adiclk : 2; enum { ADC_BIT_8 = 0b00, ADC_BIT_12 = 0b01, ADC_BIT_10 = 0b10, ADC_BIT_16 = 0b11 } mode : 2; uint32_t adlsmp : 1; enum { ADC_DIV_1 = 0b00, ADC_DIV_2 = 0b01, ADC_DIV_4 = 0b10, ADC_DIV_8 = 0b11 } adiv : 2; uint32_t adlpc : 1; uint32_t _rsvd0 : 24; UNION_STRUCT_END; } cfg1; struct ADC_CFG2 { UNION_STRUCT_START(32); enum { ADC_SAMPLE_CLKS_24 = 0b00, ADC_SAMPLE_CLKS_16 = 0b01, ADC_SAMPLE_CLKS_10 = 0b10, ADC_SAMPLE_CLKS_6 = 0b11 } adlsts : 2; uint32_t adhsc : 1; uint32_t adacken : 1; uint32_t muxsel : 1; uint32_t _rsvd0 : 27; UNION_STRUCT_END; } cfg2; uint32_t ra; uint32_t rb; uint32_t cv1; uint32_t cv2; struct ADC_SC2 { UNION_STRUCT_START(32); enum { ADC_REF_DEFAULT = 0b00, ADC_REF_ALTERNATE = 0b01 } refsel : 2; uint32_t dmaen : 1; uint32_t acren : 1; uint32_t acfgt : 1; uint32_t acfe : 1; uint32_t adtrg : 1; uint32_t adact : 1; uint32_t _rsvd0 : 24; UNION_STRUCT_END; } sc2; struct ADC_SC3 { UNION_STRUCT_START(32); enum { ADC_AVG_4 = 0b00, ADC_AVG_8 = 0b01, ADC_AVG_16 = 0b10, ADC_AVG_32 = 0b11 } avgs : 2; uint32_t avge : 1; uint32_t adco : 1; uint32_t _rsvd0 : 2; uint32_t calf : 1; uint32_t cal : 1; uint32_t _rsvd1 : 24; UNION_STRUCT_END; } sc3; uint32_t ofs; uint32_t pg; uint32_t mg; uint32_t clp[7]; uint32_t _pad0; uint32_t clm[7]; }; CTASSERT_SIZE_BYTE(struct ADC, 0x6c+4); extern volatile struct ADC ADC0;
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_26) on Wed Nov 10 08:21:33 BRST 2010 --> <TITLE> PendingReading (NeoDatis ODB) </TITLE> <META NAME="keywords" CONTENT="org.neodatis.odb.impl.core.layers.layer3.engine.PendingReading class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="PendingReading (NeoDatis ODB)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/ObjectWriterNew.html" title="class in org.neodatis.odb.impl.core.layers.layer3.engine"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/<API key>.html" title="class in org.neodatis.odb.impl.core.layers.layer3.engine"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?org/neodatis/odb/impl/core/layers/layer3/engine/PendingReading.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PendingReading.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> <FONT SIZE="-1"> org.neodatis.odb.impl.core.layers.layer3.engine</FONT> <BR> Class PendingReading</H2> <PRE> java.lang.Object <IMG SRC="../../../../../../../../resources/inherit.gif" ALT="extended by "><B>org.neodatis.odb.impl.core.layers.layer3.engine.PendingReading</B> </PRE> <HR> <DL> <DT><PRE>public class <B>PendingReading</B><DT>extends java.lang.Object</DL> </PRE> <P> <HR> <P> <A NAME="constructor_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/PendingReading.html#PendingReading(int, org.neodatis.odb.core.layers.layer2.meta.ClassInfo, org.neodatis.odb.OID)">PendingReading</A></B>(int&nbsp;id, <A HREF="../../../../../../../../org/neodatis/odb/core/layers/layer2/meta/ClassInfo.html" title="class in org.neodatis.odb.core.layers.layer2.meta">ClassInfo</A>&nbsp;ci, <A HREF="../../../../../../../../org/neodatis/odb/OID.html" title="interface in org.neodatis.odb">OID</A>&nbsp;attributeOID)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <A NAME="method_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../../org/neodatis/odb/OID.html" title="interface in org.neodatis.odb">OID</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/PendingReading.html#getAttributeOID()">getAttributeOID</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../../org/neodatis/odb/core/layers/layer2/meta/ClassInfo.html" title="class in org.neodatis.odb.core.layers.layer2.meta">ClassInfo</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/PendingReading.html#getCi()">getCi</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/PendingReading.html#getId()">getId</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="<API key>.lang.Object"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="<API key>"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <A NAME="constructor_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="PendingReading(int, org.neodatis.odb.core.layers.layer2.meta.ClassInfo, org.neodatis.odb.OID)"></A><H3> PendingReading</H3> <PRE> public <B>PendingReading</B>(int&nbsp;id, <A HREF="../../../../../../../../org/neodatis/odb/core/layers/layer2/meta/ClassInfo.html" title="class in org.neodatis.odb.core.layers.layer2.meta">ClassInfo</A>&nbsp;ci, <A HREF="../../../../../../../../org/neodatis/odb/OID.html" title="interface in org.neodatis.odb">OID</A>&nbsp;attributeOID)</PRE> <DL> </DL> <A NAME="method_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getId()"></A><H3> getId</H3> <PRE> public int <B>getId</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getCi()"></A><H3> getCi</H3> <PRE> public <A HREF="../../../../../../../../org/neodatis/odb/core/layers/layer2/meta/ClassInfo.html" title="class in org.neodatis.odb.core.layers.layer2.meta">ClassInfo</A> <B>getCi</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getAttributeOID()"></A><H3> getAttributeOID</H3> <PRE> public <A HREF="../../../../../../../../org/neodatis/odb/OID.html" title="interface in org.neodatis.odb">OID</A> <B>getAttributeOID</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/ObjectWriterNew.html" title="class in org.neodatis.odb.impl.core.layers.layer3.engine"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../org/neodatis/odb/impl/core/layers/layer3/engine/<API key>.html" title="class in org.neodatis.odb.impl.core.layers.layer3.engine"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?org/neodatis/odb/impl/core/layers/layer3/engine/PendingReading.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PendingReading.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; namespace VrPlayer.Views.Dialogs { public partial class ProcessInputDialog : Window { public ProcessInputDialog() { InitializeComponent(); DataContext = this; } public Process Process { get { return (Process)ResponseComboBox.SelectedValue; } set { ResponseComboBox.SelectedValue = value; } } private void OnOkButtonClick(object sender, RoutedEventArgs e) { DialogResult = true; } private void OnCancelButtonClick(object sender, RoutedEventArgs e) { Close(); } private void <API key>(object sender, RoutedEventArgs e) { ResponseComboBox.Focus(); } public IEnumerable<Process> Processes { get { var processlist = Process.GetProcesses(); return processlist.Where(process => !String.IsNullOrEmpty(process.MainWindowTitle)).ToList(); } } } }
# -*- coding: utf-8 -*- ''' Test case for signal to signal connections.''' import unittest from PySide2.QtCore import * def cute_slot(): pass class <API key>(unittest.TestCase): '''Test case for signal to signal connections''' def setUp(self): #Set up the basic resources needed self.sender = QObject() self.forwarder = QObject() self.args = None self.called = False def tearDown(self): #Delete used resources try: del self.sender except: pass try: del self.forwarder except: pass del self.args def callback_noargs(self): #Default callback without arguments self.called = True def callback_args(self, *args): #Default callback with arguments if args == self.args: self.called = True else: raise TypeError("Invalid arguments") def callback_qobject(self, *args): #Default callback for QObject as argument if args[0].objectName() == self.args[0]: self.called = True else: raise TypeError("Invalid arguments") def <API key>(self): QObject.connect(self.sender, SIGNAL("destroyed()"), self.forwarder, SIGNAL("forward()")) QObject.connect(self.forwarder, SIGNAL("forward()"), self.callback_noargs) del self.sender self.assert_(self.called) def <API key>(self): QObject.connect(self.sender, SIGNAL("mysignal(int)"), self.forwarder, SIGNAL("mysignal(int)")) QObject.connect(self.forwarder, SIGNAL("mysignal(int)"), self.callback_args) self.args = (19,) self.sender.emit(SIGNAL('mysignal(int)'), *self.args) self.assert_(self.called) def <API key>(self): QObject.connect(self.sender, SIGNAL("mysignal(int,int)"), self.forwarder, SIGNAL("mysignal(int,int)")) QObject.connect(self.forwarder, SIGNAL("mysignal(int,int)"), self.callback_args) self.args = (23, 29) self.sender.emit(SIGNAL('mysignal(int,int)'), *self.args) self.assert_(self.called) def <API key>(self): QObject.connect(self.sender, SIGNAL("mysignal(QString)"), self.forwarder, SIGNAL("mysignal(QString)")) QObject.connect(self.forwarder, SIGNAL("mysignal(QString)"), self.callback_args) self.args = ('myargument',) self.sender.emit(SIGNAL('mysignal(QString)'), *self.args) self.assert_(self.called) def <API key>(self): QObject.connect(self.sender, SIGNAL('destroyed(QObject*)'), self.forwarder, SIGNAL('forward(QObject*)')) QObject.connect(self.forwarder, SIGNAL('forward(QObject*)'), self.callback_qobject) obj_name = 'sender' self.sender.setObjectName(obj_name) self.args = (obj_name, ) del self.sender self.assert_(self.called) if __name__ == '__main__': unittest.main()
package org.herac.tuxguitar.android.view.tablature; import org.herac.tuxguitar.android.TuxGuitar; import org.herac.tuxguitar.android.graphics.<API key>; import org.herac.tuxguitar.document.TGDocumentManager; import org.herac.tuxguitar.editor.TGEditorManager; import org.herac.tuxguitar.graphics.TGRectangle; import org.herac.tuxguitar.graphics.TGResourceFactory; import org.herac.tuxguitar.graphics.control.TGController; import org.herac.tuxguitar.graphics.control.TGLayout; import org.herac.tuxguitar.graphics.control.TGLayoutStyles; import org.herac.tuxguitar.graphics.control.TGLayoutVertical; import org.herac.tuxguitar.graphics.control.TGResourceBuffer; import org.herac.tuxguitar.player.base.MidiPlayer; import org.herac.tuxguitar.player.base.MidiPlayerMode; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGBeat; import org.herac.tuxguitar.song.models.TGDuration; import org.herac.tuxguitar.song.models.TGMeasure; import org.herac.tuxguitar.song.models.TGMeasureHeader; import org.herac.tuxguitar.song.models.TGSong; import org.herac.tuxguitar.util.TGContext; import org.herac.tuxguitar.util.TGSynchronizer; import org.herac.tuxguitar.util.singleton.TGSingletonFactory; import org.herac.tuxguitar.util.singleton.TGSingletonUtil; public class <API key> implements TGController { public static final float EMPTY_SCALE = 0f; private TGContext context; private TGResourceFactory resourceFactory; private TGLayout layout; private TGSongViewStyles songStyles; private <API key> bufferController; private <API key> layoutPainter; private <API key> axisSelector; private TGCaret caret; private TGScroll scroll; private TGSongView songView; private float scalePreview; public <API key>(TGContext context) { this.context = context; this.songStyles = new TGSongViewStyles(); this.resourceFactory = new <API key>(); this.bufferController = new <API key>(this); this.layoutPainter = new <API key>(this); this.layout = new TGLayoutVertical(this, TGLayout.DISPLAY_TABLATURE | TGLayout.DISPLAY_SCORE | TGLayout.DISPLAY_COMPACT); this.caret = new TGCaret(this); this.scroll = new TGScroll(); this.axisSelector = new <API key>(this); this.resetCaret(); this.resetScroll(); this.updateTablature(); this.appendListeners(); } public void appendListeners() { <API key> listener = new <API key>(this); TuxGuitar.getInstance(this.context).getEditorManager().addRedrawListener(listener); TuxGuitar.getInstance(this.context).getEditorManager().addUpdateListener(listener); } public void resetCaret() { this.getCaret().update(1, TGDuration.QUARTER_TIME, 1); } public void resetScroll() { this.getScroll().getX().reset(false, 0, 0, 0); this.getScroll().getY().reset(true, 0, 0, 0); } public void <API key>() { TGSynchronizer.getInstance(this.context).executeLater(new Runnable() { public void run() { getResourceBuffer().<API key>(); } }); } public void updateTablature() { this.getLayout().updateSong(); this.getCaret().update(); this.<API key>(); } public void updateMeasure(int number) { this.getLayout().updateMeasureNumber(number); this.getCaret().update(); this.<API key>(); } public void updateScroll(TGRectangle bounds) { this.getScroll().getX().setMaximum(Math.max((this.getLayout().getWidth() - bounds.getWidth()), 0)); this.getScroll().getY().setMaximum(Math.max((this.getLayout().getHeight() - bounds.getHeight()), 0)); } public void updateSelection() { this.bufferController.updateSelection(); this.layoutPainter.refreshBuffer(); } public void configureStyles(TGLayoutStyles styles) { this.songStyles.configureStyles(styles); } public void scale(float scale) { this.getLayout().loadStyles(scale); this.setScalePreview(EMPTY_SCALE); } public void redraw() { if( this.getSongView() != null ) { this.getSongView().redraw(); } } public void redrawPlayingMode() { if( this.getSongView() != null && !this.getSongView().isPainting() && MidiPlayer.getInstance(this.context).isRunning()) { this.redraw(); } } public TGSongManager getSongManager() { return TGDocumentManager.getInstance(getContext()).getSongManager(); } public TGSong getSong() { return TGDocumentManager.getInstance(getContext()).getSong(); } public TGResourceFactory getResourceFactory() { return this.resourceFactory; } public TGResourceBuffer getResourceBuffer() { return this.bufferController.getResourceBuffer(); } public <API key> getLayoutPainter() { return layoutPainter; } public TGLayout getLayout() { return layout; } public TGCaret getCaret() { return caret; } public TGContext getContext() { return this.context; } public TGScroll getScroll() { return scroll; } public <API key> getAxisSelector() { return axisSelector; } public TGSongView getSongView() { return songView; } public void setSongView(TGSongView tgSongView) { this.songView = tgSongView; } public float getScalePreview() { return scalePreview; } public void setScalePreview(float scalePreview) { this.scalePreview = scalePreview; } public int getTrackSelection() { if ((getLayout().getStyle() & TGLayout.DISPLAY_MULTITRACK) == 0) { return getCaret().getTrack().getNumber(); } return -1; } public boolean isRunning(TGBeat beat) { return (isRunning(beat.getMeasure()) && TuxGuitar.getInstance(this.context).getTransport().getCache().isPlaying(beat.getMeasure(), beat)); } public boolean isRunning(TGMeasure measure) { return (measure.getTrack().equals(getCaret().getTrack()) && TuxGuitar.getInstance(this.context).getTransport().getCache().isPlaying(measure)); } public boolean isLoopSHeader(TGMeasureHeader measureHeader) { MidiPlayerMode pm = TuxGuitar.getInstance(this.context).getPlayer().getMode(); return (pm.isLoop() && pm.getLoopSHeader() == measureHeader.getNumber()); } public boolean isLoopEHeader(TGMeasureHeader measureHeader) { MidiPlayerMode pm = TuxGuitar.getInstance(this.context).getPlayer().getMode(); return (pm.isLoop() && pm.getLoopEHeader() == measureHeader.getNumber()); } public boolean <API key>() { return (!TGEditorManager.getInstance(getContext()).isLocked() && !MidiPlayer.getInstance(getContext()).isRunning()); } public boolean <API key>() { return (!TGEditorManager.getInstance(getContext()).isLocked()); } public void dispose(){ this.getCaret().dispose(); this.getLayout().disposeLayout(); this.getResourceBuffer().disposeAllResources(); } public static <API key> getInstance(TGContext context) { return TGSingletonUtil.getInstance(context, <API key>.class.getName(), new TGSingletonFactory<<API key>>() { public <API key> createInstance(TGContext context) { return new <API key>(context); } }); } }
#include <config.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <directfb.h> #include <core/core.h> #include <core/coredefs.h> #include <core/coretypes.h> #include <core/surface.h> #include <core/gfxcard.h> #include <core/layers.h> #include <core/layers_internal.h> #include <core/layer_context.h> #include <core/layer_control.h> #include <core/layer_region.h> #include <core/state.h> #include <core/windows.h> #include <core/windows_internal.h> #include <core/windowstack.h> #include <core/wm.h> #include <core/CoreDFB.h> #include <core/CoreLayer.h> #include <core/CoreLayerContext.h> #include <core/CoreLayerRegion.h> #include <core/CoreWindowStack.h> #include <windows/idirectfbwindow.h> #include <gfx/convert.h> #include <direct/debug.h> #include <direct/interface.h> #include <direct/mem.h> #include <direct/messages.h> #include <display/<API key>.h> #include <display/idirectfbscreen.h> #include <display/idirectfbsurface.h> #include <display/<API key>.h> D_DEBUG_DOMAIN( Layer, "<API key>", "Display Layer Interface" ); /* * private data struct of IDirectFB */ typedef struct { int ref; /* reference counter */ <API key> desc; /* description of the layer's caps */ <API key> level; /* current cooperative level */ CoreScreen *screen; /* layer's screen */ CoreLayer *layer; /* core layer data */ CoreLayerContext *context; /* shared or exclusive context */ CoreLayerRegion *region; /* primary region of the context */ CoreWindowStack *stack; /* stack of shared context */ DFBBoolean switch_exclusive; /* switch to exclusive context after creation? */ CoreDFB *core; IDirectFB *idirectfb; } <API key>; static void <API key>( <API key> *thiz ) { <API key> *data = (<API key>*)thiz->priv; D_DEBUG_AT( Layer, "<API key>()\n" ); D_DEBUG_AT( Layer, " -> unref region...\n" ); <API key>( data->region ); D_DEBUG_AT( Layer, " -> unref context...\n" ); <API key>( data->context ); <API key>( thiz ); D_DEBUG_AT( Layer, " -> done.\n" ); } static DirectResult <API key>( <API key> *thiz ) { <API key>(<API key>) data->ref++; return DFB_OK; } static DirectResult <API key>( <API key> *thiz ) { <API key>(<API key>) if (--data->ref == 0) <API key>( thiz ); return DFB_OK; } static DFBResult <API key>( <API key> *thiz, DFBDisplayLayerID *id ) { <API key>(<API key>) if (!id) return DFB_INVARG; *id = <API key>( data->layer ); return DFB_OK; } static DFBResult <API key>( <API key> *thiz, <API key> *desc ) { <API key>(<API key>) if (!desc) return DFB_INVARG; *desc = data->desc; return DFB_OK; } static DFBResult <API key>( <API key> *thiz, IDirectFBSurface **interface ) { DFBResult ret; CoreLayerRegion *region; IDirectFBSurface *surface; <API key>(<API key>) if (!interface) return DFB_INVARG; if (data->level == DLSCL_SHARED) { D_WARN( "letting unprivileged <API key>::GetSurface() " "call pass until cooperative level handling is finished" ); } ret = <API key>( data->context, true, &region ); if (ret) return ret; <API key>( surface, IDirectFBSurface ); ret = <API key>( surface, NULL, NULL, NULL, region, DSCAPS_NONE, data->core, data->idirectfb ); // Fix to only perform single buffered clearing using a background when // configured to do so AND the display layer region is frozen. Also // added support for this behavior when the cooperative level is // <API key>. if (region->config.buffermode == DLBM_FRONTONLY && data->level != DLSCL_SHARED && D_FLAGS_IS_SET( region->state, CLRSF_FROZEN )) { // If a window stack is available, give it the opportunity to // render the background (optionally based on configuration) and // flip the display layer so it is visible. Otherwise, just // directly flip the display layer and make it visible. D_ASSERT( region->context ); if (region->context->stack) { <API key>( region->context->stack ); } else { <API key>( region, NULL, DSFLIP_NONE ); } } *interface = ret ? NULL : surface; <API key>( region ); return ret; } static DFBResult <API key>( <API key> *thiz, IDirectFBScreen **interface ) { DFBResult ret; IDirectFBScreen *screen; <API key>(<API key>) if (!interface) return DFB_INVARG; <API key>( screen, IDirectFBScreen ); ret = <API key>( screen, data->screen ); *interface = ret ? NULL : screen; return ret; } static DFBResult <API key>( <API key> *thiz, <API key> level ) { DFBResult ret; CoreLayerContext *context; CoreLayerRegion *region; <API key>(<API key>) if (data->level == level) return DFB_OK; switch (level) { case DLSCL_SHARED: case <API key>: if (data->level == DLSCL_EXCLUSIVE) { ret = <API key>( data->layer, false, &context ); if (ret) return ret; ret = <API key>( context, true, &region ); if (ret) { <API key>( context ); return ret; } <API key>( data->region ); <API key>( data->context ); data->context = context; data->region = region; data->stack = <API key>( data->context ); } break; case DLSCL_EXCLUSIVE: ret = <API key>( data->layer, &context ); if (ret) return ret; if (data->switch_exclusive) { ret = <API key>( data->layer, context ); if (ret) { <API key>( context ); return ret; } } ret = <API key>( context, true, &region ); if (ret) { <API key>( context ); return ret; } <API key>( data->region ); <API key>( data->context ); data->context = context; data->region = region; data->stack = <API key>( data->context ); break; default: return DFB_INVARG; } data->level = level; return DFB_OK; } static DFBResult <API key>( <API key> *thiz, u8 opacity ) { <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; return <API key>( data->context, opacity ); } static DFBResult <API key>( <API key> *thiz, int *field ) { <API key>(<API key>) return <API key>( data->layer, field ); } static DFBResult <API key>( <API key> *thiz, int field ) { <API key>(<API key>) if (data->level != DLSCL_EXCLUSIVE) return DFB_ACCESSDENIED; return <API key>( data->context, field ); } static DFBResult <API key>( <API key> *thiz, const DFBRegion *regions, int num_regions, DFBBoolean positive ) { <API key>(<API key>) if (!regions || num_regions < 1) return DFB_INVARG; if (num_regions > data->desc.clip_regions) return DFB_UNSUPPORTED; if (data->level != DLSCL_EXCLUSIVE) return DFB_ACCESSDENIED; return <API key>( data->context, regions, num_regions, positive ); } static DFBResult <API key>( <API key> *thiz, int x, int y, int width, int height ) { DFBRectangle source = { x, y, width, height }; <API key>(<API key>) if (x < 0 || y < 0 || width <= 0 || height <= 0) return DFB_INVARG; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; return <API key>( data->context, &source ); } static DFBResult <API key>( <API key> *thiz, float x, float y, float width, float height ) { DFBLocation location = { x, y, width, height }; <API key>(<API key>) if (! D_FLAGS_IS_SET( data->desc.caps, <API key> )) return DFB_UNSUPPORTED; if (width <= 0 || height <= 0) return DFB_INVARG; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; return <API key>( data->context, &location ); } static DFBResult <API key>( <API key> *thiz, int x, int y ) { DFBPoint position; <API key>(<API key>) if (! D_FLAGS_IS_SET( data->desc.caps, <API key> )) return DFB_UNSUPPORTED; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; position.x = x; position.y = y; return <API key>( data->context, &position ); } static DFBResult <API key>( <API key> *thiz, int x, int y, int width, int height ) { DFBRectangle rect = { x, y, width, height }; <API key>(<API key>) if (! D_FLAGS_IS_SET( data->desc.caps, <API key> )) return DFB_UNSUPPORTED; if (width <= 0 || height <= 0) return DFB_INVARG; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; return <API key>( data->context, &rect ); } static DFBResult <API key>( <API key> *thiz, u8 r, u8 g, u8 b ) { DFBColorKey key; <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; key.r = r; key.g = g; key.b = b; key.index = -1; return <API key>( data->context, &key ); } static DFBResult <API key>( <API key> *thiz, u8 r, u8 g, u8 b ) { DFBColorKey key; <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; key.r = r; key.g = g; key.b = b; key.index = -1; return <API key>( data->context, &key ); } static DFBResult <API key>( <API key> *thiz, int *level ) { DFBResult ret; int lvl; <API key>(<API key>) if (!level) return DFB_INVARG; ret = dfb_layer_get_level( data->layer, &lvl ); if (ret) return ret; *level = lvl; return DFB_OK; } static DFBResult <API key>( <API key> *thiz, int level ) { <API key>(<API key>) if (! D_FLAGS_IS_SET( data->desc.caps, DLCAPS_LEVELS )) return DFB_UNSUPPORTED; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; return CoreLayer_SetLevel( data->layer, level ); } static DFBResult <API key>( <API key> *thiz, <API key> *config ) { <API key>(<API key>) if (!config) return DFB_INVARG; return <API key>( data->context, config ); } static DFBResult <API key>( <API key> *thiz, const <API key> *config, <API key> *failed ) { <API key>(<API key>) if (!config) return DFB_INVARG; if (((config->flags & DLCONF_WIDTH) && (config->width < 0)) || ((config->flags & DLCONF_HEIGHT) && (config->height < 0))) return DFB_INVARG; return <API key>( data->context, config, failed ); } static DFBResult <API key>( <API key> *thiz, const <API key> *config ) { <API key>(<API key>) if (!config) return DFB_INVARG; if (((config->flags & DLCONF_WIDTH) && (config->width < 0)) || ((config->flags & DLCONF_HEIGHT) && (config->height < 0))) return DFB_INVARG; switch (data->level) { case DLSCL_EXCLUSIVE: case <API key>: return <API key>( data->context, config ); default: break; } return DFB_ACCESSDENIED; } static DFBResult <API key>( <API key> *thiz, <API key> background_mode ) { <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; switch (background_mode) { case DLBM_DONTCARE: case DLBM_COLOR: case DLBM_IMAGE: case DLBM_TILE: break; default: return DFB_INVARG; } if (!data->stack) return DFB_OK; return <API key>( data->stack, background_mode ); } static DFBResult <API key>( <API key> *thiz, IDirectFBSurface *surface ) { <API key> *surface_data; <API key>(<API key>) if (!surface) return DFB_INVARG; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; surface_data = (<API key>*)surface->priv; if (!surface_data) return DFB_DEAD; if (!surface_data->surface) return DFB_DESTROYED; if (!data->stack) return DFB_OK; <API key>( &surface_data->state_client ); return <API key>( data->stack, surface_data->surface ); } static DFBResult <API key>( <API key> *thiz, u8 r, u8 g, u8 b, u8 a ) { DFBColor color = { a: a, r: r, g: g, b: b }; <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; if (!data->stack) return DFB_OK; return <API key>( data->stack, &color ); } static DFBResult <API key>( <API key> *thiz, const <API key> *desc, IDirectFBWindow **window ) { CoreWindow *w; DFBResult ret; <API key> wd; <API key>(<API key>) memset( &wd, 0, sizeof(wd) ); wd.flags = DWDESC_WIDTH | DWDESC_HEIGHT | DWDESC_POSX | DWDESC_POSY | DWDESC_PIXELFORMAT | DWDESC_COLORSPACE | DWDESC_SURFACE_CAPS | DWDESC_CAPS; wd.width = (desc->flags & DWDESC_WIDTH) ? desc->width : 480; wd.height = (desc->flags & DWDESC_HEIGHT) ? desc->height : 300; wd.posx = (desc->flags & DWDESC_POSX) ? desc->posx : 100; wd.posy = (desc->flags & DWDESC_POSY) ? desc->posy : 100; D_DEBUG_AT( Layer, "CreateWindow() <- %d,%d - %dx%d )\n", wd.posx, wd.posy, wd.width, wd.height ); if (wd.width < 1 || wd.width > 4096 || wd.height < 1 || wd.height > 4096) return DFB_INVARG; if (desc->flags & DWDESC_CAPS) { if ((desc->caps & ~DWCAPS_ALL) || !window) return DFB_INVARG; wd.caps = desc->caps; } if (desc->flags & DWDESC_PIXELFORMAT) wd.pixelformat = desc->pixelformat; if (desc->flags & DWDESC_COLORSPACE) wd.colorspace = desc->colorspace; if (desc->flags & DWDESC_SURFACE_CAPS) wd.surface_caps = desc->surface_caps; if (desc->flags & DWDESC_PARENT) { wd.flags |= DWDESC_PARENT; wd.parent_id = desc->parent_id; } if (desc->flags & DWDESC_OPTIONS) { wd.flags |= DWDESC_OPTIONS; wd.options = desc->options; } if (desc->flags & DWDESC_STACKING) { wd.flags |= DWDESC_STACKING; wd.stacking = desc->stacking; } if (desc->flags & DWDESC_RESOURCE_ID) { wd.flags |= DWDESC_RESOURCE_ID; wd.resource_id = desc->resource_id; } if (desc->flags & DWDESC_TOPLEVEL_ID) { wd.flags |= DWDESC_TOPLEVEL_ID; wd.toplevel_id = desc->toplevel_id; } ret = <API key>( data->context, &wd, &w ); if (ret) return ret; <API key>( *window, IDirectFBWindow ); return <API key>( *window, w, data->layer, data->core, data->idirectfb, true ); } static DFBResult <API key>( <API key> *thiz, DFBWindowID id, IDirectFBWindow **window ) { DFBResult ret; CoreWindow *w; <API key>(<API key>) if (!window) return DFB_INVARG; /* <API key> won't ref it, so we don't unref it */ ret = <API key>( data->context, id, &w ); if (ret) return ret; <API key>( *window, IDirectFBWindow ); return <API key>( *window, w, data->layer, data->core, data->idirectfb, false ); } static DFBResult <API key>( <API key> *thiz, int enable ) { <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; if (!data->stack) return DFB_OK; return <API key>( data->stack, enable ); } static DFBResult <API key>( <API key> *thiz, int *x, int *y ) { DFBResult ret; DFBPoint point; <API key>(<API key>) if (!x && !y) return DFB_INVARG; if (!data->stack) return DFB_ACCESSDENIED; ret = <API key>( data->stack, &point ); if (ret) return ret; if (x) *x = point.x; if (y) *y = point.y; return ret; } static DFBResult <API key>( <API key> *thiz, int x, int y ) { DFBPoint point = { x, y }; <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; if (!data->stack) return DFB_OK; return <API key>( data->stack, &point ); } static DFBResult <API key>( <API key> *thiz, int numerator, int denominator, int threshold ) { <API key>(<API key>) if (numerator < 0 || denominator < 1 || threshold < 0) return DFB_INVARG; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; if (!data->stack) return DFB_OK; return <API key>( data->stack, numerator, denominator, threshold ); } static DFBResult <API key>( <API key> *thiz, IDirectFBSurface *shape, int hot_x, int hot_y ) { DFBPoint hotspot = { hot_x, hot_y }; <API key> *shape_data; <API key>(<API key>) if (!shape) return DFB_INVARG; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; if (!data->stack) return DFB_OK; shape_data = (<API key>*)shape->priv; if (hot_x < 0 || hot_y < 0 || hot_x >= shape_data->surface->config.size.w || hot_y >= shape_data->surface->config.size.h) return DFB_INVARG; return <API key>( data->stack, shape_data->surface, &hotspot ); } static DFBResult <API key>( <API key> *thiz, u8 opacity ) { <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; if (!data->stack) return DFB_OK; return <API key>( data->stack, opacity ); } static DFBResult <API key>( <API key> *thiz, DFBColorAdjustment *adj ) { <API key>(<API key>) if (!adj) return DFB_INVARG; return <API key>( data->context, adj ); } static DFBResult <API key>( <API key> *thiz, const DFBColorAdjustment *adj ) { <API key>(<API key>) if (!adj || (adj->flags & ~DCAF_ALL)) return DFB_INVARG; if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; if (!adj->flags) return DFB_OK; return <API key>( data->context, adj ); } static DFBResult <API key>( <API key> *thiz, bool follow_video, int z ) { <API key>(<API key>) if (!follow_video && (z < -DLSO_FIXED_LIMIT || z > DLSO_FIXED_LIMIT)) return DFB_INVARG; if (!(data->context->config.options & DLOP_LR_MONO) && !(data->context->config.options & DLOP_STEREO)) { return DFB_INVARG; } if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; return <API key>( data->context, follow_video, z ); } static DFBResult <API key>( <API key> *thiz, bool *follow_video, int *z ) { <API key>(<API key>) if (!(data->context->config.options & DLOP_LR_MONO) && !(data->context->config.options & DLOP_STEREO)) { return DFB_INVARG; } if (!z || !follow_video) return DFB_INVARG; return <API key>( data->context, follow_video, z ); } static DFBResult <API key>( <API key> *thiz ) { <API key>(<API key>) return CoreLayer_WaitVSync( data->layer ); } static DFBResult <API key>( <API key> *thiz, <API key> *ret_descriptions ) { int i; <API key>(<API key>) if (!ret_descriptions) return DFB_INVARG; if (! D_FLAGS_IS_SET( data->desc.caps, DLCAPS_SOURCES )) return DFB_UNSUPPORTED; for (i=0; i<data->desc.sources; i++) <API key>( data->layer, i, &ret_descriptions[i] ); return DFB_OK; } static DFBResult <API key>( <API key> *thiz, DFBBoolean exclusive ) { <API key>(<API key>) if (!exclusive && data->level == DLSCL_EXCLUSIVE) { DFBResult ret; CoreLayerContext *context; ret = <API key>( data->layer, false, &context ); if (ret) return ret; <API key>( data->layer, context ); <API key>( context ); } else <API key>( data->layer, data->context ); data->switch_exclusive = exclusive; return DFB_OK; } static DFBResult <API key>( <API key> *thiz, int rotation ) { <API key>(<API key>) if (data->level == DLSCL_SHARED) return DFB_ACCESSDENIED; return <API key>( data->context, rotation ); } static DFBResult <API key>( <API key> *thiz, int *ret_rotation ) { CoreLayerContext *context; <API key>(<API key>) if (!ret_rotation) return DFB_INVARG; context = data->context; D_MAGIC_ASSERT( context, CoreLayerContext ); /* Lock the context. */ // if (<API key>( context )) // return DFB_FUSION; *ret_rotation = context->rotation; /* Unlock the context. */ // <API key>( context ); return DFB_OK; } static DFBResult <API key>( <API key> *thiz, unsigned long resource_id, IDirectFBWindow **ret_window ) { DFBResult ret; CoreWindow *w; <API key>(<API key>) if (!ret_window) return DFB_INVARG; /* <API key> won't ref it, so we don't unref it */ ret = <API key>( data->context, resource_id, &w ); if (ret) return ret; <API key>( *ret_window, IDirectFBWindow ); return <API key>( *ret_window, w, data->layer, data->core, data->idirectfb, false ); } DFBResult <API key>( <API key> *thiz, CoreLayer *layer, CoreDFB *core, IDirectFB *idirectfb ) { DFBResult ret; CoreLayerContext *context; CoreLayerRegion *region; <API key>(thiz, <API key>) ret = <API key>( layer, true, &context ); if (ret) { <API key>( thiz ) return ret; } ret = <API key>( context, true, &region ); if (ret) { <API key>( context ); <API key>( thiz ) return ret; } data->ref = 1; data->core = core; data->idirectfb = idirectfb; data->screen = dfb_layer_screen( layer ); data->layer = layer; data->context = context; data->region = region; data->stack = <API key>( context ); data->switch_exclusive = DFB_TRUE; <API key>( data->layer, &data->desc ); thiz->AddRef = <API key>; thiz->Release = <API key>; thiz->GetID = <API key>; thiz->GetDescription = <API key>; thiz->GetSurface = <API key>; thiz->GetScreen = <API key>; thiz->SetCooperativeLevel = <API key>; thiz->SetOpacity = <API key>; thiz-><API key> = <API key>; thiz->SetSourceRectangle = <API key>; thiz->SetScreenLocation = <API key>; thiz->SetSrcColorKey = <API key>; thiz->SetDstColorKey = <API key>; thiz->GetLevel = <API key>; thiz->SetLevel = <API key>; thiz->GetConfiguration = <API key>; thiz->TestConfiguration = <API key>; thiz->SetConfiguration = <API key>; thiz->SetBackgroundMode = <API key>; thiz->SetBackgroundColor = <API key>; thiz->SetBackgroundImage = <API key>; thiz->GetColorAdjustment = <API key>; thiz->SetColorAdjustment = <API key>; thiz->CreateWindow = <API key>; thiz->GetWindow = <API key>; thiz->WarpCursor = <API key>; thiz-><API key> = <API key>; thiz->EnableCursor = <API key>; thiz->GetCursorPosition = <API key>; thiz->SetCursorShape = <API key>; thiz->SetCursorOpacity = <API key>; thiz->SetFieldParity = <API key>; thiz->SetClipRegions = <API key>; thiz->WaitForSync = <API key>; thiz-><API key> = <API key>; thiz->SetScreenPosition = <API key>; thiz->SetScreenRectangle = <API key>; thiz->SwitchContext = <API key>; thiz->SetRotation = <API key>; thiz->GetRotation = <API key>; thiz-><API key> = <API key>; thiz->SetStereoDepth = <API key>; thiz->GetStereoDepth = <API key>; return DFB_OK; }
#include <valgrind/xmlprotocol/frame.h> #include <valgrind/xmlprotocol/parser.h> #include <valgrind/xmlprotocol/stack.h> #include <valgrind/xmlprotocol/suppression.h> #include <projectexplorer/projectexplorer.h> #include <extensionsystem/pluginmanager.h> #include "parsertests.h" #include <QCoreApplication> #include <QDebug> #include <QFile> #include <QFileInfo> #include <QString> #include <QTest> #include <QTcpServer> #include <QTcpSocket> #include <QSignalSpy> #include <iostream> #include <QProcess> using namespace Valgrind; using namespace Valgrind::XmlProtocol; QT_BEGIN_NAMESPACE namespace QTest { template<> inline bool qCompare(int const &t1, MemcheckErrorKind const &t2, char const *actual, char const *expected, char const *file, int line) { return qCompare(t1, int(t2), actual, expected, file, line); } } // namespace QTest QT_END_NAMESPACE void dumpFrame(const Frame &f) { qDebug() << f.instructionPointer() << f.directory() << f.file() << f.functionName() << f.line() << f.object(); } void dumpError(const Error &e) { qDebug() << e.kind() << e.leakedBlocks() << e.leakedBytes() << e.what() << e.tid() << e.unique(); qDebug() << "stacks:" << e.stacks().size(); Q_FOREACH(const Stack& s, e.stacks()) { qDebug() << s.auxWhat() << s.directory() << s.file() << s.line() << s.helgrindThreadId(); qDebug() << "frames:"; Q_FOREACH(const Frame& f, s.frames()) { dumpFrame(f); } } } static QString <API key>() { return QLatin1String(VALGRIND_FAKE_PATH); } static QString dataFile(const QLatin1String &file) { return QLatin1String(<API key>) + QLatin1String("/") + file; } void ParserTests::initTestCase() { new ExtensionSystem::PluginManager; new ProjectExplorer::<API key>; m_server = new QTcpServer(this); QVERIFY(m_server->listen()); m_socket = 0; m_process = 0; } void ParserTests::initTest(const QLatin1String &testfile, const QStringList &otherArgs) { QVERIFY(!m_server-><API key>()); m_process = new QProcess(m_server); m_process-><API key>(QProcess::ForwardedChannels); const QString fakeValgrind = <API key>(); QFileInfo fileInfo(fakeValgrind); QVERIFY2(fileInfo.isExecutable(), qPrintable(fakeValgrind)); QVERIFY2(!fileInfo.isDir(), qPrintable(fakeValgrind)); m_process->start( fakeValgrind, QStringList() << QString::fromLatin1("--xml-socket=127.0.0.1:%1").arg(m_server->serverPort()) << QLatin1String("-i") << dataFile(testfile) << otherArgs ); QVERIFY(m_process->waitForStarted(5000)); QCOMPARE(m_process->state(), QProcess::Running); QVERIFY2(m_process->error() == QProcess::UnknownError, qPrintable(m_process->errorString())); QVERIFY(m_server-><API key>(5000)); m_socket = m_server-><API key>(); QVERIFY(m_socket); } void ParserTests::cleanup() { if (m_socket) { delete m_socket; m_socket = 0; } if (m_process) { delete m_process; m_process = 0; } } void ParserTests::testHelgrindSample1() { QSKIP("testfile does not exist"); initTest(QLatin1String("<API key>.xml")); QList<Error> expectedErrors; { Error error1; error1.setUnique(0x0); error1.setTid(1); error1.setKind(LockOrder); error1.setWhat(QLatin1String("Thread #1: lock order \"0xA39C270 before 0xA3AC010\" violated")); error1.setHelgrindThreadId(1); Stack stack1; Frame frame11; frame11.<API key>(0x4C2B806); frame11.setObject(QLatin1String("/usr/lib/valgrind/<API key>.so")); frame11.setFunctionName(QLatin1String("QMutex::lock()")); frame11.setDirectory(QLatin1String("/build/buildd/valgrind-3.6.0~svn20100212/helgrind")); frame11.setFile(QLatin1String("hg_intercepts.c")); frame11.setLine(1988); Frame frame12; frame12.<API key>(0x72E57EE); frame12.setObject(QLatin1String("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3")); frame12.setFunctionName(QLatin1String("QMutexLocker::relock()")); frame12.setDirectory(QLatin1String("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread")); frame12.setFile(QLatin1String("qmutex.h")); frame12.setLine(120); stack1.setFrames(QVector<Frame>() << frame11 << frame12); Stack stack2; stack2.setAuxWhat(QLatin1String("Required order was established by acquisition of lock at 0xA39C270")); Frame frame21; frame21.<API key>(0x4C2B806); frame21.setObject(QLatin1String("/usr/lib/valgrind/<API key>.so")); frame21.setFunctionName(QLatin1String("QMutex::lock()")); frame21.setDirectory(QLatin1String("/build/buildd/valgrind-3.6.0~svn20100212/helgrind")); frame21.setFile(QLatin1String("hg_intercepts.c")); frame21.setLine(1989); Frame frame22; frame22.<API key>(0x72E57EE); frame22.setObject(QLatin1String("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3")); frame22.setFunctionName(QLatin1String("QMutexLocker::relock()")); frame22.setDirectory(QLatin1String("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread")); frame22.setFile(QLatin1String("qmutex.h")); frame22.setLine(121); stack2.setFrames(QVector<Frame>() << frame21 << frame22); Stack stack3; stack3.setAuxWhat(QLatin1String("followed by a later acquisition of lock at 0xA3AC010")); Frame frame31; frame31.<API key>(0x4C2B806); frame31.setObject(QLatin1String("/usr/lib/valgrind/<API key>.so")); frame31.setFunctionName(QLatin1String("QMutex::lock()")); frame31.setDirectory(QLatin1String("/build/buildd/valgrind-3.6.0~svn20100212/helgrind")); frame31.setFile(QLatin1String("hg_intercepts.c")); frame31.setLine(1990); Frame frame32; frame32.<API key>(0x72E57EE); frame32.setObject(QLatin1String("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3")); frame32.setFunctionName(QLatin1String("QMutexLocker::relock()")); frame32.setDirectory(QLatin1String("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread")); frame32.setFile(QLatin1String("qmutex.h")); frame32.setLine(122); stack3.setFrames(QVector<Frame>() << frame31 << frame32); error1.setStacks(QVector<Stack>() << stack1 << stack2 << stack3); expectedErrors.append(error1); } Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); const QList<Error> actualErrors = rec.errors; if (actualErrors.first() != expectedErrors.first()) { dumpError(actualErrors.first()); dumpError(expectedErrors.first()); } QCOMPARE(actualErrors.first(), expectedErrors.first()); QCOMPARE(actualErrors.size(), 1); // QCOMPARE(rec.errorcounts, expectedErrorCounts); // QCOMPARE(rec.suppcounts, expectedSuppCounts); } void ParserTests::testMemcheckSample1() { initTest(QLatin1String("<API key>.xml")); QList<Error> expectedErrors; { Error error; error.setKind(InvalidRead); error.setWhat(QLatin1String("Invalid read of size 4")); error.setUnique(0x9); error.setTid(1); Frame f1; f1.<API key>(0x6E47964); f1.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0")); f1.setFunctionName(QLatin1String("QFrame::frameStyle() const")); f1.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/widgets")); f1.setFile(QLatin1String("qframe.cpp")); f1.setLine(252); Frame f2; f2.<API key>(0x118F2AF7); f2.setObject(QLatin1String("/usr/lib/kde4/plugins/styles/oxygen.so")); Frame f3; f3.<API key>(0x6A81671); f3.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0")); f3.setFunctionName(QLatin1String("QWidget::event(QEvent*)")); f3.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/kernel")); f3.setFile(QLatin1String("qwidget.cpp")); f3.setLine(8273); Frame f4; f4.<API key>(0x6A2B6EB); f4.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0")); f4.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/kernel")); f4.setFile(QLatin1String("qapplication.cpp")); f4.setFunctionName(QLatin1String("QApplicationPrivate::notify_helper(QObject*, QEvent*)")); f4.setLine(4396); Stack s1; s1.setAuxWhat(QLatin1String("Address 0x11527cb8 is not stack'd, malloc'd or (recently) free'd")); s1.setFrames(QVector<Frame>() << f1 << f2 << f3 << f4); error.setStacks( QVector<Stack>() << s1 ); expectedErrors << error; } QVector<QPair<qint64,qint64> > expectedErrorCounts; expectedErrorCounts.push_back(QPair<qint64,qint64>(9, 2)); QVector<QPair<QString,qint64> > expectedSuppCounts; expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("X on SUSE11 writev uninit padding"), static_cast<qint64>(12))); expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("dl-hack3-cond-1"), static_cast<qint64>(2))); expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("glibc-2.5.x-on-SUSE-10.2-(PPC)-2a"), static_cast<qint64>(2))); Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); const QList<Error> actualErrors = rec.errors; if (actualErrors.first() != expectedErrors.first()) { dumpError(actualErrors.first()); dumpError(expectedErrors.first()); } QCOMPARE(actualErrors.first(), expectedErrors.first()); QCOMPARE(actualErrors.size(), 3); QCOMPARE(rec.errorcounts, expectedErrorCounts); QCOMPARE(rec.suppcounts, expectedSuppCounts); } void ParserTests::testMemcheckSample2() { QSKIP("testfile does not exist"); initTest(QLatin1String("<API key>.xml")); Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); //tests: multiple stacks with auxwhat == stack count - 1. //the first auxwhat should be assigned to the _second_ stack. const QList<Error> errors = rec.errors; QCOMPARE(errors.size(), 1); const QVector<Stack> stacks = errors.first().stacks(); QCOMPARE(stacks.size(), 2); QCOMPARE(stacks.first().auxWhat(), QString()); QCOMPARE(stacks.last().auxWhat(), QLatin1String("Address 0x11b66c50 is 0 bytes inside a block of size 16 free'd")); } void ParserTests::testMemcheckSample3() { QSKIP("testfile does not exist"); initTest(QLatin1String("<API key>.xml")); Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); const QList<Error> errors = rec.errors; QCOMPARE(errors.size(), 6); { const Error error = errors.at(0); const QVector<Stack> stacks = error.stacks(); QCOMPARE(error.unique(), 0x1ll); QCOMPARE(error.what(), QLatin1String("Conditional jump or move depends on uninitialised value(s)")); QCOMPARE(error.kind(), UninitCondition); QCOMPARE(stacks.size(), 1); QCOMPARE(stacks.first().frames().size(), 12); QVERIFY(!error.suppression().isNull()); QCOMPARE(error.suppression().frames().count(), stacks.first().frames().size()); QCOMPARE(error.suppression().kind(), QLatin1String("Memcheck:Cond")); QVERIFY(!error.suppression().rawText().trimmed().isEmpty()); // rawtext contains <...> while <name></name> does not QCOMPARE(error.suppression().name(), QLatin1String("<API key>")); Suppression sup = error.suppression(); sup.setName(QLatin1String("<<API key>>")); QCOMPARE(sup.toString().trimmed(), sup.rawText().trimmed()); QCOMPARE(error.suppression().frames().first().object(), QLatin1String("/usr/lib/kde4/plugins/styles/qtcurve.so")); QVERIFY(error.suppression().frames().first().function().isEmpty()); QCOMPARE(error.suppression().frames().last().function(), QLatin1String("main")); QVERIFY(error.suppression().frames().last().object().isEmpty()); } QCOMPARE(rec.suppcounts.count(), 3); QCOMPARE(rec.suppcounts.at(0).second, qint64(1)); QCOMPARE(rec.suppcounts.at(1).second, qint64(2)); QCOMPARE(rec.suppcounts.at(2).second, qint64(3)); } void ParserTests::testMemcheckCharm() { QSKIP("testfile does not exist"); // a somewhat larger file, to make sure buffering and partial I/O works ok initTest(QLatin1String("<API key>.xml")); Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); const QList<Error> errors = rec.errors; QCOMPARE(errors.size(), 102); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); } void ParserTests::testValgrindCrash() { initTest(QLatin1String("<API key>.xml"), QStringList() << "--crash"); Parser parser; parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->state(), QProcess::NotRunning); QCOMPARE(m_process->exitStatus(), QProcess::CrashExit); QVERIFY(!parser.errorString().isEmpty()); QCOMPARE(m_socket->error(), QAbstractSocket::<API key>); QCOMPARE(parser.errorString(), m_socket->errorString()); } void ParserTests::testValgrindGarbage() { initTest(QLatin1String("<API key>.xml"), QStringList() << "--garbage"); Parser parser; parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->state(), QProcess::NotRunning); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QVERIFY(!parser.errorString().isEmpty()); qDebug() << parser.errorString(); } void ParserTests::testParserStop() { ThreadedParser parser; Memcheck::MemcheckRunner runner; runner.<API key>(<API key>()); runner.setParser(&parser); runner.<API key>(QStringList() << QLatin1String("-i") << dataFile(QLatin1String("<API key>.xml")) << "--wait" << "5"); runner.<API key>(QProcess::ForwardedChannels); runner.start(); QTest::qWait(500); runner.stop(); } void ParserTests::testRealValgrind() { QString executable = QProcessEnvironment::systemEnvironment().value("VALGRIND_TEST_BIN", <API key>()); qDebug() << "running exe:" << executable << " HINT: set VALGRIND_TEST_BIN to change this"; ThreadedParser parser; Memcheck::MemcheckRunner runner; runner.<API key>(QLatin1String("valgrind")); runner.<API key>(executable); runner.setParser(&parser); RunnerDumper dumper(&runner, &parser); runner.start(); runner.waitForFinished(); } void ParserTests::<API key>() { QTest::addColumn<QString>("valgrindExe"); QTest::addColumn<QStringList>("valgrindArgs"); QTest::addColumn<QString>("debuggee"); QTest::addColumn<QString>("debuggeeArgs"); QTest::newRow("invalid_client") << QString::fromLatin1("valgrind") << QStringList() << QString::fromLatin1("<API key>") << QString(); QTest::newRow("invalid_valgrind") << QString::fromLatin1("<API key>") << QStringList() << <API key>() << QString(); QTest::newRow("<API key>") << QString::fromLatin1("valgrind") << (QStringList() << QString::fromLatin1("--foobar-fail")) << <API key>() << QString(); } void ParserTests::<API key>() { QFETCH(QString, valgrindExe); QFETCH(QStringList, valgrindArgs); QFETCH(QString, debuggee); QFETCH(QString, debuggeeArgs); ThreadedParser parser; Memcheck::MemcheckRunner runner; runner.setParser(&parser); runner.<API key>(valgrindExe); runner.<API key>(valgrindArgs); runner.<API key>(debuggee); runner.<API key>(debuggeeArgs); RunnerDumper dumper(&runner, &parser); runner.start(); runner.waitForFinished(); QVERIFY(dumper.m_errorReceived); // just finish without deadlock and we are fine } QTEST_MAIN(ParserTests)
#ifndef FORMRESIZER_H #define FORMRESIZER_H #include "widgethostconstants.h" #include <QWidget> #include <QVector> <API key>(<API key>) <API key>(QFrame) namespace SharedTools { namespace Internal { class SizeHandleRect; class FormResizer : public QWidget { Q_OBJECT public: FormResizer(QWidget *parent = 0); void updateGeometry(); void setState(<API key> st); void update(); void setFormWindow(<API key> *fw); signals: void <API key>(const QRect &oldGeo, const QRect &newGeo); protected: virtual void resizeEvent(QResizeEvent *event); private slots: void <API key>(); private: QSize decorationSize() const; QWidget *mainContainer(); QFrame *m_frame; typedef QVector<SizeHandleRect*> Handles; Handles m_handles; <API key> * m_formWindow; }; } } // namespace SharedTools #endif // FORMRESIZER_H
#include "SDL_config.h" /* * Atari keyboard events manager, using Gemdos * * Patrice Mandin */ #ifndef <API key> #define <API key> #include "../SDL_sysvideo.h" extern void <API key>(_THIS); extern void <API key>(_THIS); extern void <API key>(void); #endif /* <API key> */ /* vi: set ts=4 sw=4 expandtab: */
##This file is part of pythonOCC. ##pythonOCC is free software: you can redistribute it and/or modify ##(at your option) any later version. ##pythonOCC is distributed in the hope that it will be useful, ##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from __future__ import print_function import webbrowser from OCC.Visualization import Tesselator import OCC from time import time import os import tempfile HEADER = """ <head> <title>pythonOCC @VERSION@ webgl renderer</title> <meta name='Author' content='Thomas Paviot - tpaviot@gmail.com'> <meta name='Keywords' content='WebGl,pythonOCC'> <meta charset="utf-8"> <style type="text/css"> body { background-color: @background-color@; margin: 0px; overflow: hidden; } #info { position: absolute; top: 96%; width: 96%; color: #808080; padding: 5px; font-family: Monospace; font-size: 13px; text-align: right; opacity: 1; } #pythonocc_rocks { padding: 5px; position: absolute; left: 1%; top: 85%; height: 60px; width: 305px; border-radius: 5px; border: 2px solid #f7941e; opacity: 0.7; font-family: Arial; background-color: #414042; color: #ffffff; font-size: 16px; opacity: 0.7; } a { color: #f7941e; text-decoration: none; } a:hover { color: #ffffff; } </style> </head> """ class HTMLHeader(object): def __init__(self, background_color='#000000'): self._background_color = background_color def get_str(self): header_str = HEADER.replace('@background-color@', '%s' % self._background_color) header_str = header_str.replace('@VERSION@', OCC.VERSION) return header_str class HTMLBody(object): def __init__(self, background_color='#000000', vertex_shader=None, fragment_shader=None, uniforms=None): self._background_color = background_color self._vertex_shader = vertex_shader self._fragment_shader = fragment_shader self._uniforms = uniforms def get_str(self): # get the location where pythonocc is running from <API key> = os.sep.join([OCC.__path__[0], 'Display', 'WebGl', 'js']) body_str = BODY.replace('@Three.jsPath@', '%s' % <API key>) body_str = body_str.replace('@background-color@', '%s' % self._background_color) body_str = body_str.replace('@VERSION@', OCC.VERSION) if (self._fragment_shader is not None) and (self._fragment_shader is not None): <API key> = '<script type="x-shader/x-vertex" id="vertexShader">%s</script>' % self._vertex_shader <API key> = '<script type="x-shader/x-fragment" id="fragmentShader">%s</script>' % self._fragment_shader <API key> = """ var vertexShader = document.getElementById( 'vertexShader' ).textContent; var fragmentShader = document.getElementById( 'fragmentShader' ).textContent; var shader_material = new THREE.ShaderMaterial( { uniforms: uniforms, vertexShader: vertexShader, fragmentShader: fragmentShader } ); """ if self._uniforms is None: body_str = body_str.replace('@Uniforms@', 'uniforms ={};\n') body_str = body_str.replace('@IncrementTime@', '') else: body_str = body_str.replace('@Uniforms@', self._uniforms) if 'time' in self._uniforms: body_str = body_str.replace('@IncrementTime@', 'uniforms.time.value += 0.05;') else: body_str = body_str.replace('@IncrementTime@', '') body_str = body_str.replace('@<API key>@', <API key>) body_str = body_str.replace('@<API key>@', <API key>) body_str = body_str.replace('@<API key>@', <API key>) body_str = body_str.replace('@ShapeMaterial@', 'shader_material') else: body_str = body_str.replace('@Uniforms@', '') body_str = body_str.replace('@<API key>@', '') body_str = body_str.replace('@<API key>@', '') body_str = body_str.replace('@<API key>@', '') body_str = body_str.replace('@ShapeMaterial@', 'phong_material') body_str = body_str.replace('@IncrementTime@', '') return body_str class ThreejsRenderer(object): def __init__(self, background_color="#123345", vertex_shader=None, fragment_shader=None, uniforms=None, path=None): if not path: self._path = tempfile.mkdtemp() else: self._path = path self._js_filename = os.path.join(self._path, "shape.js") self._html_filename = os.path.join(self._path, "webgl_topods_shape.html" ) self._background_color = background_color self._vertex_shader = vertex_shader self._fragment_shader = fragment_shader self._uniforms = uniforms def set_vertex_shader(self, vertex_shader): ''' adds a vertex shader definition ''' self._vertex_shader = vertex_shader def set_fragment_shader(self, fragment_shader): ''' adds a fragment shader ''' self._fragment_shader = fragment_shader def create_files(self, shape): ''' generate .js and .html files ''' self._shape = shape print("Tesselate shape ...") t0 = time() tess = Tesselator(self._shape) t1 = time() print("done in %f s." % (t1-t0)) print("Exporting tesselation to JSON ...") t2 = time() tess.<API key>(self._js_filename) t3 = time() print("done in %f s." % (t3-t2)) print("Generating HTML stream ...") self.GenerateHTMLFile() print("done.") return self._js_filename, self._html_filename def DisplayShape(self, shape): self.create_files(shape) print("Opening html output in the default webbrowser ...") # previous version us a os.system call to the "open" command # but this is a platform (osx) specific solution _path = "file:///{0}".format(os.path.join(os.getcwd(), self._html_filename)) webbrowser.open_new_tab(_path) def GenerateHTMLFile(self): """ Generate the HTML file to be rendered wy the web browser """ fp = open(self._html_filename, "w") fp.write("<!DOCTYPE HTML>") fp.write('<html lang="en">') # header fp.write(HTMLHeader(self._background_color).get_str()) # body fp.write(HTMLBody(self._background_color, self._vertex_shader, self._fragment_shader, self._uniforms).get_str()) fp.write("</html>\n") fp.close() if __name__ == "__main__": from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox box_shp = BRepPrimAPI_MakeBox(10., 20., 30.).Shape() my_ren = ThreejsRenderer() my_ren.DisplayShape(box_shp)
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version <API key> = <API key>:new { } ObjectTemplates:addTemplate(<API key>, "object/tangible/painting/<API key>.iff")
// This file is part of Bytecoin. // Bytecoin is free software: you can redistribute it and/or modify // (at your option) any later version. // Bytecoin is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #include <boost/<API key>.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/random_access_index.hpp> #include "crypto/hash.h" #include <vector> namespace CryptoNote { class ISerializer; class BlockIndex { public: BlockIndex() : m_index(m_container.get<1>()) {} void pop() { m_container.pop_back(); } // returns true if new element was inserted, false if already exists bool push(const Crypto::Hash& h) { auto result = m_container.push_back(h); return result.second; } bool hasBlock(const Crypto::Hash& h) const { return m_index.find(h) != m_index.end(); } bool getBlockHeight(const Crypto::Hash& h, uint32_t& height) const { auto hi = m_index.find(h); if (hi == m_index.end()) return false; height = static_cast<uint32_t>(std::distance(m_container.begin(), m_container.project<0>(hi))); return true; } uint32_t size() const { return static_cast<uint32_t>(m_container.size()); } void clear() { m_container.clear(); } Crypto::Hash getBlockId(uint32_t height) const; std::vector<Crypto::Hash> getBlockIds(uint32_t startBlockIndex, uint32_t maxCount) const; bool findSupplement(const std::vector<Crypto::Hash>& ids, uint32_t& offset) const; std::vector<Crypto::Hash> buildSparseChain(const Crypto::Hash& startBlockId) const; Crypto::Hash getTailId() const; void serialize(ISerializer& s); private: typedef boost::<API key> < Crypto::Hash, boost::multi_index::indexed_by< boost::multi_index::random_access<>, boost::multi_index::hashed_unique<boost::multi_index::identity<Crypto::Hash>> > > ContainerT; ContainerT m_container; ContainerT::nth_index<1>::type& m_index; }; }
#if defined(<API key>) && !defined (__ATK_H_INSIDE__) && !defined (ATK_COMPILATION) #error "Only <atk/atk.h> can be included directly." #endif #ifndef __ATK_STATE_SET_H__ #define __ATK_STATE_SET_H__ #include <glib-object.h> #include <atk/atkobject.h> #include <atk/atkstate.h> G_BEGIN_DECLS #define ATK_TYPE_STATE_SET (<API key> ()) #define ATK_STATE_SET(obj) (<API key> ((obj), ATK_TYPE_STATE_SET, AtkStateSet)) #define ATK_STATE_SET_CLASS(klass) (<API key> ((klass), ATK_TYPE_STATE_SET, AtkStateSetClass)) #define ATK_IS_STATE_SET(obj) (<API key> ((obj), ATK_TYPE_STATE_SET)) #define <API key>(klass) (<API key> ((klass), ATK_TYPE_STATE_SET)) #define <API key>(obj) (<API key> ((obj), ATK_TYPE_STATE_SET, AtkStateSetClass)) typedef struct _AtkStateSetClass AtkStateSetClass; struct _AtkStateSet { GObject parent; }; struct _AtkStateSetClass { GObjectClass parent; }; <API key> GType <API key> (void); <API key> AtkStateSet* atk_state_set_new (void); <API key> gboolean <API key> (AtkStateSet *set); <API key> gboolean <API key> (AtkStateSet *set, AtkStateType type); <API key> void <API key> (AtkStateSet *set, AtkStateType *types, gint n_types); <API key> void <API key> (AtkStateSet *set); <API key> gboolean <API key> (AtkStateSet *set, AtkStateType type); <API key> gboolean <API key> (AtkStateSet *set, AtkStateType *types, gint n_types); <API key> gboolean <API key> (AtkStateSet *set, AtkStateType type); <API key> AtkStateSet* <API key> (AtkStateSet *set, AtkStateSet *compare_set); <API key> AtkStateSet* <API key> (AtkStateSet *set, AtkStateSet *compare_set); <API key> AtkStateSet* <API key> (AtkStateSet *set, AtkStateSet *compare_set); G_END_DECLS #endif /* __ATK_STATE_SET_H__ */
// <API key>.cs // Part of the Mono class libraries at // mcs/class/System.Data.OracleClient/System.Data.OracleClient // Assembly: System.Data.OracleClient.dll // Namespace: System.Data.OracleClient // Authors: // Hubert FONGARNAND <informatique.internet@fiducial.fr> using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.OracleClient.Oci; using System.Drawing.Design; using System.EnterpriseServices; using System.Text; using System.Threading; namespace System.Data.OracleClient { internal class <API key> { Hashtable pools = new Hashtable(); public <API key> () { } public <API key> GetConnectionPool (<API key> info, int minPoolSize, int maxPoolSize) { lock (pools) { <API key> pool = (<API key>) pools [info.ConnectionString]; if (pool == null) { pool = new <API key> (this, info, minPoolSize, maxPoolSize); pools [info.ConnectionString] = pool; } return pool; } } public virtual OciGlue CreateConnection (<API key> info) { OciGlue oci; oci = new OciGlue (); oci.CreateConnection (info); return oci; } public void Dispose () { if (pools != null) { foreach (<API key> pool in pools) pool.Dispose (); pools.Clear (); pools = null; } } ~<API key> () { Dispose (); } } }
// 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, // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // included in all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // 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. // Authors: // Andreia Gaita (avidigal@novell.com) using System; namespace Mono.WebBrowser.DOM { public interface IMediaList { } }
/** * @file viewer3D-3-objects.cpp * @ingroup examples/3dViewer * @author Bertrand Kerautret (\c kerautre@loria.fr ) * LORIA (CNRS, UMR 7503), University of Nancy, France * * @date 2011/19/03 * * Simple example of class Viewer3D. * * This file is part of the DGtal library. */ #include <iostream> #include <QtGui/qapplication.h> #include "DGtal/io/viewers/Viewer3D.h" #include "DGtal/io/<API key>.h" #include "DGtal/io/Color.h" #include "DGtal/base/Common.h" #include "DGtal/helpers/StdDefs.h" #include "DGtal/shapes/Shapes.h" using namespace std; using namespace DGtal; using namespace Z3i; // Standard services - public : int main( int argc, char** argv ) { QApplication application(argc,argv); Viewer3D viewer; viewer.show(); Point p1( 0, 0, 0 ); Point p2( 10, 10 , 10 ); Domain domain( p1, p2 ); DigitalSet shape_set( domain ); Shapes<Domain>::addNorm1Ball( shape_set, Point( 5, 5, 5 ), 2 ); Shapes<Domain>::addNorm2Ball( shape_set, Point( 3, 3, 3 ), 2 ); viewer << CustomColors3D(Color(250, 200,0, 100),Color(250, 200,0, 25)); viewer << shape_set; Object6_18 shape( dt6_18, shape_set ); viewer << SetMode3D( shape.className(), "DrawAdjacencies" ); viewer << shape; Object18_6 shape2( dt18_6, shape_set ); viewer << SetMode3D( shape2.className(), "DrawAdjacencies" ); //viewer << shape2; viewer<< Viewer3D::updateDisplay; return application.exec(); }
package org.hy.commons.lang.character.example; import java.util.Random; public class IsChineseOrEnglish { // <API key> // <API key> public static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.<API key> || ub == Character.UnicodeBlock.<API key> || ub == Character.UnicodeBlock.<API key> || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.<API key> || ub == Character.UnicodeBlock.<API key>) { return true; } return false; } public static void isChinese(String strName) { char[] ch = strName.toCharArray(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (isChinese(c) == true) { System.out.println(isChinese(c)); return; } else { System.out.println(isChinese(c)); return; } } } public static void main(String[] args) { Random r = new Random(); for(int i=0;i<20;i++) System.out.println(r.nextInt(10)+1); isChinese(""); isChinese(""); isChinese("aa"); isChinese("aa"); } }
#include "six/sidd/<API key>.h" using namespace six; using namespace six::sidd; InputROI::InputROI(double nr, double nc, double fr, double fc) : size(nr, nc), upperLeft(fr, fc) { } InputROI* InputROI::clone() const { return new InputROI(*this); } TxRcvPolarization::TxRcvPolarization(PolarizationType tx, PolarizationType rcv, double rcvOffset) : txPolarization(tx), rcvPolarization(rcv), <API key>(rcvOffset), processed(Init::undefined<BooleanType>()) { } TxRcvPolarization::TxRcvPolarization(PolarizationType tx, PolarizationType rcv) : txPolarization(tx), rcvPolarization(rcv), <API key>(Init::undefined<double>()), processed(Init::undefined<BooleanType>()) { } TxRcvPolarization* TxRcvPolarization::clone() const { return new TxRcvPolarization(*this); } Information::Information() : sensorName(Init::undefined<std::string>()), radarMode(Init::undefined<RadarModeType>()), radarModeID(Init::undefined<std::string>()), localDateTime(Init::undefined<std::string>()), collectionDuration(Init::undefined<double>()), resolution(Init::undefined<types::RgAz<double> >()) { //! TODO: Should we set sensorName to SPOTLIGHT? } Information* Information::clone() const { return new Information(*this); } Geometry::Geometry() : azimuth(Init::undefined<double>()), slope(Init::undefined<double>()), squint(Init::undefined<double>()), graze(Init::undefined<double>()), tilt(Init::undefined<double>()) { } Geometry* Geometry::clone() const { return new Geometry(*this); } Phenomenology::Phenomenology() : shadow(Init::undefined<AngleMagnitude>()), layover(Init::undefined<AngleMagnitude>()), multiPath(Init::undefined<double>()), groundTrack(Init::undefined<double>()) { } Phenomenology* Phenomenology::clone() const { return new Phenomenology(*this); } Collection* Collection::clone() const { return new Collection(*this); } Product::Product() : resolution(Init::undefined<RowColDouble>()), north(Init::undefined<double>()) { } <API key>::<API key>(unsigned int numCollections) { collections.resize(numCollections); for (unsigned int i = 0; i < numCollections; ++i) { collections[i].reset(new Collection()); } } <API key>* <API key>::clone() const { return new <API key>(*this); }
// UriTemplateTable.cs // Atsushi Enomoto <atsushi@ximian.com> // 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, // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // included in all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // 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. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using Pair = System.Collections.Generic.KeyValuePair<System.UriTemplate, object>; namespace System { public class UriTemplateTable { public UriTemplateTable () { } public UriTemplateTable (Uri baseAddress) { BaseAddress = baseAddress; key_value_pairs = new List<Pair> (); } public UriTemplateTable (IEnumerable<Pair> keyValuePairs) { key_value_pairs = keyValuePairs as IList<Pair>; if (key_value_pairs == null) key_value_pairs = new List<Pair> (keyValuePairs); } public UriTemplateTable (Uri baseAddress, IEnumerable<Pair> keyValuePairs) : this (keyValuePairs) { BaseAddress = baseAddress; } void CheckReadOnly () { if (is_readonly) throw new <API key> ("This UriTemplateTable is read-only"); } bool is_readonly; Uri base_address; IList<Pair> key_value_pairs; public Uri BaseAddress { get { return base_address; } set { CheckReadOnly (); base_address = value; } } public bool IsReadOnly { get { return is_readonly; } } public IList<Pair> KeyValuePairs { get { return key_value_pairs; } } [MonoTODO] public void MakeReadOnly (bool <API key>) { throw new <API key> (); } public Collection<UriTemplateMatch> Match (Uri uri) { if (key_value_pairs.Count == 0) throw new <API key> ("At least one UriTemplate must exist in the UriTemplateTable."); var c = new Collection<UriTemplateMatch> (); UriTemplateMatch ret = null; foreach (Pair p in key_value_pairs) { ret = p.Key.Match (base_address, uri); if (ret != null) c.Add (ret); } return c; } public UriTemplateMatch MatchSingle (Uri uri) { if (key_value_pairs.Count == 0) throw new <API key> ("At least one UriTemplate must exist in the UriTemplateTable."); UriTemplateMatch ret = null; foreach (Pair p in key_value_pairs) { ret = p.Key.Match (base_address, uri); if (ret != null) return ret; } return null; } } }
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/awing_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_awing_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 4185031918, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/awing_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_awing_s02.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 577055865, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1430717714, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2387651973, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2826438901, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1936695394, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2775195131, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2122167660, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/bwing_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_bwing_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2775913620, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/bwing_engine_s02.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_bwing_s02.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2120399875, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/vt49_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_decimator.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1116177012, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/vt49_engine_s02.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_decimator.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2576362211, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_tiefighter_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1064155476, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2054741017, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2708436110, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2269630974, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1548777833, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 987700646, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3788027185, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1758759963, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3015910540, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_tiefighter_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 557699423, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_tieadvanced_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1078468437, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_tiebomber_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 4073386065, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3973162809, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/<API key>.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3648736552, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_xwing_neg_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1476333721, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_xwing_neg_s02.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2364061710, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_xwing_neg_s03.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3320176515, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_xwing_pos_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 4116130746, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_xwing_pos_s02.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 775979821, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/<API key>.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_xwing_pos_s03.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1733158048, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/ykl37r_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_ykl37r_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 332197254, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/ykl37r_engine_s02.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_ykl37r_s02.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3369813265, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/yt1300_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_yt1300_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3573306455, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/yt1300_engine_s02.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_yt1300_s02.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 267123904, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/ywing_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_ywing_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 281820240, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/ywing_engine_s02.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_ywing_s02.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 3420165319, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/z95_engine_s01.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_z95_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 2645704367, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff") <API key> = <API key>:new { <API key> = "object/tangible/ship/attachment/engine/<API key>.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups appearanceFilename = "appearance/z95_engine_s02.apt", <API key> = "", <API key> = {}, clearFloraRadius = 0, clientDataFile = "clientdata/ship/component/eng_z95_s01.cdf", <API key> = 1073741824, <API key> = 0, <API key> = 51, <API key> = 1, <API key> = 0, <API key> = 1, <API key> = 0, containerType = 0, <API key> = 1, <API key> = {}, detailedDescription = "@item_n:ship_attachment", gameObjectType = 1073741824, <API key> = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@item_n:ship_attachment", onlyVisibleInTools = 0, <API key> = {}, <API key> = "", <API key> = {}, scale = 1, <API key> = 0.5, sendToClient = 1, <API key> = "", snapToTerrain = 1, socketDestinations = {}, <API key> = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, <API key> = 0, clientObjectCRC = 1185257016, <API key> = {"object/object/base/shared_base_object.iff", "object/tangible/base/<API key>.iff", "object/tangible/ship/attachment/base/<API key>.iff"} ]] } ObjectTemplates:addClientTemplate(<API key>, "object/tangible/ship/attachment/engine/<API key>.iff")
// of patent rights can be found in the PATENTS file in the same directory. #pragma once #include <string> #include <stdexcept> #include "rocksdb/options.h" #include "rocksdb/status.h" #include "util/mutable_cf_options.h" #ifndef ROCKSDB_LITE namespace rocksdb { // Returns true if the input char "c" is considered as a special character // that will be escaped when EscapeOptionString() is called. // @param c the input char // @return true if the input char "c" is considered as a special character. // @see EscapeOptionString bool isSpecialChar(const char c); // If the input char is an escaped char, it will return the its // associated raw-char. Otherwise, the function will simply return // the original input char. char UnescapeChar(const char c); // If the input char is a control char, it will return the its // associated escaped char. Otherwise, the function will simply return // the original input char. char EscapeChar(const char c); // Converts a raw string to an escaped string. Escaped-characters are // defined via the isSpecialChar() function. When a char in the input // string "raw_string" is classified as a special characters, then it // will be prefixed by '\' in the output. // It's inverse function is <API key>(). // @param raw_string the input string // @return the '\' escaped string of the input "raw_string" // @see isSpecialChar, <API key> std::string EscapeOptionString(const std::string& raw_string); // The inverse function of EscapeOptionString. It converts // an '\' escaped string back to a raw string. // @param escaped_string the input '\' escaped string // @return the raw string of the input "escaped_string" std::string <API key>(const std::string& escaped_string); Status <API key>( const MutableCFOptions& base_options, const std::unordered_map<std::string, std::string>& options_map, MutableCFOptions* new_options); enum class OptionType { kBoolean, kInt, kUInt, kUInt32T, kUInt64T, kSizeT, kString, kDouble, kCompactionStyle, kSliceTransform, kCompressionType, <API key>, kTableFactory, kComparator, kCompactionFilter, <API key>, kMergeOperator, kMemTableRepFactory, kUnknown }; enum class <API key> { kNormal, kByName, // The option is pointer typed so we can only verify // based on it's name. kDeprecated // The option is no longer used in rocksdb. The RocksDB // OptionsParser will still accept this option if it // happen to exists in some Options file. However, the // parser will not include it in serialization and // verification processes. }; // A struct for storing constant option information such as option name, // option type, and offset. struct OptionTypeInfo { int offset; OptionType type; <API key> verification; }; // A helper function that converts "opt_address" to a std::string // based on the specified OptionType. bool <API key>(const char* opt_address, const OptionType opt_type, std::string* value); static std::unordered_map<std::string, OptionTypeInfo> <API key> = { /* // not yet supported AccessHint <API key>; Env* env; InfoLogLevel info_log_level; WALRecoveryMode wal_recovery_mode; std::shared_ptr<Cache> row_cache; std::shared_ptr<DeleteScheduler> delete_scheduler; std::shared_ptr<Logger> info_log; std::shared_ptr<RateLimiter> rate_limiter; std::shared_ptr<Statistics> statistics; std::vector<DbPath> db_paths; std::vector<std::shared_ptr<EventListener>> listeners; */ {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"allow_mmap_reads", {offsetof(struct DBOptions, allow_mmap_reads), OptionType::kBoolean, <API key>::kNormal}}, {"allow_fallocate", {offsetof(struct DBOptions, allow_fallocate), OptionType::kBoolean, <API key>::kNormal}}, {"allow_mmap_writes", {offsetof(struct DBOptions, allow_mmap_writes), OptionType::kBoolean, <API key>::kNormal}}, {"allow_os_buffer", {offsetof(struct DBOptions, allow_os_buffer), OptionType::kBoolean, <API key>::kNormal}}, {"create_if_missing", {offsetof(struct DBOptions, create_if_missing), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"disableDataSync", {offsetof(struct DBOptions, disableDataSync), OptionType::kBoolean, <API key>::kNormal}}, {"disable_data_sync", // for compatibility {offsetof(struct DBOptions, disableDataSync), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"error_if_exists", {offsetof(struct DBOptions, error_if_exists), OptionType::kBoolean, <API key>::kNormal}}, {"is_fd_close_on_exec", {offsetof(struct DBOptions, is_fd_close_on_exec), OptionType::kBoolean, <API key>::kNormal}}, {"paranoid_checks", {offsetof(struct DBOptions, paranoid_checks), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kSizeT, <API key>::kNormal}}, {"use_adaptive_mutex", {offsetof(struct DBOptions, use_adaptive_mutex), OptionType::kBoolean, <API key>::kNormal}}, {"use_fsync", {offsetof(struct DBOptions, use_fsync), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"max_open_files", {offsetof(struct DBOptions, max_open_files), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kSizeT, <API key>::kNormal}}, {"keep_log_file_num", {offsetof(struct DBOptions, keep_log_file_num), OptionType::kSizeT, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kSizeT, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kSizeT, <API key>::kNormal}}, {"max_log_file_size", {offsetof(struct DBOptions, max_log_file_size), OptionType::kSizeT, <API key>::kNormal}}, {"db_log_dir", {offsetof(struct DBOptions, db_log_dir), OptionType::kString, <API key>::kNormal}}, {"wal_dir", {offsetof(struct DBOptions, wal_dir), OptionType::kString, <API key>::kNormal}}, {"max_subcompactions", {offsetof(struct DBOptions, max_subcompactions), OptionType::kUInt32T, <API key>::kNormal}}, {"WAL_size_limit_MB", {offsetof(struct DBOptions, WAL_size_limit_MB), OptionType::kUInt64T, <API key>::kNormal}}, {"WAL_ttl_seconds", {offsetof(struct DBOptions, WAL_ttl_seconds), OptionType::kUInt64T, <API key>::kNormal}}, {"bytes_per_sync", {offsetof(struct DBOptions, bytes_per_sync), OptionType::kUInt64T, <API key>::kNormal}}, {"delayed_write_rate", {offsetof(struct DBOptions, delayed_write_rate), OptionType::kUInt64T, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kUInt64T, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kUInt64T, <API key>::kNormal}}, {"max_total_wal_size", {offsetof(struct DBOptions, max_total_wal_size), OptionType::kUInt64T, <API key>::kNormal}}, {"wal_bytes_per_sync", {offsetof(struct DBOptions, wal_bytes_per_sync), OptionType::kUInt64T, <API key>::kNormal}}, {"<API key>", {offsetof(struct DBOptions, <API key>), OptionType::kUInt, <API key>::kNormal}}}; static std::unordered_map<std::string, OptionTypeInfo> <API key> = { /* not yet supported <API key> <API key>; <API key> <API key>; CompressionOptions compression_opts; <API key> <API key>; typedef std::vector<std::shared_ptr<<API key>>> <API key>; UpdateStatus (*inplace_callback)(char* existing_value, uint34_t* existing_value_size, Slice delta_value, std::string* merged_value); std::vector<int> <API key>; */ {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"filter_deletes", {offsetof(struct ColumnFamilyOptions, filter_deletes), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kBoolean, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt64T, <API key>::kNormal}}, {"hard_rate_limit", {offsetof(struct ColumnFamilyOptions, hard_rate_limit), OptionType::kDouble, <API key>::kDeprecated}}, {"soft_rate_limit", {offsetof(struct ColumnFamilyOptions, soft_rate_limit), OptionType::kDouble, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kDeprecated}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"num_levels", {offsetof(struct ColumnFamilyOptions, num_levels), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kInt, <API key>::kNormal}}, {"arena_block_size", {offsetof(struct ColumnFamilyOptions, arena_block_size), OptionType::kSizeT, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kSizeT, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kSizeT, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kSizeT, <API key>::kNormal}}, {"write_buffer_size", {offsetof(struct ColumnFamilyOptions, write_buffer_size), OptionType::kSizeT, <API key>::kNormal}}, {"bloom_locality", {offsetof(struct ColumnFamilyOptions, bloom_locality), OptionType::kUInt32T, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt32T, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt32T, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt32T, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt64T, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt64T, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt64T, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::kUInt, <API key>::kDeprecated}}, {"compression", {offsetof(struct ColumnFamilyOptions, compression), OptionType::kCompressionType, <API key>::kNormal}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::<API key>, <API key>::kNormal}}, {"comparator", {offsetof(struct ColumnFamilyOptions, comparator), OptionType::kComparator, <API key>::kByName}}, {"prefix_extractor", {offsetof(struct ColumnFamilyOptions, prefix_extractor), OptionType::kSliceTransform, <API key>::kByName}}, {"memtable_factory", {offsetof(struct ColumnFamilyOptions, memtable_factory), OptionType::kMemTableRepFactory, <API key>::kByName}}, {"table_factory", {offsetof(struct ColumnFamilyOptions, table_factory), OptionType::kTableFactory, <API key>::kByName}}, {"compaction_filter", {offsetof(struct ColumnFamilyOptions, compaction_filter), OptionType::kCompactionFilter, <API key>::kByName}}, {"<API key>", {offsetof(struct ColumnFamilyOptions, <API key>), OptionType::<API key>, <API key>::kByName}}, {"merge_operator", {offsetof(struct ColumnFamilyOptions, merge_operator), OptionType::kMergeOperator, <API key>::kByName}}, {"compaction_style", {offsetof(struct ColumnFamilyOptions, compaction_style), OptionType::kCompactionStyle, <API key>::kNormal}}}; } // namespace rocksdb #endif // !ROCKSDB_LITE
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const graphql_1 = require("graphql"); exports.default = { test(value) { return value && typeof value.kind === 'string'; }, serialize(value, _config, indentation, _depth, _refs, _printer) { return graphql_1.print(value) .trim() .replace(/\n/g, '\n' + indentation); }, }; //# sourceMappingURL=astSerializer.js.map
# Backup API Type ## Use The `Backup` API type is used as a request for the Ark Server to perform a backup. Once created, the Ark Server immediately starts the backup process. ## API GroupVersion Backup belongs to the API group version `ark.heptio.com/v1`. ## Definition Here is a sample `Backup` object with each of the fields documented: yaml # Standard Kubernetes API Version declaration. Required. apiVersion: ark.heptio.com/v1 # Standard Kubernetes Kind declaration. Required. kind: Backup # Standard Kubernetes metadata. Required. metadata: # Backup name. May be any valid Kubernetes object name. Required. name: a # Backup namespace. Must be heptio-ark. Required. namespace: heptio-ark # Parameters about the backup. Required. spec: # Array of namespaces to include in the backup. If unspecified, all namespaces are included. # Optional. includedNamespaces: - '*' # Array of namespaces to exclude from the backup. Optional. excludedNamespaces: - some-namespace # Array of resources to include in the backup. Resources may be shortcuts (e.g. 'po' for 'pods') # or fully-qualified. If unspecified, all resources are included. Optional. includedResources: - '*' # Array of resources to exclude from the backup. Resources may be shortcuts (e.g. 'po' for 'pods') # or fully-qualified. Optional. excludedResources: - storageclasses.storage.k8s.io # Whether or not to include cluster-scoped resources. Valid values are true, false, and # null/unset. If true, all cluster-scoped resources are included (subject to included/excluded # resources and the label selector). If false, no cluster-scoped resources are included. If unset, # all cluster-scoped resources are included if and only if all namespaces are included and there are # no excluded namespaces. Otherwise, if there is at least one namespace specified in either # includedNamespaces or excludedNamespaces, then the only cluster-scoped resources that are backed # up are those associated with namespace-scoped resources included in the backup. For example, if a # <API key> is included in the backup, its associated PersistentVolume (which is # cluster-scoped) would also be backed up. <API key>: null # Individual objects must match this label selector to be included in the backup. Optional. labelSelector: matchLabels: app: ark component: server # Whether or not to snapshot volumes. This only applies to PersistentVolumes for Azure, GCE, and # AWS. Valid values are true, false, and null/unset. If unset, Ark performs snapshots as long as # a persistent volume provider is configured for Ark. snapshotVolumes: null # The amount of time before this backup is eligible for garbage collection. ttl: 24h0m0s # Actions to perform at different times during a backup. The only hook currently supported is # executing a command in a container in a pod using the pod exec API. Optional. hooks: # Array of hooks that are applicable to specific resources. Optional. resources: - # Name of the hook. Will be displayed in backup log. name: my-hook # Array of namespaces to which this hook applies. If unspecified, the hook applies to all # namespaces. Optional. includedNamespaces: - '*' # Array of namespaces to which this hook does not apply. Optional. excludedNamespaces: - some-namespace # Array of resources to which this hook applies. The only resource supported at this time is # pods. includedResources: - pods # Array of resources to which this hook does not apply. Optional. excludedResources: [] # This hook only applies to objects matching this label selector. Optional. labelSelector: matchLabels: app: ark component: server # An array of hooks to run. Currently only "exec" hooks are supported. hooks: - # The type of hook. This must be "exec". exec: # The name of the container where the command will be executed. If unspecified, the # first container in the pod will be used. Optional. container: my-container # The command to execute, specified as an array. Required. command: - /bin/uname - -a # How to handle an error executing the command. Valid values are Fail and Continue. # Defaults to Fail. Optional. onError: Fail # How long to wait for the command to finish executing. Defaults to 30 seconds. Optional. timeout: 10s # Status about the Backup. Users should not set any data here. status: # The date and time when the Backup is eligible for garbage collection. expiration: null # The current phase. Valid values are New, FailedValidation, InProgress, Completed, Failed. phase: "" # An array of any validation errors encountered. validationErrors: null # The version of this Backup. The only version currently supported is 1. version: 1 # Information about PersistentVolumes needed during restores. volumeBackups: # Each key is the name of a PersistentVolume. some-pv-name: # The ID used by the cloud provider for the snapshot created for this Backup. snapshotID: snap-1234 # The type of the volume in the cloud provider API. type: io1 # The availability zone where the volume resides in the cloud provider. availabilityZone: my-zone # The amount of provisioned IOPS for the volume. Optional. iops: 10000
package org.jetbrains.kotlin.idea.codeInsight.surroundWith.statement; import com.intellij.codeInsight.CodeInsightBundle; import org.jetbrains.annotations.NotNull; public class <API key> extends <API key> { @Override public String <API key>() { return CodeInsightBundle.message("surround.with.ifelse.template"); } @NotNull @Override protected String getCodeTemplate() { return "if (a) { \n} else { \n}"; } @Override protected boolean <API key>() { return false; } }
// xfail-fast // file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. extern mod extra; use extra::json; use std::hashmap::HashMap; use std::option; enum object { bool_value(bool), int_value(i64), } fn lookup(table: ~json::Object, key: ~str, default: ~str) -> ~str { match table.find(&key) { option::Some(&extra::json::String(ref s)) => { copy *s } option::Some(value) => { error!("%s was expected to be a string but is a %?", key, value); default } option::None => { default } } } fn add_interface(store: int, managed_ip: ~str, data: extra::json::Json) -> (~str, object) { match &data { &extra::json::Object(ref interface) => { let name = lookup(copy *interface, ~"ifDescr", ~""); let label = fmt!("%s-%s", managed_ip, name); (label, bool_value(false)) } _ => { error!("Expected dict for %s interfaces but found %?", managed_ip, data); (~"gnos:missing-interface", bool_value(true)) } } } fn add_interfaces(store: int, managed_ip: ~str, device: HashMap<~str, extra::json::Json>) -> ~[(~str, object)] { match device.get(&~"interfaces") { &extra::json::List(ref interfaces) => { do interfaces.map |interface| { add_interface(store, copy managed_ip, copy *interface) } } _ => { error!("Expected list for %s interfaces but found %?", managed_ip, device.get(&~"interfaces")); ~[] } } } pub fn main() {}
# <API key>: Apache-2.0 from .common import BaseTest from c7n.lookup import Lookup class LookupTest(BaseTest): def test_lookup_type(self): number_schema = {'type': 'number'} <API key> = Lookup.lookup_type(number_schema) string_schema = {'type': 'string'} <API key> = Lookup.lookup_type(string_schema) self.assertEqual(number_schema, <API key>['oneOf'][1]) self.assertEqual(number_schema, <API key>['oneOf'][0]['oneOf'][0] ['properties']['default-value']) self.assertEqual(string_schema, <API key>['oneOf'][1]) self.assertEqual(string_schema, <API key>['oneOf'][0]['oneOf'][0] ['properties']['default-value']) def <API key>(self): source = 'mock_string_value' value = Lookup.extract(source) self.assertEqual(source, value) def test_extract_lookup(self): data = { 'field_level_1': { 'field_level_2': 'value_1' } } source = { 'type': Lookup.RESOURCE_SOURCE, 'key': 'field_level_1.field_level_2', 'default-value': 'value_2' } value = Lookup.extract(source, data) self.assertEqual(value, 'value_1') def <API key>(self): resource = { 'field_level_1': { 'field_level_2': 'value_1' } } source = { 'type': Lookup.RESOURCE_SOURCE, 'key': 'field_level_1.field_level_2', 'default-value': 'value_2' } value = Lookup.<API key>(source, resource) self.assertEqual(value, 'value_1') def <API key>(self): resource = { 'field_level_1': { 'field_level_2': None } } source = { 'type': Lookup.RESOURCE_SOURCE, 'key': 'field_level_1.field_level_2', 'default-value': 'value_2' } value = Lookup.<API key>(source, resource) self.assertEqual(value, 'value_2') def <API key>(self): resource = { 'field_level_1': { 'field_level_2': None } } source = { 'type': Lookup.RESOURCE_SOURCE, 'key': 'field_level_1.field_level_2' } with self.assertRaises(Exception): Lookup.<API key>(source, resource)
#ifndef <API key> #define <API key> #include <set> #include <string> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/debug/stack_trace.h" #include "base/files/file_path.h" #include "base/lazy_instance.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/timer.h" #include "googleurl/src/gurl.h" #include "net/base/host_port_pair.h" #include "net/http/<API key>.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" namespace base { class <API key>; } // namespace base namespace net { class HttpResponseHeaders; class IOBuffer; class URLFetcherDelegate; class <API key>; class <API key>; class <API key>; class <API key>; class URLFetcherCore : public base::<API key><URLFetcherCore>, public URLRequest::Delegate { public: URLFetcherCore(URLFetcher* fetcher, const GURL& original_url, URLFetcher::RequestType request_type, URLFetcherDelegate* d); // Starts the load. It's important that this not happen in the constructor // because it causes the IO thread to begin AddRef()ing and Release()ing // us. If our caller hasn't had time to fully construct us and take a // reference, the IO thread could interrupt things, run a task, Release() // us, and destroy us, leaving the caller with an already-destroyed object // when construction finishes. void Start(); // Stops any in-progress load and ensures no callback will happen. It is // safe to call this multiple times. void Stop(); // URLFetcher-like functions. // For POST requests, set |content_type| to the MIME type of the // content and set |content| to the data to upload. void SetUploadData(const std::string& upload_content_type, const std::string& upload_content); void SetUploadFilePath(const std::string& upload_content_type, const base::FilePath& file_path, scoped_refptr<base::TaskRunner> file_task_runner); void SetChunkedUpload(const std::string& upload_content_type); // Adds a block of data to be uploaded in a POST body. This can only be // called after Start(). void AppendChunkToUpload(const std::string& data, bool is_last_chunk); // |flags| are flags to apply to the load operation--these should be // one or more of the LOAD_* flags defined in net/base/load_flags.h. void SetLoadFlags(int load_flags); int GetLoadFlags() const; void SetReferrer(const std::string& referrer); void <API key>(const std::string& <API key>); void <API key>(const std::string& header_line); void <API key>(HttpRequestHeaders* headers) const; void SetRequestContext(<API key>* <API key>); // Set the URL that should be consulted for the third-party cookie // blocking policy. void <API key>(const GURL& <API key>); // Set the key and data callback that is used when setting the user // data on any URLRequest objects this object creates. void <API key>( const void* key, const URLFetcher::CreateDataCallback& <API key>); void SetStopOnRedirect(bool stop_on_redirect); void <API key>(bool retry); void SetMaxRetriesOn5xx(int max_retries); int GetMaxRetriesOn5xx() const; base::TimeDelta GetBackoffDelay() const; void <API key>(int max_retries); void <API key>( const base::FilePath& file_path, scoped_refptr<base::TaskRunner> file_task_runner); void <API key>( scoped_refptr<base::TaskRunner> file_task_runner); HttpResponseHeaders* GetResponseHeaders() const; HostPortPair GetSocketAddress() const; bool WasFetchedViaProxy() const; const GURL& GetOriginalURL() const; const GURL& GetURL() const; const URLRequestStatus& GetStatus() const; int GetResponseCode() const; const ResponseCookies& GetCookies() const; bool FileErrorOccurred(int* out_error_code) const; // Reports that the received content was malformed (i.e. failed parsing // or validation). This makes the throttling logic that does exponential // back-off when servers are having problems treat the current request as // a failure. Your call to this method will be ignored if your request is // already considered a failure based on the HTTP response code or response // headers. void <API key>(); bool GetResponseAsString(std::string* out_response_string) const; bool <API key>(bool take_ownership, base::FilePath* out_response_path); // Overridden from URLRequest::Delegate: virtual void OnReceivedRedirect(URLRequest* request, const GURL& new_url, bool* defer_redirect) OVERRIDE; virtual void OnResponseStarted(URLRequest* request) OVERRIDE; virtual void OnReadCompleted(URLRequest* request, int bytes_read) OVERRIDE; virtual void <API key>( URLRequest* request, SSLCertRequestInfo* cert_request_info) OVERRIDE; URLFetcherDelegate* delegate() const { return delegate_; } static void CancelAll(); static int GetNumFetcherCores(); static void <API key>(bool enabled); static void <API key>(bool ignored); private: friend class base::<API key><URLFetcherCore>; // How should the response be stored? enum <API key> { STRING, // Default: In a std::string PERMANENT_FILE, // Write to a permanent file. TEMP_FILE, // Write to a temporary file. }; class Registry { public: Registry(); ~Registry(); void AddURLFetcherCore(URLFetcherCore* core); void <API key>(URLFetcherCore* core); void CancelAll(); int size() const { return fetchers_.size(); } private: std::set<URLFetcherCore*> fetchers_; <API key>(Registry); }; virtual ~URLFetcherCore(); // Wrapper functions that allow us to ensure actions happen on the right // thread. void StartOnIOThread(); void StartURLRequest(); void DidInitializeWriter(int result); void <API key>(); void CancelURLRequest(); void <API key>(base::TimeDelta backoff_delay); void <API key>(); void <API key>(); void DidFinishWriting(int result); void <API key>(); // Deletes the request, removes it from the registry, and removes the // destruction observer. void ReleaseRequest(); // Returns the max value of exponential back-off release time for // |original_url_| and |url_|. base::TimeTicks <API key>(); void <API key>(const std::string& data, bool is_last_chunk); // Handles the result of WriteBuffer. void DidWriteBuffer(int result); // Read response bytes from the request. void ReadResponse(); // Drop ownership of any file managed by |file_path_|. void DisownFile(); // Notify Delegate about the progress of upload/download. void <API key>(); void <API key>(int64 current, int64 total); void <API key>(); void <API key>(int64 current, int64 total); void <API key>(int bytes_read); void <API key>( scoped_ptr<std::string> download_data); URLFetcher* fetcher_; // Corresponding fetcher object GURL original_url_; // The URL we were asked to fetch GURL url_; // The URL we eventually wound up at URLFetcher::RequestType request_type_; // What type of request is this? URLRequestStatus status_; // Status of the request URLFetcherDelegate* delegate_; // Object to notify on completion scoped_refptr<base::<API key>> <API key>; // Task runner for the creating thread. scoped_refptr<base::<API key>> <API key>; // Task runner for download file access. scoped_refptr<base::TaskRunner> file_task_runner_; // Task runner for upload file access. scoped_refptr<base::TaskRunner> <API key>; scoped_ptr<URLRequest> request_; // The actual request this wraps int load_flags_; // Flags for the load operation int response_code_; // HTTP status code for the request std::string data_; // Results of the request, when we are // storing the response as a string. scoped_refptr<IOBuffer> buffer_; // Read buffer scoped_refptr<<API key>> <API key>; // Cookie/cache info for the request GURL <API key>; // The first party URL for the request // The user data to add to each newly-created URLRequest. const void* <API key>; URLFetcher::CreateDataCallback <API key>; ResponseCookies cookies_; // Response cookies HttpRequestHeaders <API key>; scoped_refptr<HttpResponseHeaders> response_headers_; bool <API key>; HostPortPair socket_address_; bool upload_content_set_; // SetUploadData has been called std::string upload_content_; // HTTP POST payload base::FilePath upload_file_path_; // Path to file containing POST payload std::string <API key>; // MIME type of POST payload std::string referrer_; // HTTP Referer header value bool is_chunked_upload_; // True if using chunked transfer encoding // Used to determine how long to wait before making a request or doing a // retry. // Both of them can only be accessed on the IO thread. // We need not only the throttler entry for |original_URL|, but also // the one for |url|. For example, consider the case that URL A // redirects to URL B, for which the server returns a 500 // response. In this case, the exponential back-off release time of // URL A won't increase. If we retry without considering the // back-off constraint of URL B, we may send out too many requests // for URL A in a short period of time. // Both of these will be NULL if // URLRequestContext::throttler_manager() is NULL. scoped_refptr<<API key>> <API key>; scoped_refptr<<API key>> <API key>; // True if the URLFetcher has been cancelled. bool was_cancelled_; // Writer object to write response to the destination like file and string. scoped_ptr<<API key>> response_writer_; // If writing results to a file, |file_writer_| will manage creation, // writing, and destruction of that file. // |file_writer_| points to the same object as |response_writer_| when writing // response to a file, otherwise, |file_writer_| is NULL. <API key>* file_writer_; // Where should responses be saved? <API key> <API key>; // Path to the file where the response is written. base::FilePath <API key>; // By default any server-initiated redirects are automatically followed. If // this flag is set to true, however, a redirect will halt the fetch and call // back to to the delegate immediately. bool stop_on_redirect_; // True when we're actually stopped due to a redirect halted by the above. We // use this to ensure that |url_| is set to the redirect destination rather // than the originally-fetched URL. bool <API key>; // If |<API key>| is false, 5xx responses will be // propagated to the observer, if it is true URLFetcher will automatically // re-execute the request, after the back-off delay has expired. // true by default. bool <API key>; // |num_retries_on_5xx_| indicates how many times we've failed to successfully // fetch this URL due to 5xx responses. Once this value exceeds the maximum // number of retries specified by the owner URLFetcher instance, // we'll give up. int num_retries_on_5xx_; // Maximum retries allowed when 5xx responses are received. int max_retries_on_5xx_; // Back-off time delay. 0 by default. base::TimeDelta backoff_delay_; // The number of retries that have been attempted due to ERR_NETWORK_CHANGED. int <API key>; // Maximum retries allowed when the request fails with ERR_NETWORK_CHANGED. // 0 by default. int <API key>; // Timer to poll the progress of uploading for POST and PUT requests. // When crbug.com/119629 is fixed, scoped_ptr is not necessary here. scoped_ptr<base::RepeatingTimer<URLFetcherCore> > <API key>; // Number of bytes sent so far. int64 <API key>; // Number of bytes received so far. int64 <API key>; // Total expected bytes to receive (-1 if it cannot be determined). int64 <API key>; // TODO(willchan): Get rid of this after debugging crbug.com/90971. base::debug::StackTrace stack_trace_; static base::LazyInstance<Registry> g_registry; <API key>(URLFetcherCore); }; } // namespace net #endif // <API key>
id: adaptors-kafka title: Pulsar adaptor for Apache Kafka sidebar_label: "Kafka client wrapper" original_id: adaptors-kafka Pulsar provides an easy option for applications that are currently written using the [Apache Kafka](http://kafka.apache.org) Java client API. ## Using the Pulsar Kafka compatibility wrapper In an existing application, change the regular Kafka client dependency and replace it with the Pulsar Kafka wrapper. Remove the following dependency in `pom.xml`: xml <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>0.10.2.1</version> </dependency> Then include this dependency for the Pulsar Kafka wrapper: xml <dependency> <groupId>org.apache.pulsar</groupId> <artifactId>pulsar-client-kafka</artifactId> <version>@pulsar:version@</version> </dependency> With the new dependency, the existing code works without any changes. You need to adjust the configuration, and make sure it points the producers and consumers to Pulsar service rather than Kafka, and uses a particular Pulsar topic. ## Using the Pulsar Kafka compatibility wrapper together with existing kafka client When migrating from Kafka to Pulsar, the application might use the original kafka client and the pulsar kafka wrapper together during migration. You should consider using the unshaded pulsar kafka client wrapper. xml <dependency> <groupId>org.apache.pulsar</groupId> <artifactId><API key></artifactId> <version>@pulsar:version@</version> </dependency> When using this dependency, construct producers using `org.apache.kafka.clients.producer.PulsarKafkaProducer` instead of `org.apache.kafka.clients.producer.KafkaProducer` and `org.apache.kafka.clients.producer.PulsarKafkaConsumer` for consumers. ## Producer example java // Topic needs to be a regular Pulsar topic String topic = "persistent://public/default/my-topic"; Properties props = new Properties(); // Point to a Pulsar service props.put("bootstrap.servers", "pulsar://localhost:6650"); props.put("key.serializer", IntegerSerializer.class.getName()); props.put("value.serializer", StringSerializer.class.getName()); Producer<Integer, String> producer = new KafkaProducer(props); for (int i = 0; i < 10; i++) { producer.send(new ProducerRecord<Integer, String>(topic, i, "hello-" + i)); log.info("Message {} sent successfully", i); } producer.close(); ## Consumer example java String topic = "persistent://public/default/my-topic"; Properties props = new Properties(); // Point to a Pulsar service props.put("bootstrap.servers", "pulsar://localhost:6650"); props.put("group.id", "<API key>"); props.put("enable.auto.commit", "false"); props.put("key.deserializer", IntegerDeserializer.class.getName()); props.put("value.deserializer", StringDeserializer.class.getName()); Consumer<Integer, String> consumer = new KafkaConsumer(props); consumer.subscribe(Arrays.asList(topic)); while (true) { ConsumerRecords<Integer, String> records = consumer.poll(100); records.forEach(record -> { log.info("Received record: {}", record); }); // Commit last offset consumer.commitSync(); } ## Complete Examples You can find the complete producer and consumer examples [here](https://github.com/apache/pulsar/tree/master/<API key>/<API key>/src/test/java/org/apache/pulsar/client/kafka/compat/examples). ## Compatibility matrix Currently the Pulsar Kafka wrapper supports most of the operations offered by the Kafka API. # Producer APIs: | Producer Method | Supported | Notes | |: | `Future<RecordMetadata> send(ProducerRecord<K, V> record)` | Yes | | | `Future<RecordMetadata> send(ProducerRecord<K, V> record, Callback callback)` | Yes | | | `void flush()` | Yes | | | `List<PartitionInfo> partitionsFor(String topic)` | No | | | `Map<MetricName, ? extends Metric> metrics()` | No | | | `void close()` | Yes | | | `void close(long timeout, TimeUnit unit)` | Yes | | Properties: | Config property | Supported | Notes | |: | `acks` | Ignored | Durability and quorum writes are configured at the namespace level | | `auto.offset.reset` | Yes | Will have a default value of `latest` if user does not give specific setting. | | `batch.size` | Ignored | | | `bootstrap.servers` | Yes | | | `buffer.memory` | Ignored | | | `client.id` | Ignored | | | `compression.type` | Yes | Allows `gzip` and `lz4`. No `snappy`. | | `connections.max.idle.ms` | Yes | Only support up to 2,147,483,647,000(Integer.MAX_VALUE * 1000) ms of idle time| | `interceptor.classes` | Yes | | | `key.serializer` | Yes | | | `linger.ms` | Yes | Controls the group commit time when batching messages | | `max.block.ms` | Ignored | | | `max.in.flight.requests.per.connection` | Ignored | In Pulsar ordering is maintained even with multiple requests in flight | | `max.request.size` | Ignored | | | `metric.reporters` | Ignored | | | `metrics.num.samples` | Ignored | | | `metrics.sample.window.ms` | Ignored | | | `partitioner.class` | Yes | | | `receive.buffer.bytes` | Ignored | | | `reconnect.backoff.ms` | Ignored | | | `request.timeout.ms` | Ignored | | | `retries` | Ignored | Pulsar client retries with exponential backoff until the send timeout expires. | | `send.buffer.bytes` | Ignored | | | `timeout.ms` | Yes | | | `value.serializer` | Yes | | # Consumer The following table lists consumer APIs. | Consumer Method | Supported | Notes | |: | `Set<TopicPartition> assignment()` | No | | | `Set<String> subscription()` | Yes | | | `void subscribe(Collection<String> topics)` | Yes | | | `void subscribe(Collection<String> topics, <API key> callback)` | No | | | `void assign(Collection<TopicPartition> partitions)` | No | | | `void subscribe(Pattern pattern, <API key> callback)` | No | | | `void unsubscribe()` | Yes | | | `ConsumerRecords<K, V> poll(long timeoutMillis)` | Yes | | | `void commitSync()` | Yes | | | `void commitSync(Map<TopicPartition, OffsetAndMetadata> offsets)` | Yes | | | `void commitAsync()` | Yes | | | `void commitAsync(<API key> callback)` | Yes | | | `void commitAsync(Map<TopicPartition, OffsetAndMetadata> offsets, <API key> callback)` | Yes | | | `void seek(TopicPartition partition, long offset)` | Yes | | | `void seekToBeginning(Collection<TopicPartition> partitions)` | Yes | | | `void seekToEnd(Collection<TopicPartition> partitions)` | Yes | | | `long position(TopicPartition partition)` | Yes | | | `OffsetAndMetadata committed(TopicPartition partition)` | Yes | | | `Map<MetricName, ? extends Metric> metrics()` | No | | | `List<PartitionInfo> partitionsFor(String topic)` | No | | | `Map<String, List<PartitionInfo>> listTopics()` | No | | | `Set<TopicPartition> paused()` | No | | | `void pause(Collection<TopicPartition> partitions)` | No | | | `void resume(Collection<TopicPartition> partitions)` | No | | | `Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch)` | No | | | `Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions)` | No | | | `Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions)` | No | | | `void close()` | Yes | | | `void close(long timeout, TimeUnit unit)` | Yes | | | `void wakeup()` | No | | Properties: | Config property | Supported | Notes | |: | `group.id` | Yes | Maps to a Pulsar subscription name | | `max.poll.records` | Yes | | | `max.poll.interval.ms` | Ignored | Messages are "pushed" from broker | | `session.timeout.ms` | Ignored | | | `heartbeat.interval.ms` | Ignored | | | `bootstrap.servers` | Yes | Needs to point to a single Pulsar service URL | | `enable.auto.commit` | Yes | | | `auto.commit.interval.ms` | Ignored | With auto-commit, acks are sent immediately to broker | | `partition.assignment.strategy` | Ignored | | | `auto.offset.reset` | Yes | Only support earliest and latest. | | `fetch.min.bytes` | Ignored | | | `fetch.max.bytes` | Ignored | | | `fetch.max.wait.ms` | Ignored | | | `interceptor.classes` | Yes | | | `metadata.max.age.ms` | Ignored | | | `max.partition.fetch.bytes` | Ignored | | | `send.buffer.bytes` | Ignored | | | `receive.buffer.bytes` | Ignored | | | `client.id` | Ignored | | ## Customize Pulsar configurations You can configure Pulsar authentication provider directly from the Kafka properties. Pulsar client properties | Config property | Default | Notes | |: | [`pulsar.authentication.class`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>.apache.pulsar.client.api.Authentication-) | | Configure to auth provider. For example, `org.apache.pulsar.client.impl.auth.AuthenticationTls`.| | [`pulsar.authentication.params.map`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>.lang.String-java.util.Map-) | | Map which represents parameters for the <API key>. | | [`pulsar.authentication.params.string`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>.lang.String-java.lang.String-) | | String which represents parameters for the <API key>, for example, `key1:val1,key2:val2`. | | [`pulsar.use.tls`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#setUseTls-boolean-) | `false` | Enable TLS transport encryption. | | [`pulsar.tls.trust.certs.file.path`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>.lang.String-) | | Path for the TLS trust certificate store. | | [`pulsar.tls.allow.insecure.connection`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>-) | `false` | Accept self-signed certificates from brokers. | | [`pulsar.operation.timeout.ms`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>.util.concurrent.TimeUnit-) | `30000` | General operations timeout. | | [`pulsar.stats.interval.seconds`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>.util.concurrent.TimeUnit-) | `60` | Pulsar client lib stats printing interval. | | [`pulsar.num.io.threads`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#setIoThreads-int-) | `1` | The number of Netty IO threads to use. | | [`pulsar.connections.per.broker`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>-) | `1` | The maximum number of connection to each broker. | | [`pulsar.use.tcp.nodelay`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>-) | `true` | TCP no-delay. | | [`pulsar.concurrent.lookup.requests`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>-) | `50000` | The maximum number of concurrent topic lookups. | | [`pulsar.max.number.rejected.request.per.connection`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientConfiguration.html#<API key>-) | `50` | The threshold of errors to forcefully close a connection. | | [`pulsar.keepalive.interval.ms`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ClientBuilder.html#<API key>.util.concurrent.TimeUnit-)| `30000` | Keep alive interval for each <API key>. | Pulsar producer properties | Config property | Default | Notes | |: | [`pulsar.producer.name`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>.lang.String-) | | Specify the producer name. | | [`pulsar.producer.initial.sequence.id`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>-) | | Specify baseline for sequence ID of this producer. | | [`pulsar.producer.max.pending.messages`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>-) | `1000` | Set the maximum size of the message queue pending to receive an acknowledgment from the broker. | | [`pulsar.producer.max.pending.messages.across.partitions`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>-) | `50000` | Set the maximum number of pending messages across all the partitions. | | [`pulsar.producer.batching.enabled`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>-) | `true` | Control whether automatic batching of messages is enabled for the producer. | | [`pulsar.producer.batching.max.messages`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>-) | `1000` | The maximum number of messages in a batch. | Pulsar consumer Properties | Config property | Default | Notes | |: | [`pulsar.consumer.name`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>.lang.String-) | | Specify the consumer name. | | [`pulsar.consumer.receiver.queue.size`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>-) | 1000 | Set the size of the consumer receiver queue. | | [`pulsar.consumer.acknowledgments.group.time.millis`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ConsumerBuilder.html#<API key>.util.concurrent.TimeUnit-) | 100 | Set the maximum amount of group time for consumers to send the acknowledgments to the broker. | | [`pulsar.consumer.total.receiver.queue.size.across.partitions`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/<API key>.html#<API key>-) | 50000 | Set the maximum size of the total receiver queue across partitions. | | [`pulsar.consumer.subscription.topics.mode`](http://pulsar.apache.org/api/client/org/apache/pulsar/client/api/ConsumerBuilder.html#<API key>-) | PersistentOnly | Set the subscription topic mode for consumers. |
THREE.MeshFaceMaterial = function () { this.toString = function () { return 'THREE.MeshFaceMaterial'; }; };
"""Fixtures for pywemo.""" import asyncio from unittest.mock import create_autospec, patch import pytest import pywemo from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC from homeassistant.components.wemo.const import DOMAIN from homeassistant.helpers import entity_registry as er from homeassistant.setup import <API key> MOCK_HOST = "127.0.0.1" MOCK_PORT = 50000 MOCK_NAME = "WemoDeviceName" MOCK_SERIAL_NUMBER = "WemoSerialNumber" <API key> = "WeMo_WW_2.00.XXXXX.PVT-OWRT" @pytest.fixture(name="pywemo_model") def <API key>(): """Fixture containing a pywemo class name used by <API key>.""" return "LightSwitch" @pytest.fixture(name="pywemo_registry", autouse=True) async def <API key>(): """Fixture for <API key> instances.""" registry = create_autospec(pywemo.<API key>, instance=True) registry.callbacks = {} registry.semaphore = asyncio.Semaphore(value=0) def on_func(device, type_filter, callback): registry.callbacks[device.name] = callback registry.semaphore.release() registry.on.side_effect = on_func registry.is_subscribed.return_value = False with patch("pywemo.<API key>", return_value=registry): yield registry @pytest.fixture(name="<API key>", autouse=True) def <API key>(): """Fixture for the DiscoveryResponder instance.""" with patch("pywemo.ssdp.DiscoveryResponder", autospec=True): yield @pytest.fixture(name="pywemo_device") def <API key>(pywemo_registry, pywemo_model): """Fixture for WeMoDevice instances.""" cls = getattr(pywemo, pywemo_model) device = create_autospec(cls, instance=True) device.host = MOCK_HOST device.port = MOCK_PORT device.name = MOCK_NAME device.serialnumber = MOCK_SERIAL_NUMBER device.model_name = pywemo_model.replace("LongPress", "") device.udn = f"uuid:{device.model_name}-1_0-{device.serialnumber}" device.firmware_version = <API key> device.get_state.return_value = 0 # Default to Off device.supports_long_press.return_value = cls.supports_long_press() url = f"http://{MOCK_HOST}:{MOCK_PORT}/setup.xml" with patch("pywemo.<API key>", return_value=url), patch( "pywemo.discovery.<API key>", return_value=device ): yield device @pytest.fixture(name="wemo_entity_suffix") def <API key>(): """Fixture to select a specific entity for wemo_entity.""" return "" @pytest.fixture(name="wemo_entity") async def <API key>(hass, pywemo_device, wemo_entity_suffix): """Fixture for a Wemo entity in hass.""" assert await <API key>( hass, DOMAIN, { DOMAIN: { CONF_DISCOVERY: False, CONF_STATIC: [f"{MOCK_HOST}:{MOCK_PORT}"], }, }, ) await hass.<API key>() entity_registry = er.async_get(hass) for entry in entity_registry.entities.values(): if entry.entity_id.endswith(wemo_entity_suffix): return entry return None
/ [tests/cases/compiler/<API key>.ts] / [package.json] { "name": "@foo/bar", "version": "1.2.3" } / [index.d.ts] export class C { private x: number; } / [index.d.ts] import { C } from "@foo/bar"; export const o: C; / [use.d.ts] import { C } from "./index"; export function use(o: C): void; / [index.d.ts] export class C { private x: number; } / [package.json] { "name": "@foo/bar", "version": "1.2.3" } / [index.ts] import { use } from "@foo/bar/use"; import { o } from "a"; use(o); / [index.js] "use strict"; exports.__esModule = true; var use_1 = require("@foo/bar/use"); var a_1 = require("a"); (0, use_1.use)(a_1.o);
<!DOCTYPE html> <html devsite> <head> <meta name="project_path" value="/web/tools/workbox/_project.yaml" /> <meta name="book_path" value="/web/tools/workbox/_book.yaml" /> <meta name="gtm_var" data-key="docType" data-value="reference"> <title>Namespace: backgroundSync</title> <link href="jsdoc.css" rel="stylesheet"> </head> <body> <div id="<API key>"> <div id="jsdoc-content"> <div id="<API key>"> <div id="jsdoc-main" role="main"> <header class="page-header"> <h1><small><a href="workbox.html">workbox</a>.<wbr></small><span class="symbol-name">backgroundSync</span></h1> <div class="<API key>"><span class="label label-kind"><small>namespace</small></span>&nbsp;&nbsp;&nbsp;<span class="label label-static"><small>static</small></span></div> <div class="<API key>"> <span class="label label-kind"><small>Version</small></span> &nbsp;&nbsp;&nbsp; <span class="label label-version"><small>v3.0.0-alpha.3</small></span> </div> </header> <section> <h2>Classes</h2> <section id='members-links'> <h3 class="class-list"><a href="workbox.backgroundSync.Plugin.html">Plugin</a></h3> <p>A class implementing the <code>fetchDidFail</code> lifecycle callback. This makes it easier to add failed requests to a background sync Queue.</p> <h3 class="class-list"><a href="workbox.backgroundSync.Queue.html">Queue</a></h3> <p>A class to manage storing failed requests in IndexedDB and retrying them later. All parts of the storing and replaying process are observable via callbacks. </p> </section> </section> </div> </div> <nav id="jsdoc-toc-nav" role="navigation"></nav> </div> </div> </body> </html>
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/language/v1/language_service.proto namespace Google\Cloud\Language\V1; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * Represents the smallest syntactic building block of the text. * * Generated from protobuf message <code>google.cloud.language.v1.Token</code> */ class Token extends \Google\Protobuf\Internal\Message { /** * The token text. * * Generated from protobuf field <code>.google.cloud.language.v1.TextSpan text = 1;</code> */ private $text = null; /** * Parts of speech tag for this token. * * Generated from protobuf field <code>.google.cloud.language.v1.PartOfSpeech part_of_speech = 2;</code> */ private $part_of_speech = null; /** * Dependency tree parse for this token. * * Generated from protobuf field <code>.google.cloud.language.v1.DependencyEdge dependency_edge = 3;</code> */ private $dependency_edge = null; private $lemma = ''; public function __construct($data = NULL) { \GPBMetadata\Google\Cloud\Language\V1\LanguageService::initOnce(); parent::__construct($data); } /** * The token text. * * Generated from protobuf field <code>.google.cloud.language.v1.TextSpan text = 1;</code> * @return \Google\Cloud\Language\V1\TextSpan|null */ public function getText() { return $this->text; } public function hasText() { return isset($this->text); } public function clearText() { unset($this->text); } /** * The token text. * * Generated from protobuf field <code>.google.cloud.language.v1.TextSpan text = 1;</code> * @param \Google\Cloud\Language\V1\TextSpan $var * @return $this */ public function setText($var) { GPBUtil::checkMessage($var, \Google\Cloud\Language\V1\TextSpan::class); $this->text = $var; return $this; } /** * Parts of speech tag for this token. * * Generated from protobuf field <code>.google.cloud.language.v1.PartOfSpeech part_of_speech = 2;</code> * @return \Google\Cloud\Language\V1\PartOfSpeech|null */ public function getPartOfSpeech() { return $this->part_of_speech; } public function hasPartOfSpeech() { return isset($this->part_of_speech); } public function clearPartOfSpeech() { unset($this->part_of_speech); } /** * Parts of speech tag for this token. * * Generated from protobuf field <code>.google.cloud.language.v1.PartOfSpeech part_of_speech = 2;</code> * @param \Google\Cloud\Language\V1\PartOfSpeech $var * @return $this */ public function setPartOfSpeech($var) { GPBUtil::checkMessage($var, \Google\Cloud\Language\V1\PartOfSpeech::class); $this->part_of_speech = $var; return $this; } /** * Dependency tree parse for this token. * * Generated from protobuf field <code>.google.cloud.language.v1.DependencyEdge dependency_edge = 3;</code> * @return \Google\Cloud\Language\V1\DependencyEdge|null */ public function getDependencyEdge() { return $this->dependency_edge; } public function hasDependencyEdge() { return isset($this->dependency_edge); } public function clearDependencyEdge() { unset($this->dependency_edge); } /** * Dependency tree parse for this token. * * Generated from protobuf field <code>.google.cloud.language.v1.DependencyEdge dependency_edge = 3;</code> * @param \Google\Cloud\Language\V1\DependencyEdge $var * @return $this */ public function setDependencyEdge($var) { GPBUtil::checkMessage($var, \Google\Cloud\Language\V1\DependencyEdge::class); $this->dependency_edge = $var; return $this; } public function getLemma() { return $this->lemma; } public function setLemma($var) { GPBUtil::checkString($var, True); $this->lemma = $var; return $this; } }
// This source file is part of the Swift.org open source project // This file defines routines relating to abstraction patterns. // working in concert with the Clang importer. #define DEBUG_TYPE "libsil" #include "swift/SIL/TypeLowering.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/<API key>.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/PrettyPrinter.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" using namespace swift; using namespace swift::Lowering; AbstractionPattern TypeConverter::<API key>(AbstractStorageDecl *decl) { if (auto var = dyn_cast<VarDecl>(decl)) { return <API key>(var); } else { return <API key>(cast<SubscriptDecl>(decl)); } } AbstractionPattern TypeConverter::<API key>(SubscriptDecl *decl) { CanGenericSignature genericSig; if (auto sig = decl-><API key>()) genericSig = sig-><API key>(); return AbstractionPattern(genericSig, decl-><API key>() ->getCanonicalType()); } AbstractionPattern TypeConverter::<API key>(SubscriptDecl *decl) { CanGenericSignature genericSig; if (auto sig = decl-><API key>()) genericSig = sig-><API key>(); auto indicesTy = decl-><API key>(); auto indicesCanTy = indicesTy->getCanonicalType(genericSig, *decl->getParentModule()); return AbstractionPattern(genericSig, indicesCanTy); } static const clang::Type *getClangType(const clang::Decl *decl) { if (auto valueDecl = dyn_cast<clang::ValueDecl>(decl)) { return valueDecl->getType().getTypePtr(); } // This should *really* be a ValueDecl. return cast<clang::ObjCPropertyDecl>(decl)->getType().getTypePtr(); } AbstractionPattern TypeConverter::<API key>(VarDecl *var) { CanGenericSignature genericSig; if (auto sig = var->getDeclContext()-><API key>()) genericSig = sig-><API key>(); CanType swiftType = var->getInterfaceType()->getCanonicalType(); if (auto inout = dyn_cast<InOutType>(swiftType)) swiftType = inout.getObjectType(); if (auto clangDecl = var->getClangDecl()) { auto clangType = getClangType(clangDecl); auto contextType = var->getDeclContext()->mapTypeIntoContext(swiftType); swiftType = <API key>( AbstractionPattern(genericSig, swiftType, clangType), contextType, <API key>::CFunctionPointer, TypeConverter::ForMemory)->getCanonicalType(); return AbstractionPattern(genericSig, swiftType, clangType); } return AbstractionPattern(genericSig, swiftType); } AbstractionPattern TypeConverter::<API key>(EnumElementDecl *decl) { assert(decl-><API key>()); assert(!decl->hasClangNode()); // This cannot be implemented correctly for Optional.Some. assert(decl->getParentEnum()-><API key>() == OTK_None && "Optional.Some does not have a unique abstraction pattern because " "optionals are re-abstracted"); CanGenericSignature genericSig; if (auto sig = decl->getParentEnum()-><API key>()) genericSig = sig-><API key>(); return AbstractionPattern(genericSig, decl-><API key>() ->getCanonicalType()); } AbstractionPattern::<API key> AbstractionPattern::<API key>::encode( const Optional<<API key>> &foreignError) { <API key> errorInfo; if (foreignError.hasValue()) { errorInfo = <API key>(foreignError-><API key>(), foreignError-><API key>(), foreignError-><API key>()); } return errorInfo; } AbstractionPattern AbstractionPattern::getObjCMethod(CanType origType, const clang::ObjCMethodDecl *method, const Optional<<API key>> &foreignError) { auto errorInfo = <API key>::encode(foreignError); return getObjCMethod(origType, method, errorInfo); } AbstractionPattern AbstractionPattern::<API key>(CanType origType, const clang::ObjCMethodDecl *method, const Optional<<API key>> &foreignError) { auto errorInfo = <API key>::encode(foreignError); return <API key>(origType, method, errorInfo); } AbstractionPattern AbstractionPattern::<API key>(CanType origType, const <API key> *function) { auto clangFn = cast<clang::ValueDecl>(function->getClangDecl()); return <API key>(origType, clangFn->getType().getTypePtr(), function-><API key>()); } AbstractionPattern AbstractionPattern::getOptional(AbstractionPattern object, OptionalTypeKind optionalKind) { switch (object.getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::Tuple: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: llvm_unreachable("cannot add optionality to non-type abstraction"); case Kind::Opaque: return AbstractionPattern::getOpaque(); case Kind::ClangType: return AbstractionPattern(object.getGenericSignature(), OptionalType::get(optionalKind, object.getType()) ->getCanonicalType(), object.getClangType()); case Kind::Type: return AbstractionPattern(object.getGenericSignature(), OptionalType::get(optionalKind, object.getType()) ->getCanonicalType()); case Kind::Discard: return AbstractionPattern::getDiscard(object.getGenericSignature(), OptionalType::get(optionalKind, object.getType()) ->getCanonicalType()); } llvm_unreachable("bad kind"); } bool AbstractionPattern::matchesTuple(CanTupleType substType) { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: return false; case Kind::Opaque: return true; case Kind::Tuple: return <API key>() == substType->getNumElements(); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ClangType: case Kind::Type: case Kind::Discard: if (isTypeParameter()) return true; auto tuple = dyn_cast<TupleType>(getType()); return (tuple && tuple->getNumElements() == substType->getNumElements()); } llvm_unreachable("bad kind"); } static const clang::FunctionType * <API key>(const clang::Type *clangType) { if (auto ptrTy = clangType->getAs<clang::PointerType>()) { clangType = ptrTy->getPointeeType().getTypePtr(); } else if (auto blockTy = clangType->getAs<clang::BlockPointerType>()) { clangType = blockTy->getPointeeType().getTypePtr(); } return clangType->castAs<clang::FunctionType>(); } static const clang::Type *<API key>(const clang::Type *ty, unsigned index) { // TODO: adjust for error type parameter. // If we're asking about parameters, we'd better have a FunctionProtoType. auto fnType = <API key>(ty)->castAs<clang::FunctionProtoType>(); assert(index < fnType->getNumParams()); return fnType->getParamType(index).getTypePtr(); } static const clang::Type *<API key>(const clang::Type *ty, unsigned index) { return ty-><API key>()->getElementType().getTypePtr(); } static bool isVoidLike(CanType type) { return (type->isVoid() || (isa<TupleType>(type) && cast<TupleType>(type)->getNumElements() == 1 && cast<TupleType>(type).getElementType(0)->isVoid())); } static CanType <API key>(CanType type, unsigned index) { if (auto tupleTy = dyn_cast<TupleType>(type)) return tupleTy.getElementType(index); assert(index == 0); return type; } AbstractionPattern AbstractionPattern::getTupleElementType(unsigned index) const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: llvm_unreachable("function types are not tuples"); case Kind::Opaque: return *this; case Kind::Tuple: assert(index < <API key>()); return OrigTupleElements[index]; case Kind::ClangType: return AbstractionPattern(getGenericSignature(), <API key>(getType(), index), <API key>(getClangType(), index)); case Kind::Discard: llvm_unreachable("operation not needed on discarded abstractions yet"); case Kind::Type: if (isTypeParameter()) return AbstractionPattern::getOpaque(); return AbstractionPattern(getGenericSignature(), <API key>(getType(), index)); case Kind::<API key>: { // Handle the (label: ()) param used by functions imported as labeled // nullary initializers. if (isVoidLike(getType())) return AbstractionPattern(getType()->getASTContext().TheEmptyTupleType); return AbstractionPattern(getGenericSignature(), <API key>(getType(), index), <API key>(getClangType(), index)); } case Kind::<API key>: { auto swiftEltType = <API key>(getType(), index); auto method = getObjCMethod(); auto errorInfo = <API key>(); // If we're asking for something after the error parameter, slide // the parameter index up by one. auto paramIndex = index; if (errorInfo.hasErrorParameter()) { auto errorParamIndex = errorInfo.<API key>(); if (errorInfo.<API key>()) { if (paramIndex == errorParamIndex) { assert(isVoidLike(swiftEltType)); (void)&isVoidLike; return AbstractionPattern(swiftEltType); } } else { if (paramIndex >= errorParamIndex) { paramIndex++; } } } return AbstractionPattern(getGenericSignature(), swiftEltType, method->parameters()[paramIndex]->getType().getTypePtr()); } case Kind::<API key>: { // Jump over the self parameter in the Clang type. unsigned clangIndex = index; auto memberStatus = <API key>(); if (memberStatus.isInstance() && clangIndex >= memberStatus.getSelfIndex()) ++clangIndex; return AbstractionPattern(getGenericSignature(), <API key>(getType(), index), <API key>(getClangType(), clangIndex)); } case Kind::<API key>: { auto tupleType = cast<TupleType>(getType()); assert(tupleType->getNumElements() == 2); assert(index < 2); auto swiftEltType = tupleType.getElementType(index); if (index != 0) { return <API key>(swiftEltType); } // Otherwise, we're talking about the formal parameter clause. return <API key>(swiftEltType); } } llvm_unreachable("bad kind"); } Return a pattern corresponding to the 'self' parameter of the given Objective-C method. AbstractionPattern AbstractionPattern::<API key>(CanType selfType) const { // Just use id for the receiver type. If this is ever auto clangSelfType = getObjCMethod()->getASTContext().getObjCIdType().getTypePtr(); return AbstractionPattern(<API key>(), selfType, clangSelfType); } Return a pattern corresponding to the 'self' parameter of the given C function imported as a method. AbstractionPattern AbstractionPattern::<API key>(CanType selfType) const { auto memberStatus = <API key>(); if (memberStatus.isInstance()) { // Use the clang type for the receiver type. If this is ever auto clangSelfType = <API key>(getClangType(),memberStatus.getSelfIndex()); return AbstractionPattern(<API key>(), selfType, clangSelfType); } // The formal metatype parameter to a C function imported as a static method // is dropped on the floor. Leave it untransformed. return AbstractionPattern::getDiscard( <API key>(), selfType); } Return a pattern corresponding to the formal method parameters of the current C function imported as a method. AbstractionPattern AbstractionPattern:: <API key>(CanType paramType) const { auto sig = <API key>(); auto clangType = getClangType(); // Nullary methods still take a formal () parameter clause. // There's no corresponding Clang type for that. if (isVoidLike(paramType)) return AbstractionPattern(paramType); // If we imported as a tuple type, construct the special // <API key> abstraction pattern. if (isa<TupleType>(paramType)) { return <API key>(sig, paramType, clangType, <API key>()); } // Otherwise, we imported a single parameter. // Get the non-self parameter from the Clang type. unsigned paramIndex = 0; auto selfIndex = <API key>(); if (selfIndex.isInstance() && selfIndex.getSelfIndex() == 0) paramIndex = 1; return AbstractionPattern(sig, paramType, <API key>(clangType, paramIndex)); } Return a pattern corresponding to the formal parameters of the current Objective-C method. AbstractionPattern AbstractionPattern::<API key>(CanType inputType) const { auto signature = <API key>(); auto method = getObjCMethod(); auto errorInfo = <API key>(); // Nullary methods still take a formal () parameter clause. // There's no corresponding Clang type for that. if (method->parameters().empty() || (method->parameters().size() == 1 && errorInfo.hasErrorParameter())) { // Imported initializers also sometimes get "withFooBar: ()" clauses. assert(isVoidLike(inputType)); return AbstractionPattern(inputType); } // If we imported as a tuple type, construct the special // <API key> abstraction pattern. if (isa<TupleType>(inputType)) { // This assertion gets messed up by variadic methods that we've // imported as non-variadic. assert(method->isVariadic() || method->parameters().size() == cast<TupleType>(inputType)->getNumElements() + unsigned(errorInfo.<API key>())); return <API key>(signature, inputType, method, errorInfo); } // Otherwise, we must have imported a single parameter. // But we might also have a foreign error. // If we don't, we must have a single source parameter. if (!errorInfo.hasErrorParameter()) { assert(method->parameters().size() == 1); return AbstractionPattern(signature, inputType, method->parameters()[0]->getType().getTypePtr()); } // Otherwise, we must have two; pick the one that isn't the foreign error. assert(method->parameters().size() == 2); unsigned errorIndex = errorInfo.<API key>(); assert(errorIndex < 2); unsigned paramIndex = (errorIndex == 0 ? 1 : 0); return AbstractionPattern(signature, inputType, method->parameters()[paramIndex]->getType().getTypePtr()); } AbstractionPattern AbstractionPattern::transformType( llvm::function_ref<CanType(CanType)> transform) const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::Tuple: return *this; case Kind::Opaque: return getOpaque(); case Kind::<API key>: return <API key>(getGenericSignature(), transform(getType()), getObjCMethod(), <API key>()); case Kind::<API key>: return <API key>(transform(getType()), getObjCMethod(), <API key>()); case Kind::<API key>: return <API key>(getGenericSignature(), transform(getType()), getClangType(), <API key>()); case Kind::<API key>: return <API key>(transform(getType()), getClangType(), <API key>()); case Kind::ObjCMethodType: return getObjCMethod(transform(getType()), getObjCMethod(), <API key>()); case Kind::ClangType: return AbstractionPattern(getGenericSignature(), transform(getType()), getClangType()); case Kind::Type: return AbstractionPattern(getGenericSignature(), transform(getType())); case Kind::Discard: return AbstractionPattern::getDiscard(getGenericSignature(), transform(getType())); case Kind::<API key>: return <API key>(getGenericSignature(), transform(getType()), getObjCMethod(), <API key>()); // In both of the following cases, if the transform makes it no // longer a tuple type, we need to change kinds. case Kind::<API key>: { auto newType = transform(getType()); if (isa<TupleType>(newType)) { return <API key>(getGenericSignature(), newType, getClangType()); } else { assert(getNumTupleElements() == 1); return AbstractionPattern(getGenericSignature(), newType, <API key>(getClangType(), 0)); } } case Kind::<API key>: { auto newType = transform(getType()); if (isa<TupleType>(newType)) { return <API key>(getGenericSignature(), newType, getObjCMethod(), <API key>()); } else { assert(getNumTupleElements() == 1); return AbstractionPattern(getGenericSignature(), newType, getObjCMethod()->parameters()[0]->getType().getTypePtr()); } } case Kind::<API key>: { auto newType = transform(getType()); if (isa<TupleType>(newType)) { return <API key>(getGenericSignature(), newType, getClangType(), <API key>()); } } } llvm_unreachable("bad kind"); } static CanType dropLastElement(CanType type) { auto elts = cast<TupleType>(type)->getElements().drop_back(); return TupleType::get(elts, type->getASTContext())->getCanonicalType(); } AbstractionPattern AbstractionPattern::<API key>() const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::Tuple: { auto n = <API key>(); return getTuple(llvm::makeArrayRef(OrigTupleElements, n - 1)); } case Kind::Opaque: return getOpaque(); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: llvm_unreachable("not a tuple type"); case Kind::ClangType: llvm_unreachable("dropping last element of imported array?"); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: llvm_unreachable("operation is not needed on method abstraction patterns"); case Kind::Type: if (isTypeParameter()) return AbstractionPattern::getOpaque(); return AbstractionPattern(getGenericSignature(), dropLastElement(getType())); case Kind::Discard: llvm_unreachable("don't need to drop element on discarded abstractions " "yet"); // In both of the following cases, if the transform makes it no // longer a tuple type, we need to change kinds. case Kind::<API key>: { auto newType = dropLastElement(getType()); if (isa<TupleType>(newType)) { return <API key>(getGenericSignature(), newType, getClangType()); } else { assert(getNumTupleElements() == 2); return AbstractionPattern(getGenericSignature(), newType, <API key>(getClangType(), 0)); } } } llvm_unreachable("bad kind"); } AbstractionPattern AbstractionPattern::<API key>() const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::Tuple: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: llvm_unreachable("abstraction pattern for lvalue cannot be tuple"); case Kind::Opaque: return *this; case Kind::Type: return AbstractionPattern(getGenericSignature(), getType().<API key>()); case Kind::Discard: return AbstractionPattern::getDiscard(getGenericSignature(), getType().<API key>()); case Kind::ClangType: return AbstractionPattern(getGenericSignature(), getType().<API key>(), getClangType()); } llvm_unreachable("bad kind"); } static CanType getResultType(CanType type) { return cast<AnyFunctionType>(type).getResult(); } AbstractionPattern AbstractionPattern::<API key>() const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::Tuple: llvm_unreachable("abstraction pattern for tuple cannot be function"); case Kind::Opaque: return *this; case Kind::Type: if (isTypeParameter()) return AbstractionPattern::getOpaque(); return AbstractionPattern(<API key>(), getResultType(getType())); case Kind::Discard: llvm_unreachable("don't need to discard function abstractions yet"); case Kind::ClangType: case Kind::<API key>: { auto clangFunctionType = <API key>(getClangType()); return AbstractionPattern(<API key>(), getResultType(getType()), clangFunctionType->getReturnType().getTypePtr()); } case Kind::<API key>: return <API key>( <API key>(), getResultType(getType()), getObjCMethod(), <API key>()); case Kind::<API key>: return <API key>( <API key>(), getResultType(getType()), getClangType(), <API key>()); case Kind::<API key>: case Kind::ObjCMethodType: return AbstractionPattern(<API key>(), getResultType(getType()), getObjCMethod()->getReturnType().getTypePtr()); } llvm_unreachable("bad kind"); } AbstractionPattern AbstractionPattern::<API key>() const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::Tuple: llvm_unreachable("abstraction pattern for tuple cannot be function"); case Kind::Opaque: return *this; case Kind::Type: if (isTypeParameter()) return AbstractionPattern::getOpaque(); return AbstractionPattern(<API key>(), cast<AnyFunctionType>(getType()).getInput()); case Kind::Discard: llvm_unreachable("don't need to discard function abstractions yet"); case Kind::ClangType: { // Preserve the Clang type in the resulting abstraction pattern. auto inputType = cast<AnyFunctionType>(getType()).getInput(); if (isa<TupleType>(inputType)) { return <API key>( <API key>(), inputType, getClangType()); } else { return AbstractionPattern(<API key>(), inputType, <API key>(getClangType(), 0)); } } case Kind::<API key>: return <API key>( cast<AnyFunctionType>(getType()).getInput()); case Kind::<API key>: return <API key>( cast<AnyFunctionType>(getType()).getInput()); case Kind::<API key>: return <API key>( cast<AnyFunctionType>(getType()).getInput()); case Kind::<API key>: return <API key>( cast<AnyFunctionType>(getType()).getInput()); case Kind::ObjCMethodType: { // Preserve the Clang type in the resulting abstraction pattern. auto inputType = cast<AnyFunctionType>(getType()).getInput(); assert(isa<TupleType>(inputType)); // always at least ((), SelfType) return <API key>(<API key>(), inputType, getObjCMethod(), <API key>()); } } llvm_unreachable("bad kind"); } static CanType <API key>(CanType type) { auto objectType = type.<API key>(); assert(objectType && "type was not optional"); return objectType; } AbstractionPattern AbstractionPattern::<API key>() const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::Tuple: case Kind::<API key>: llvm_unreachable("pattern for function or tuple cannot be for optional"); case Kind::Opaque: return *this; case Kind::Type: if (isTypeParameter()) return AbstractionPattern::getOpaque(); return AbstractionPattern(getGenericSignature(), ::<API key>(getType())); case Kind::Discard: return AbstractionPattern::getDiscard(getGenericSignature(), ::<API key>(getType())); case Kind::ClangType: // This is not reflected in clang types. return AbstractionPattern(getGenericSignature(), ::<API key>(getType()), getClangType()); } llvm_unreachable("bad kind"); } AbstractionPattern AbstractionPattern::<API key>() const { switch (getKind()) { case Kind::Invalid: llvm_unreachable("querying invalid abstraction pattern!"); case Kind::Opaque: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::Tuple: case Kind::<API key>: return *this; case Kind::Type: return AbstractionPattern(getGenericSignature(), getType().<API key>()); case Kind::Discard: return AbstractionPattern::getDiscard(getGenericSignature(), getType().<API key>()); case Kind::ClangType: // This is not reflected in clang types. return AbstractionPattern(getGenericSignature(), getType().<API key>(), getClangType()); } llvm_unreachable("bad kind"); } void AbstractionPattern::dump() const { print(llvm::errs()); llvm::errs() << "\n"; } void AbstractionPattern::print(raw_ostream &out) const { switch (getKind()) { case Kind::Invalid: out << "AP::Invalid"; return; case Kind::Opaque: out << "AP::Opaque"; return; case Kind::Type: case Kind::Discard: out << (getKind() == Kind::Type ? "AP::Type" : getKind() == Kind::Discard ? "AP::Discard" : "<<UNHANDLED CASE>>"); if (auto sig = getGenericSignature()) { sig->print(out); } out << '('; getType().dump(out); out << ')'; return; case Kind::Tuple: out << "AP::Tuple("; for (unsigned i = 0, e = getNumTupleElements(); i != e; ++i) { if (i != 0) out << ", "; getTupleElementType(i).print(out); } out << ")"; return; case Kind::ClangType: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: out << (getKind() == Kind::ClangType ? "AP::ClangType(" : getKind() == Kind::<API key> ? "AP::<API key>(" : getKind() == Kind::<API key> ? "AP::<API key>(" : getKind() == Kind::<API key> ? "AP::<API key>(" : getKind() == Kind::<API key> ? "AP::<API key>(" : "<<UNHANDLED CASE>>("); getType().dump(out); out << ", "; // It would be better to use print, but we need a PrintingPolicy // for that, for which we need a clang LangOptions, and... ugh. clang::QualType(getClangType(), 0).dump(); if (<API key>()) { out << ", member="; auto status = <API key>(); if (status.isInstance()) { out << "instance, self=" << status.getSelfIndex(); } else if (status.isStatic()) { out << "static"; } } out << ")"; return; case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::<API key>: case Kind::ObjCMethodType: out << (getKind() == Kind::ObjCMethodType ? "AP::ObjCMethodType(" : getKind() == Kind::<API key> ? "AP::<API key>(" : getKind() == Kind::<API key> ? "AP::<API key>(" : getKind() == Kind::<API key> ? "AP::<API key>(" : "AP::<API key>("); getType().dump(out); auto errorInfo = <API key>(); if (errorInfo.hasValue()) { if (errorInfo.hasErrorParameter()) out << ", errorParameter=" << errorInfo.<API key>(); if (errorInfo.<API key>()) out << ", replacedWithVoid"; if (errorInfo.<API key>()) out << ", <API key>"; } out << ", "; getObjCMethod()->dump(out); out << ")"; return; } llvm_unreachable("bad kind"); }
// file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::Show; trait Something { fn yay<T: Show>(_: Option<Self>, thing: &[T]) -> String { } } struct X { data: u32 } impl Something for X { fn yay<T: Str>(_:Option<X>, thing: &[T]) -> String { //~^ ERROR in method `yay`, type parameter 0 requires bound `core::str::Str`, which is not required format!("{:s}", thing[0]) } } fn main() { let arr = &["one", "two", "three"]; println!("{}", Something::yay(None::<X>, arr)); }
<?php namespace oasis\names\specification\ubl\schema\xsd\<API key>; /** * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:<API key> * @xmlType URIType * @xmlName URI * @var oasis\names\specification\ubl\schema\xsd\<API key>\URI */ class URI extends URIType { } // end class URI
describe ManageIQ::Providers::Openstack::CloudManager::Vm do describe "vm actions" do let(:ems) { FactoryGirl.create(:ems_openstack) } let(:tenant) { FactoryGirl.create(:<API key>, :<API key> => ems) } let(:vm) do FactoryGirl.create(:vm_openstack, :<API key> => ems, :name => 'test', :ems_ref => 'one_id', :cloud_tenant => tenant) end let(:handle) do double.tap do |handle| allow(ems).to receive(:connect).with({}).and_return(handle) end end before do handle end context "#live_migrate" do it "live migrates with default options" do expect(handle).to receive(:live_migrate_server).with(vm.ems_ref, nil, false, false) vm.live_migrate expect(vm.power_state).to eq 'migrating' end it "live migrates with special options" do expect(handle).to receive(:live_migrate_server).with(vm.ems_ref, 'host_1.localdomain', true, true) vm.live_migrate(:hostname => 'host_1.localdomain', :disk_over_commit => true, :block_migration => true) expect(vm.power_state).to eq 'migrating' end it "checks live migration is_available?" do expect(vm.<API key>?).to eq true end end context "evacuate" do it "evacuates with default options" do expect(handle).to receive(:evacuate_server).with(vm.ems_ref, nil, true, nil) vm.evacuate expect(vm.power_state).to eq 'migrating' end it "evacuates with special options" do expect(handle).to receive(:evacuate_server).with(vm.ems_ref, 'host_1.localdomain', false, 'blah') vm.evacuate(:hostname => 'host_1.localdomain', :on_shared_storage => false, :admin_password => 'blah') expect(vm.power_state).to eq 'migrating' end it "evacuates with special options" do expect(handle).to receive(:evacuate_server).with(vm.ems_ref, 'host_1.localdomain', true, nil) vm.evacuate(:hostname => 'host_1.localdomain', :on_shared_storage => true) expect(vm.power_state).to eq 'migrating' end it "returns true for querying vm if the evacuate operation is supported" do expect(vm.supports_evacuate?).to eq true end end context "associate floating ip" do it "associates with floating ip" do service = double allow(ems).to receive(:connect).and_return(service) expect(service).to receive(:associate_address).with(vm.ems_ref, '10.10.10.10') vm.<API key>('10.10.10.10') end it "checks <API key> is_available? when floating ips are available" do expect(vm.cloud_tenant).to receive(:floating_ips).and_return([1]) # fake a floating ip being available expect(vm.<API key>?).to eq true end it "checks <API key> is_available? when floating ips are not available" do expect(vm.cloud_tenant).to receive(:floating_ips).and_return([]) expect(vm.<API key>?).to eq false end end context "disassociate floating ip" do it "disassociates from floating ip" do service = double allow(ems).to receive(:connect).and_return(service) expect(service).to receive(:<API key>).with(vm.ems_ref, '10.10.10.10') vm.<API key>('10.10.10.10') end it "checks <API key> is_available? when floating ips are associated with the instance" do expect(vm).to receive(:floating_ips).and_return([1]) # fake a floating ip being associated expect(vm.<API key>?).to eq true end it "checks <API key> is_available? when no floating ips are associated with the instance" do expect(vm).to receive(:floating_ips).and_return([]) expect(vm.<API key>?).to eq false end end end context "#is_available?" do let(:ems) { FactoryGirl.create(:ems_openstack) } let(:vm) { FactoryGirl.create(:vm_openstack, :<API key> => ems) } let(:power_state_on) { "ACTIVE" } let(:<API key>) { "SUSPENDED" } context("with :start") do let(:state) { :start } include_examples "Vm operation is available when not powered on" end context("with :stop") do let(:state) { :stop } include_examples "Vm operation is available when powered on" end context("with :suspend") do let(:state) { :suspend } include_examples "Vm operation is available when powered on" end context("with :pause") do let(:state) { :pause } include_examples "Vm operation is available when powered on" end context("with :shutdown_guest") do let(:state) { :shutdown_guest } include_examples "Vm operation is not available" end context("with :standby_guest") do let(:state) { :standby_guest } include_examples "Vm operation is not available" end context("with :reboot_guest") do let(:state) { :reboot_guest } include_examples "Vm operation is available when powered on" end context("with :reset") do let(:state) { :reset } include_examples "Vm operation is available when powered on" end end context "when detroyed" do let(:ems) { FactoryGirl.create(:ems_openstack) } let(:provider_object) do double("<API key>", :destroy => nil).as_null_object end let(:vm) { FactoryGirl.create(:vm_openstack, :<API key> => ems) } it "sets the raw_power_state and not state" do expect(vm).to receive(:<API key>).and_yield(provider_object) vm.raw_destroy expect(vm.raw_power_state).to eq("DELETED") expect(vm.state).to eq("archived") end end context "when resized" do let(:ems) { FactoryGirl.create(:ems_openstack) } let(:cloud_tenant) { FactoryGirl.create(:cloud_tenant) } let(:vm) { FactoryGirl.create(:vm_openstack, :<API key> => ems, :cloud_tenant => cloud_tenant) } let(:flavor) { FactoryGirl.create(:flavor_openstack, :ems_ref => '2') } it "initiate resize process" do service = double allow(ems).to receive(:connect).and_return(service) expect(vm.supports_resize?).to be_truthy expect(vm.<API key>).to be false expect(service).to receive(:resize_server).with(vm.ems_ref, flavor.ems_ref) expect(MiqQueue).to receive(:put) vm.resize(flavor) end it 'confirm resize' do vm.raw_power_state = 'VERIFY_RESIZE' service = double allow(ems).to receive(:connect).and_return(service) expect(vm.supports_resize?).to be_falsey expect(vm.<API key>).to be true expect(service).to receive(:<API key>).with(vm.ems_ref) vm.resize_confirm end it 'revert resize' do vm.raw_power_state = 'VERIFY_RESIZE' service = double allow(ems).to receive(:connect).and_return(service) expect(vm.supports_resize?).to be_falsey expect(vm.<API key>).to be true expect(service).to receive(:<API key>).with(vm.ems_ref) vm.resize_revert end end end
package com.ntobjectives.hackazon.activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.ntobjectives.hackazon.R; import com.ntobjectives.hackazon.adapter.OrdersListAdapter; import com.ntobjectives.hackazon.model.Order; import com.ntobjectives.hackazon.network.<API key>; import com.ntobjectives.hackazon.view.OrderListItemView; import com.octo.android.robospice.persistence.DurationInMillis; import com.octo.android.robospice.persistence.exception.SpiceException; public class OrdersFragment extends Fragment { public static final String TAG = OrdersFragment.class.getSimpleName(); private ListView ordersListView; private View loadingView; //private SimpleCursorAdapter adapter; private View view; @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); //getActivity().<API key>(Window.<API key>); super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView"); if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) { parent.removeView(view); } } try { view = inflater.inflate(R.layout.orders_fragment, container, false); } catch (InflateException ignored) { } return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { Log.d(TAG, "onActivityCreated"); super.onActivityCreated(savedInstanceState); ordersListView = (ListView) getActivity().findViewById(R.id.listview_orders); loadingView = getActivity().findViewById(R.id.loading_layout); loadingView.setVisibility(View.VISIBLE); getActivity().<API key>(false); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); <API key> req = new <API key>(); String lastRequestCacheKey = req.createCacheKey(); getActivity().<API key>(true); ((<API key>) getActivity()).getSpiceManager().execute(req, lastRequestCacheKey, DurationInMillis.ONE_MINUTE, new <API key>(getActivity().<API key>())); ordersListView.<API key>(new OnItemClickListener()); } private void <API key>(Order.OrdersResponse response) { <API key> act = (<API key>) getActivity(); OrdersListAdapter orderListAdapter = new OrdersListAdapter(getActivity(), act.<API key>(), response.data); ordersListView.setAdapter(orderListAdapter); loadingView.setVisibility(View.GONE); ordersListView.setVisibility(View.VISIBLE); } public final class <API key> extends com.ntobjectives.hackazon.network.RequestListener<Order.OrdersResponse> { protected <API key>(Context context) { super(context); } @Override public void onFailure(SpiceException spiceException) { if (getActivity() != null) { getActivity().<API key>(false); Toast.makeText(OrdersFragment.this.getActivity(), "failure", Toast.LENGTH_SHORT).show(); } } @Override public void onSuccess(Order.OrdersResponse response) { if (getActivity() != null) { getActivity().<API key>(false); <API key>(response); //Toast.makeText(OrdersFragment.this.getActivity(), "success", Toast.LENGTH_SHORT).show(); } } } public final class OnItemClickListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { OrderListItemView v = (OrderListItemView) view; Log.d(TAG, Integer.toString(v.getData().id)); Intent intent = new Intent(getActivity(), OrderActivity.class); intent.putExtra("id", v.getData().id); startActivity(intent); } } }
"""The tests for the manual Alarm Control Panel component.""" from datetime import timedelta import unittest from unittest.mock import patch from homeassistant.setup import setup_component from homeassistant.const import ( <API key>, <API key>, <API key>, <API key>, STATE_ALARM_PENDING, <API key>) from homeassistant.components import alarm_control_panel import homeassistant.util.dt as dt_util from tests.common import fire_time_changed, <API key> CODE = 'HELLO_CODE' class <API key>(unittest.TestCase): """Test the manual alarm module.""" def setUp(self): # pylint: disable=invalid-name """Setup things to be run when tests are started.""" self.hass = <API key>() def tearDown(self): # pylint: disable=invalid-name """Stop down everything that was started.""" self.hass.stop() def <API key>(self): """Test arm home method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 0, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_home(self.hass, CODE) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test arm home method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 1, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_home(self.hass, CODE, entity_id) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Attempt to arm home without a valid code.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 1, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_home(self.hass, CODE + '2') self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test arm home method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 0, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_away(self.hass, CODE, entity_id) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test arm home method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 1, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Attempt to arm away without a valid code.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 1, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_away(self.hass, CODE + '2') self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test arm night method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 0, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_night(self.hass, CODE) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test arm night method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 1, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_night(self.hass, CODE, entity_id) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Attempt to night home without a valid code.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'code': CODE, 'pending_time': 1, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_arm_night(self.hass, CODE + '2') self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test triggering when no pending submitted method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'trigger_time': 1, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=60) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test arm home method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'pending_time': 2, 'trigger_time': 3, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_trigger(self.hass) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test disarm after trigger.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'trigger_time': 5, 'pending_time': 0, '<API key>': True }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test disarming while pending state.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'trigger_time': 5, '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_trigger(self.hass) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_disarm(self.hass, entity_id=entity_id) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state) def <API key>(self): """Test disarming while code is invalid.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'pending_time': 5, 'code': CODE + '2', '<API key>': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(<API key>, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_trigger(self.hass) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) alarm_control_panel.alarm_disarm(self.hass, entity_id=entity_id) self.hass.block_till_done() self.assertEqual(STATE_ALARM_PENDING, self.hass.states.get(entity_id).state) future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' 'dt_util.utcnow'), return_value=future): fire_time_changed(self.hass, future) self.hass.block_till_done() self.assertEqual(<API key>, self.hass.states.get(entity_id).state)
// tree. package layers import ( "errors" "fmt" "github.com/google/gopacket" ) // EnumMetadata keeps track of a set of metadata for each enumeration value // for protocol enumerations. type EnumMetadata struct { // DecodeWith is the decoder to use to decode this protocol's data. DecodeWith gopacket.Decoder // Name is the name of the enumeration value. Name string // LayerType is the layer type implied by the given enum. LayerType gopacket.LayerType } // errorFunc returns a decoder that spits out a specific error message. func errorFunc(msg string) gopacket.Decoder { var e = errors.New(msg) return gopacket.DecodeFunc(func([]byte, gopacket.PacketBuilder) error { return e }) } // EthernetType is an enumeration of ethernet type values, and acts as a decoder // for any type it supports. type EthernetType uint16 const ( // EthernetTypeLLC is not an actual ethernet type. It is instead a // placeholder we use in Ethernet frames that use the 802.3 standard of // srcmac|dstmac|length|LLC instead of srcmac|dstmac|ethertype. EthernetTypeLLC EthernetType = 0 EthernetTypeIPv4 EthernetType = 0x0800 EthernetTypeARP EthernetType = 0x0806 EthernetTypeIPv6 EthernetType = 0x86DD <API key> EthernetType = 0x2000 <API key> EthernetType = 0x01a2 <API key> EthernetType = 0x6558 EthernetTypeDot1Q EthernetType = 0x8100 <API key> EthernetType = 0x8863 <API key> EthernetType = 0x8864 <API key> EthernetType = 0x8847 <API key> EthernetType = 0x8848 EthernetTypeEAPOL EthernetType = 0x888e EthernetTypeQinQ EthernetType = 0x88a8 <API key> EthernetType = 0x88cc <API key> EthernetType = 0x9000 ) // IPProtocol is an enumeration of IP protocol values, and acts as a decoder // for any type it supports. type IPProtocol uint8 const ( <API key> IPProtocol = 0 IPProtocolICMPv4 IPProtocol = 1 IPProtocolIGMP IPProtocol = 2 IPProtocolIPv4 IPProtocol = 4 IPProtocolTCP IPProtocol = 6 IPProtocolUDP IPProtocol = 17 IPProtocolRUDP IPProtocol = 27 IPProtocolIPv6 IPProtocol = 41 <API key> IPProtocol = 43 <API key> IPProtocol = 44 IPProtocolGRE IPProtocol = 47 IPProtocolESP IPProtocol = 50 IPProtocolAH IPProtocol = 51 IPProtocolICMPv6 IPProtocol = 58 <API key> IPProtocol = 59 <API key> IPProtocol = 60 IPProtocolOSPF IPProtocol = 89 IPProtocolIPIP IPProtocol = 94 IPProtocolEtherIP IPProtocol = 97 IPProtocolVRRP IPProtocol = 112 IPProtocolSCTP IPProtocol = 132 IPProtocolUDPLite IPProtocol = 136 IPProtocolMPLSInIP IPProtocol = 137 ) // LinkType is an enumeration of link types, and acts as a decoder for any // link type it supports. type LinkType uint8 const ( LinkTypeNull LinkType = 0 LinkTypeEthernet LinkType = 1 LinkTypeAX25 LinkType = 3 LinkTypeTokenRing LinkType = 6 LinkTypeArcNet LinkType = 7 LinkTypeSLIP LinkType = 8 LinkTypePPP LinkType = 9 LinkTypeFDDI LinkType = 10 LinkTypePPP_HDLC LinkType = 50 LinkTypePPPEthernet LinkType = 51 LinkTypeATM_RFC1483 LinkType = 100 LinkTypeRaw LinkType = 101 LinkTypeC_HDLC LinkType = 104 LinkTypeIEEE802_11 LinkType = 105 LinkTypeFRelay LinkType = 107 LinkTypeLoop LinkType = 108 LinkTypeLinuxSLL LinkType = 113 LinkTypeLTalk LinkType = 114 LinkTypePFLog LinkType = 117 LinkTypePrismHeader LinkType = 119 LinkTypeIPOverFC LinkType = 122 LinkTypeSunATM LinkType = 123 <API key> LinkType = 127 LinkTypeARCNetLinux LinkType = 129 LinkTypeIPOver1394 LinkType = 138 LinkTypeMTP2Phdr LinkType = 139 LinkTypeMTP2 LinkType = 140 LinkTypeMTP3 LinkType = 141 LinkTypeSCCP LinkType = 142 LinkTypeDOCSIS LinkType = 143 LinkTypeLinuxIRDA LinkType = 144 LinkTypeLinuxLAPD LinkType = 177 LinkTypeLinuxUSB LinkType = 220 LinkTypeIPv4 LinkType = 228 LinkTypeIPv6 LinkType = 229 ) type PPPoECode uint8 const ( PPPoECodePADI PPPoECode = 0x09 PPPoECodePADO PPPoECode = 0x07 PPPoECodePADR PPPoECode = 0x19 PPPoECodePADS PPPoECode = 0x65 PPPoECodePADT PPPoECode = 0xA7 PPPoECodeSession PPPoECode = 0x00 ) // PPPType is an enumeration of PPP type values, and acts as a decoder for any // type it supports. type PPPType uint16 const ( PPPTypeIPv4 PPPType = 0x0021 PPPTypeIPv6 PPPType = 0x0057 PPPTypeMPLSUnicast PPPType = 0x0281 <API key> PPPType = 0x0283 ) // SCTPChunkType is an enumeration of chunk types inside SCTP packets. type SCTPChunkType uint8 const ( SCTPChunkTypeData SCTPChunkType = 0 SCTPChunkTypeInit SCTPChunkType = 1 <API key> SCTPChunkType = 2 SCTPChunkTypeSack SCTPChunkType = 3 <API key> SCTPChunkType = 4 <API key> SCTPChunkType = 5 SCTPChunkTypeAbort SCTPChunkType = 6 <API key> SCTPChunkType = 7 <API key> SCTPChunkType = 8 SCTPChunkTypeError SCTPChunkType = 9 <API key> SCTPChunkType = 10 <API key> SCTPChunkType = 11 <API key> SCTPChunkType = 14 ) // FDDIFrameControl is an enumeration of FDDI frame control bytes. type FDDIFrameControl uint8 const ( FDDIFrameControlLLC FDDIFrameControl = 0x50 ) // EAPOLType is an enumeration of EAPOL packet types. type EAPOLType uint8 const ( EAPOLTypeEAP EAPOLType = 0 EAPOLTypeStart EAPOLType = 1 EAPOLTypeLogOff EAPOLType = 2 EAPOLTypeKey EAPOLType = 3 EAPOLTypeASFAlert EAPOLType = 4 ) // ProtocolFamily is the set of values defined as PF_* in sys/socket.h type ProtocolFamily uint8 const ( ProtocolFamilyIPv4 ProtocolFamily = 2 // BSDs use different values for INET6... glory be. These values taken from // tcpdump 4.3.0. <API key> ProtocolFamily = 24 <API key> ProtocolFamily = 28 <API key> ProtocolFamily = 30 <API key> ProtocolFamily = 10 ) // Dot11Type is a combination of IEEE 802.11 frame's Type and Subtype fields. // By combining these two fields together into a single type, we're able to // provide a String function that correctly displays the subtype given the // top-level type. // If you just care about the top-level type, use the MainType function. type Dot11Type uint8 // MainType strips the subtype information from the given type, // returning just the overarching type (Mgmt, Ctrl, Data, Reserved). func (d Dot11Type) MainType() Dot11Type { return d & dot11TypeMask } func (d Dot11Type) QOS() bool { return d&dot11QOSMask == <API key> } const ( Dot11TypeMgmt Dot11Type = 0x00 Dot11TypeCtrl Dot11Type = 0x01 Dot11TypeData Dot11Type = 0x02 Dot11TypeReserved Dot11Type = 0x03 dot11TypeMask = 0x03 dot11QOSMask = 0x23 // The following are type/subtype conglomerations. // Management <API key> Dot11Type = 0x00 <API key> Dot11Type = 0x04 <API key> Dot11Type = 0x08 <API key> Dot11Type = 0x0c <API key> Dot11Type = 0x10 <API key> Dot11Type = 0x14 <API key> Dot11Type = 0x18 Dot11TypeMgmtBeacon Dot11Type = 0x20 Dot11TypeMgmtATIM Dot11Type = 0x24 <API key> Dot11Type = 0x28 <API key> Dot11Type = 0x2c <API key> Dot11Type = 0x30 Dot11TypeMgmtAction Dot11Type = 0x34 <API key> Dot11Type = 0x38 // Control <API key> Dot11Type = 0x1d <API key> Dot11Type = 0x21 <API key> Dot11Type = 0x25 <API key> Dot11Type = 0x29 Dot11TypeCtrlRTS Dot11Type = 0x2d Dot11TypeCtrlCTS Dot11Type = 0x31 Dot11TypeCtrlAck Dot11Type = 0x35 Dot11TypeCtrlCFEnd Dot11Type = 0x39 <API key> Dot11Type = 0x3d // Data Dot11TypeDataCFAck Dot11Type = 0x06 Dot11TypeDataCFPoll Dot11Type = 0x0a <API key> Dot11Type = 0x0e Dot11TypeDataNull Dot11Type = 0x12 <API key> Dot11Type = 0x16 <API key> Dot11Type = 0x1a <API key> Dot11Type = 0x1e <API key> Dot11Type = 0x22 <API key> Dot11Type = 0x26 <API key> Dot11Type = 0x2a <API key> Dot11Type = 0x2e <API key> Dot11Type = 0x32 <API key> Dot11Type = 0x3a <API key> Dot11Type = 0x3e ) // Decode a raw v4 or v6 IP packet. func decodeIPv4or6(data []byte, p gopacket.PacketBuilder) error { version := data[0] >> 4 switch version { case 4: return decodeIPv4(data, p) case 6: return decodeIPv6(data, p) } return fmt.Errorf("Invalid IP packet version %v", version) } func initActualTypeData() { // Each of the XXXTypeMetadata arrays contains mappings of how to handle enum // values for various enum types in gopacket/layers. // enums_generated.go. // So, <API key>[2] contains information on how to handle EthernetType // 2, including which name to give it and which decoder to use to decode // packet data of that type. These arrays are filled by default with all of the // protocols gopacket/layers knows how to handle, but users of the library can // add new decoders or override existing ones. For example, if you write a better // TCP decoder, you can override IPProtocolMetadata[IPProtocolTCP].DecodeWith // with your new decoder, and all gopacket/layers decoding will use your new // decoder whenever they encounter that IPProtocol. // Here we link up all enumerations with their respective names and decoders. <API key>[EthernetTypeLLC] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeLLC), Name: "LLC", LayerType: LayerTypeLLC} <API key>[EthernetTypeIPv4] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv4), Name: "IPv4", LayerType: LayerTypeIPv4} <API key>[EthernetTypeIPv6] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6", LayerType: LayerTypeIPv6} <API key>[EthernetTypeARP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeARP), Name: "ARP", LayerType: LayerTypeARP} <API key>[EthernetTypeDot1Q] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot1Q), Name: "Dot1Q", LayerType: LayerTypeDot1Q} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodePPPoE), Name: "PPPoEDiscovery", LayerType: LayerTypePPPoE} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodePPPoE), Name: "PPPoESession", LayerType: LayerTypePPPoE} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeEthernetCTP), Name: "EthernetCTP", LayerType: <API key>} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CiscoDiscovery", LayerType: <API key>} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "NortelDiscovery", LayerType: <API key>} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "LinkLayerDiscovery", LayerType: <API key>} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeMPLS), Name: "MPLSUnicast", LayerType: LayerTypeMPLS} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeMPLS), Name: "MPLSMulticast", LayerType: LayerTypeMPLS} <API key>[EthernetTypeEAPOL] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeEAPOL), Name: "EAPOL", LayerType: LayerTypeEAPOL} <API key>[EthernetTypeQinQ] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot1Q), Name: "Dot1Q", LayerType: LayerTypeDot1Q} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeEthernet), Name: "<API key>", LayerType: LayerTypeEthernet} IPProtocolMetadata[IPProtocolIPv4] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv4), Name: "IPv4", LayerType: LayerTypeIPv4} IPProtocolMetadata[IPProtocolTCP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeTCP), Name: "TCP", LayerType: LayerTypeTCP} IPProtocolMetadata[IPProtocolUDP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeUDP), Name: "UDP", LayerType: LayerTypeUDP} IPProtocolMetadata[IPProtocolICMPv4] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeICMPv4), Name: "ICMPv4", LayerType: LayerTypeICMPv4} IPProtocolMetadata[IPProtocolICMPv6] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeICMPv6), Name: "ICMPv6", LayerType: LayerTypeICMPv6} IPProtocolMetadata[IPProtocolSCTP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTP), Name: "SCTP", LayerType: LayerTypeSCTP} IPProtocolMetadata[IPProtocolIPv6] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6", LayerType: LayerTypeIPv6} IPProtocolMetadata[IPProtocolIPIP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv4), Name: "IPv4", LayerType: LayerTypeIPv4} IPProtocolMetadata[IPProtocolEtherIP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeEtherIP), Name: "EtherIP", LayerType: LayerTypeEtherIP} IPProtocolMetadata[IPProtocolRUDP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeRUDP), Name: "RUDP", LayerType: LayerTypeRUDP} IPProtocolMetadata[IPProtocolGRE] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeGRE), Name: "GRE", LayerType: LayerTypeGRE} IPProtocolMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6HopByHop), Name: "IPv6HopByHop", LayerType: <API key>} IPProtocolMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6Routing), Name: "IPv6Routing", LayerType: <API key>} IPProtocolMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6Fragment), Name: "IPv6Fragment", LayerType: <API key>} IPProtocolMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "IPv6Destination", LayerType: <API key>} IPProtocolMetadata[IPProtocolOSPF] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeOSPF), Name: "OSPF", LayerType: LayerTypeOSPF} IPProtocolMetadata[IPProtocolAH] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPSecAH), Name: "IPSecAH", LayerType: LayerTypeIPSecAH} IPProtocolMetadata[IPProtocolESP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPSecESP), Name: "IPSecESP", LayerType: LayerTypeIPSecESP} IPProtocolMetadata[IPProtocolUDPLite] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeUDPLite), Name: "UDPLite", LayerType: LayerTypeUDPLite} IPProtocolMetadata[IPProtocolMPLSInIP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeMPLS), Name: "MPLS", LayerType: LayerTypeMPLS} IPProtocolMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodePayload, Name: "NoNextHeader", LayerType: gopacket.LayerTypePayload} IPProtocolMetadata[IPProtocolIGMP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIGMP), Name: "IGMP", LayerType: LayerTypeIGMP} IPProtocolMetadata[IPProtocolVRRP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeVRRP), Name: "VRRP", LayerType: LayerTypeVRRP} <API key>[SCTPChunkTypeData] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPData), Name: "Data"} <API key>[SCTPChunkTypeInit] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPInit), Name: "Init"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPInit), Name: "InitAck"} <API key>[SCTPChunkTypeSack] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPSack), Name: "Sack"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPHeartbeat), Name: "Heartbeat"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPHeartbeat), Name: "HeartbeatAck"} <API key>[SCTPChunkTypeAbort] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPError), Name: "Abort"} <API key>[SCTPChunkTypeError] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPError), Name: "Error"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeSCTPShutdown), Name: "Shutdown"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "ShutdownAck"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CookieEcho"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CookieAck"} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "ShutdownComplete"} PPPTypeMetadata[PPPTypeIPv4] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv4), Name: "IPv4"} PPPTypeMetadata[PPPTypeIPv6] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6"} PPPTypeMetadata[PPPTypeMPLSUnicast] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeMPLS), Name: "MPLSUnicast"} PPPTypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeMPLS), Name: "MPLSMulticast"} PPPoECodeMetadata[PPPoECodeSession] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodePPP), Name: "PPP"} LinkTypeMetadata[LinkTypeEthernet] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeEthernet), Name: "Ethernet"} LinkTypeMetadata[LinkTypePPP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodePPP), Name: "PPP"} LinkTypeMetadata[LinkTypeFDDI] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeFDDI), Name: "FDDI"} LinkTypeMetadata[LinkTypeNull] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeLoopback), Name: "Null"} LinkTypeMetadata[LinkTypeIEEE802_11] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11), Name: "Dot11"} LinkTypeMetadata[LinkTypeLoop] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeLoopback), Name: "Loop"} LinkTypeMetadata[LinkTypeIEEE802_11] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11), Name: "802.11"} LinkTypeMetadata[LinkTypeRaw] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv4or6), Name: "Raw"} LinkTypeMetadata[LinkTypePFLog] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodePFLog), Name: "PFLog"} LinkTypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeRadioTap), Name: "RadioTap"} LinkTypeMetadata[LinkTypeLinuxUSB] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeUSB), Name: "USB"} LinkTypeMetadata[LinkTypeLinuxSLL] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeLinuxSLL), Name: "Linux SLL"} LinkTypeMetadata[LinkTypePrismHeader] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodePrismHeader), Name: "Prism"} <API key>[FDDIFrameControlLLC] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeLLC), Name: "LLC"} EAPOLTypeMetadata[EAPOLTypeEAP] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeEAP), Name: "EAP", LayerType: LayerTypeEAP} EAPOLTypeMetadata[EAPOLTypeKey] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeEAPOLKey), Name: "EAPOLKey", LayerType: LayerTypeEAPOLKey} <API key>[ProtocolFamilyIPv4] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv4), Name: "IPv4", LayerType: LayerTypeIPv4} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6", LayerType: LayerTypeIPv6} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6", LayerType: LayerTypeIPv6} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6", LayerType: LayerTypeIPv6} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeIPv6), Name: "IPv6", LayerType: LayerTypeIPv6} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtAssociationReq", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtAssociationResp", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "<API key>", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "<API key>", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtProbeReq", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtProbeResp", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "<API key>", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeMgmtBeacon] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtBeacon", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeMgmtATIM] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11MgmtATIM), Name: "MgmtATIM", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtDisassociation", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtAuthentication", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "<API key>", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeMgmtAction] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtAction", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "MgmtActionNoAck", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeCtrl] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11Ctrl), Name: "Ctrl", LayerType: LayerTypeDot11Ctrl} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11Ctrl), Name: "CtrlWrapper", LayerType: LayerTypeDot11Ctrl} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CtrlBlockAckReq", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CtrlBlockAck", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CtrlPowersavePoll", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeCtrlRTS] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11CtrlRTS), Name: "CtrlRTS", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeCtrlCTS] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11CtrlCTS), Name: "CtrlCTS", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeCtrlAck] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11CtrlAck), Name: "CtrlAck", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeCtrlCFEnd] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CtrlCFEnd", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "CtrlCFEndAck", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeData] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11Data), Name: "Data", LayerType: LayerTypeDot11Data} Dot11TypeMetadata[Dot11TypeDataCFAck] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataCFAck", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeDataCFPoll] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataCFPoll", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataCFAckPoll", LayerType: <API key>} Dot11TypeMetadata[Dot11TypeDataNull] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeDot11DataNull), Name: "DataNull", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataCFAckNoData", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataCFPollNoData", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataCFAckPollNoData", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataQOSData", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataQOSDataCFAck", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataQOSDataCFPoll", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "<API key>", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataQOSNull", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "DataQOSCFPollNoData", LayerType: <API key>} Dot11TypeMetadata[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(<API key>), Name: "<API key>", LayerType: <API key>} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeUSBInterrupt), Name: "Interrupt", LayerType: <API key>} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeUSBControl), Name: "Control", LayerType: LayerTypeUSBControl} <API key>[<API key>] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(decodeUSBBulk), Name: "Bulk", LayerType: LayerTypeUSBBulk} }
description: How do we connect docker containers within and across hosts ? keywords: docker, network, IPv6 title: IPv6 with Docker The information in this section explains IPv6 with the Docker default bridge. This is a `bridge` network named `bridge` created automatically when you install Docker. As we are [running out of IPv4 addresses](http://en.wikipedia.org/wiki/<API key>) the IETF has standardized an IPv4 successor, [Internet Protocol Version 6](http://en.wikipedia.org/wiki/IPv6) , in [RFC 2460](https: reside on layer 3 of the [OSI model](http://en.wikipedia.org/wiki/OSI_model). ## How IPv6 works on Docker By default, the Docker server configures the container network for IPv4 only. You can enable IPv4/IPv6 dualstack support by running the Docker daemon with the `--ipv6` flag. Docker will set up the bridge `docker0` with the IPv6 [link-local address](http://en.wikipedia.org/wiki/Link-local_address) `fe80::1`. By default, containers that are created will only get a link-local IPv6 address. To assign globally routable IPv6 addresses to your containers you have to specify an IPv6 subnet to pick the addresses from. Set the IPv6 subnet via the `--fixed-cidr-v6` parameter when starting Docker daemon: dockerd --ipv6 --fixed-cidr-v6="2001:db8:1::/64" The subnet for Docker containers should at least have a size of `/80`. This way an IPv6 address can end with the container's MAC address and you prevent NDP neighbor cache invalidation issues in the Docker layer. With the `--fixed-cidr-v6` parameter set Docker will add a new route to the routing table. Further IPv6 routing will be enabled (you may prevent this by starting dockerd with `--ip-forward=false`): $ ip -6 route add 2001:db8:1::/64 dev docker0 $ sysctl net.ipv6.conf.default.forwarding=1 $ sysctl net.ipv6.conf.all.forwarding=1 All traffic to the subnet `2001:db8:1::/64` will now be routed via the `docker0` interface. Be aware that IPv6 forwarding may interfere with your existing IPv6 configuration: If you are using Router Advertisements to get IPv6 settings for your host's interfaces you should set `accept_ra` to `2`. Otherwise IPv6 enabled forwarding will result in rejecting Router Advertisements. E.g., if you want to configure `eth0` via Router Advertisements you should set: $ sysctl net.ipv6.conf.eth0.accept_ra=2 ![](images/<API key>.svg) Every new container will get an IPv6 address from the defined subnet. Further a default route will be added on `eth0` in the container via the address specified by the daemon option `--default-gateway-v6` if present, otherwise via `fe80::1`: docker run -it ubuntu bash -c "ip -6 addr show dev eth0; ip -6 route show" 15: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 inet6 2001:db8:1:0:0:242:ac11:3/64 scope global valid_lft forever preferred_lft forever inet6 fe80::42:acff:fe11:3/64 scope link valid_lft forever preferred_lft forever 2001:db8:1::/64 dev eth0 proto kernel metric 256 fe80::/64 dev eth0 proto kernel metric 256 default via fe80::1 dev eth0 metric 1024 In this example the Docker container is assigned a link-local address with the network suffix `/64` (here: `fe80::42:acff:fe11:3/64`) and a globally routable IPv6 address (here: `2001:db8:1:0:0:242:ac11:3/64`). The container will create connections to addresses outside of the `2001:db8:1::/64` network via the link-local gateway at `fe80::1` on `eth0`. Often servers or virtual machines get a `/64` IPv6 subnet assigned (e.g. `2001:db8:23:42::/64`). In this case you can split it up further and provide Docker a `/80` subnet while using a separate `/80` subnet for other applications on the host: ![](images/<API key>.svg) In this setup the subnet `2001:db8:23:42::/64` with a range from `2001:db8:23:42:0:0:0:0` to `2001:db8:23:42:ffff:ffff:ffff:ffff` is attached to `eth0`, with the host listening at `2001:db8:23:42::1`. The subnet `2001:db8:23:42:1::/80` with an address range from `2001:db8:23:42:1:0:0:0` to `2001:db8:23:42:1:ffff:ffff:ffff` is attached to `docker0` and will be used by containers. Using NDP proxying If your Docker host is the only part of an IPv6 subnet but has not got an IPv6 subnet assigned you can use NDP proxying to connect your containers via IPv6 to the internet. For example your host with the IPv6 address `2001:db8::c001`, is part of the subnet `2001:db8::/64` and your IaaS provider allows you to configure the IPv6 addresses `2001:db8::c000` to `2001:db8::c00f`: $ ip -6 addr show 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000 inet6 2001:db8::c001/64 scope global valid_lft forever preferred_lft forever inet6 fe80::601:3fff:fea1:9c01/64 scope link valid_lft forever preferred_lft forever Let's split up the configurable address range into two subnets `2001:db8::c000/125` and `2001:db8::c008/125`. The first one can be used by the host itself, the latter by Docker: dockerd --ipv6 --fixed-cidr-v6 2001:db8::c008/125 You notice the Docker subnet is within the subnet managed by your router that is connected to `eth0`. This means all devices (containers) with the addresses from the Docker subnet are expected to be found within the router subnet. Therefore the router thinks it can talk to these containers directly. ![](images/ipv6_ndp_proxying.svg) As soon as the router wants to send an IPv6 packet to the first container it will transmit a neighbor solicitation request, asking, who has `2001:db8::c009`? But it will get no answer because no one on this subnet has this address. The container with this address is hidden behind the Docker host. The Docker host has to listen to neighbor solicitation requests for the container address and send a response that itself is the device that is responsible for the address. This is done by a Kernel feature called `NDP Proxy`. You can enable it by executing $ sysctl net.ipv6.conf.eth0.proxy_ndp=1 Now you can add the container's IPv6 address to the NDP proxy table: $ ip -6 neigh add proxy 2001:db8::c009 dev eth0 This command tells the Kernel to answer to incoming neighbor solicitation requests regarding the IPv6 address `2001:db8::c009` on the device `eth0`. As a consequence of this all traffic to this IPv6 address will go into the Docker host and it will forward it according to its routing table via the `docker0` device to the container network: $ ip -6 route show 2001:db8::c008/125 dev docker0 metric 1 2001:db8::/64 dev eth0 proto kernel metric 256 You have to execute the `ip -6 neigh add proxy ...` command for every IPv6 address in your Docker subnet. Unfortunately there is no functionality for adding a whole subnet by executing one command. An alternative approach would be to use an NDP proxy daemon such as [ndppd](https://github.com/DanielAdolfsson/ndppd). ## Docker IPv6 cluster Switched network environment Using routable IPv6 addresses allows you to realize communication between containers on different hosts. Let's have a look at a simple Docker IPv6 cluster example: ![](images/<API key>.svg) The Docker hosts are in the `2001:db8:0::/64` subnet. Host1 is configured to provide addresses from the `2001:db8:1::/64` subnet to its containers. It has three routes configured: - Route all traffic to `2001:db8:0::/64` via `eth0` - Route all traffic to `2001:db8:1::/64` via `docker0` - Route all traffic to `2001:db8:2::/64` via Host2 with IP `2001:db8::2` Host1 also acts as a router on OSI layer 3. When one of the network clients tries to contact a target that is specified in Host1's routing table Host1 will forward the traffic accordingly. It acts as a router for all networks it knows: `2001:db8::/64`, `2001:db8:1::/64` and `2001:db8:2::/64`. On Host2 we have nearly the same configuration. Host2's containers will get IPv6 addresses from `2001:db8:2::/64`. Host2 has three routes configured: - Route all traffic to `2001:db8:0::/64` via `eth0` - Route all traffic to `2001:db8:2::/64` via `docker0` - Route all traffic to `2001:db8:1::/64` via Host1 with IP `2001:db8:0::1` The difference to Host1 is that the network `2001:db8:2::/64` is directly attached to the host via its `docker0` interface whereas it reaches `2001:db8:1::/64` via Host1's IPv6 address `2001:db8::1`. This way every container is able to contact every other container. The containers `Container1-*` share the same subnet and contact each other directly. The traffic between `Container1-*` and `Container2-*` will be routed via Host1 and Host2 because those containers do not share the same subnet. In a switched environment every host has to know all routes to every subnet. You always have to update the hosts' routing tables once you add or remove a host to the cluster. Every configuration in the diagram that is shown below the dashed line is handled by Docker: The `docker0` bridge IP address configuration, the route to the Docker subnet on the host, the container IP addresses and the routes on the containers. The configuration above the line is up to the user and can be adapted to the individual environment. Routed network environment In a routed network environment you replace the layer 2 switch with a layer 3 router. Now the hosts just have to know their default gateway (the router) and the route to their own containers (managed by Docker). The router holds all routing information about the Docker subnets. When you add or remove a host to this environment you just have to update the routing table in the router - not on every host. ![](images/<API key>.png) In this scenario containers of the same host can communicate directly with each other. The traffic between containers on different hosts will be routed via their hosts and the router. For example packet from `Container1-1` to `Container2-1` will be routed through `Host1`, `Router` and `Host2` until it arrives at `Container2-1`. To keep the IPv6 addresses short in this example a `/48` network is assigned to every host. The hosts use a `/64` subnet of this for its own services and one for Docker. When adding a third host you would add a route for the subnet `2001:db8:3::/48` in the router and configure Docker on Host3 with `--fixed-cidr-v6=2001:db8:3:1::/64`. Remember the subnet for Docker containers should at least have a size of `/80`. This way an IPv6 address can end with the container's MAC address and you prevent NDP neighbor cache invalidation issues in the Docker layer. So if you have a `/64` for your whole environment use `/76` subnets for the hosts and `/80` for the containers. This way you can use 4096 hosts with 16 `/80` subnets each. Every configuration in the diagram that is visualized below the dashed line is handled by Docker: The `docker0` bridge IP address configuration, the route to the Docker subnet on the host, the container IP addresses and the routes on the containers. The configuration above the line is up to the user and can be adapted to the individual environment.
<!-- HTML header for doxygen 1.8.13--> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>chigraph: Class Members - Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="chigraphDoxygenIcon.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">chigraph &#160;<span id="projectnumber">master</span> </div> <div id="projectbrief">Systems programming language written for beginners in LLVM</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('functions_func_k.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160; <h3><a id="index_k"></a>- k -</h3><ul> <li>kill() : <a class="el" href="<API key>.html#<API key>">chi::Subprocess</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Sat Sep 16 2017 17:41:35 for chigraph by <a href="http: <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
[expect] In BaseClass constructor [expect] In BaseClass constructor [expect] In SubClass constructor [file] <?php class BaseClass { function __construct() { print "In BaseClass constructor\n"; } } class SubClass extends BaseClass { function __construct() { parent::__construct(); print "In SubClass constructor\n"; } } $obj = new BaseClass(); $obj = new SubClass(); ?>
#! /bin/bash # A script to reconfigure Apache so that it serves up Graphite's Web UI. sudo tee /etc/apache2/sites-available/000-default.conf > /dev/null <<CONFIG_EOF WSGISocketPrefix /var/run/wsgi <VirtualHost *:80> ServerAdmin $SERVER_ADMIN_EMAIL ServerName graphite DocumentRoot "/opt/graphite/webapp" ErrorLog /opt/graphite/storage/log/webapp/error.log CustomLog /opt/graphite/storage/log/webapp/access.log common WSGIDaemonProcess graphite processes=5 threads=5 display-name='%{GROUP}' inactivity-timeout=120 WSGIProcessGroup graphite <API key> %{GLOBAL} WSGIImportScript /opt/graphite/conf/graphite.wsgi process-group=graphite application-group=%{GLOBAL} WSGIScriptAlias / /opt/graphite/conf/graphite.wsgi Alias /content/ /opt/graphite/webapp/content/ <Location "/content/"> SetHandler None Order deny,allow Allow from all </Location> <Directory /opt/graphite/conf/> Options All AllowOverride All Require all granted </Directory> <Directory /opt/graphite/webapp> Options All AllowOverride All Require all granted </Directory> </VirtualHost> CONFIG_EOF # Make Graphite's storage directory writeable by the Web server sudo chown -R www-data:www-data /opt/graphite/storage # Restart Apache to pick up on the configuration change sudo service apache2 restart
package org.zstack.kvm; public class <API key> extends KVMHostHttpCallMsg { }