answer
stringlengths
15
1.25M
#ifndef DYNET_NODES_LSTM_H_ #define DYNET_NODES_LSTM_H_ #include "dynet/dynet.h" #include "dynet/nodes-def-macros.h" namespace dynet { struct VanillaLSTMGates : public Node { explicit VanillaLSTMGates(const std::vector<VariableIndex>& a, bool dropout, real weightnoise_std) : Node(a), dropout(dropout), weightnoise_std(weightnoise_std), forget_gate_bias(1.0) {} virtual bool supports_multibatch() const override { return true; } virtual int autobatch_sig(const ComputationGraph &cg, SigMap &sm) const override; virtual std::vector<int> autobatch_concat(const ComputationGraph & cg) const override; virtual void autobatch_reshape(const ComputationGraph & cg, const std::vector<VariableIndex> & batch_ids, const std::vector<int> & concat, std::vector<const Tensor*>& xs, Tensor& fx) const override { <API key>(cg, batch_ids, concat, xs, fx); } bool dropout; real weightnoise_std; const real forget_gate_bias; <API key>() }; struct VanillaLSTMC : public Node { explicit VanillaLSTMC(const std::initializer_list<VariableIndex>& a) : Node(a) {} virtual bool supports_multibatch() const override { return true; } virtual int autobatch_sig(const ComputationGraph &cg, SigMap &sm) const override; virtual std::vector<int> autobatch_concat(const ComputationGraph & cg) const override; virtual void autobatch_reshape(const ComputationGraph & cg, const std::vector<VariableIndex> & batch_ids, const std::vector<int> & concat, std::vector<const Tensor*>& xs, Tensor& fx) const override { <API key>(cg, batch_ids, concat, xs, fx); } <API key>() }; struct VanillaLSTMH : public Node { explicit VanillaLSTMH(const std::initializer_list<VariableIndex>& a) : Node(a) {} virtual bool supports_multibatch() const override { return true; } virtual int autobatch_sig(const ComputationGraph &cg, SigMap &sm) const override; virtual std::vector<int> autobatch_concat(const ComputationGraph & cg) const override; virtual void autobatch_reshape(const ComputationGraph & cg, const std::vector<VariableIndex> & batch_ids, const std::vector<int> & concat, std::vector<const Tensor*>& xs, Tensor& fx) const override { <API key>(cg, batch_ids, concat, xs, fx); } <API key>() }; } // namespace dynet #endif
<?php /** * When appropriate, displays a plugin upgrade message "inline" within the plugin * admin screen. * * This is drawn from the Upgrade Notice section of the plugin readme.txt file (ie, * the one belonging to the current stable accessible via WP SVN - at least by * default). */ class <API key> { /** * Currently installed version of the plugin * * @var string */ protected $current_version = ''; /** * The plugin path as it is within the plugins directory, ie * "some-plugin/main-file.php". * * @var string */ protected $plugin_path = ''; /** * Contains the plugin upgrade notice (empty if none are available). * * @var string */ protected $upgrade_notice = ''; /** * Test for and display any plugin upgrade messages (if any are available) inline * beside the plugin listing itself. * * The optional third param is the object which actually checks to see if there * are any upgrade notices worth displaying. If not provided, an object of the * default type will be created (which connects to WP SVN). * * @param string $current_version * @param string $plugin_path (ie "plugin-dir/main-file.php") */ public function __construct( $current_version, $plugin_path ) { $this->current_version = $current_version; $this->plugin_path = $plugin_path; add_action( "<API key>-$plugin_path", array( $this, 'maybe_run' ) ); } /** * Test if there is a plugin upgrade notice and displays it if so. * * Expects to fire during "<API key>-{plugin_path}", therefore * this should only run if WordPress has detected that an upgrade is indeed * available. */ public function maybe_run() { $this-><API key>(); if ( $this->upgrade_notice ) { $this->display_message(); } } /** * Tests to see if an upgrade notice is available. */ protected function <API key>() { $cache_key = $this->cache_key(); $this->upgrade_notice = get_transient( $cache_key ); if ( false === $this->upgrade_notice ) { $this-><API key>(); } set_transient( $cache_key, $this->upgrade_notice, $this->cache_expiration() ); } /** * Returns a cache key unique to the current plugin path and version, that * still fits within the 45-char limit of regular WP transient keys. * * @return string */ protected function cache_key() { return '<API key>-' . hash( 'crc32b', $this->plugin_path . $this->current_version ); } /** * Returns the period of time (in seconds) for which to cache plugin upgrade messages. * * @return int */ protected function cache_expiration() { /** * Number of seconds to cache plugin upgrade messages for. * * Defaults to one day, which provides a decent balance between efficiency savings * and allowing for the possibility that some upgrade messages may be changed or * rescinded. * * @var int $cache_expiration */ return (int) apply_filters( '<API key>', DAY_IN_SECONDS, $this->plugin_path ); } /** * Looks at the current stable plugin readme.txt and parses to try and find the first * available upgrade notice relating to a plugin version higher than this one. * * By default, WP SVN is the source. */ protected function <API key>() { /** * The URL for the current plugin readme.txt file. * * @var string $url * @var string $plugin_path */ $readme_url = apply_filters( '<API key>', $this-><API key>(), $this->plugin_path ); if ( ! empty( $readme_url ) ) { $response = wp_safe_remote_get( $readme_url ); } if ( ! empty( $response ) && ! is_wp_error( $response ) ) { $readme = $response['body']; } if ( ! empty( $readme ) ) { $this-><API key>( $readme ); $this-><API key>(); } /** * The upgrade notice for the current plugin (may be empty). * * @var string $upgrade_notice * @var string $plugin_path */ return apply_filters( '<API key>', $this->upgrade_notice, $this->plugin_path ); } /** * Forms the expected URL to the trunk readme.txt file as it is on WP SVN * or an empty string if for any reason it cannot be determined. * * @return string */ protected function <API key>() { $parts = explode( '/', $this->plugin_path ); $slug = empty( $parts[0] ) ? '' : $parts[0]; return esc_url( "https://plugins.svn.wordpress.org/$slug/trunk/readme.txt" ); } /** * Given a standard Markdown-format WP readme.txt file, finds the first upgrade * notice (if any) for a version higher than $this->current_version. * * @param string $readme * @return string */ protected function <API key>( $readme ) { $in_upgrade_notice = false; $in_version_notice = false; $readme_lines = explode( "\n", $readme ); foreach ( $readme_lines as $line ) { // Once we leave the Upgrade Notice section (ie, we encounter a new section header), bail if ( $in_upgrade_notice && 0 === strpos( $line, '==' ) ) { break; } // Look out for the start of the Upgrade Notice section if ( ! $in_upgrade_notice && preg_match( '/^==\s*Upgrade\s+Notice\s*==/i', $line ) ) { $in_upgrade_notice = true; } // Also test to see if we have left the version specific note (ie, we encounter a new sub heading or header) if ( $in_upgrade_notice && $in_version_notice && 0 === strpos( $line, '=' ) ) { break; } // Look out for the first applicable version-specific note within the Upgrade Notice section if ( $in_upgrade_notice && ! $in_version_notice && preg_match( '/^=\s*\[?([0-9\.]{3,})\]?\s*=/', $line, $matches ) ) { // Is this a higher version than currently installed? if ( version_compare( $matches[1], $this->current_version, '>' ) ) { $in_version_notice = true; } } // Copy the details of the upgrade notice for the first higher version we find if ( $in_upgrade_notice && $in_version_notice ) { $this->upgrade_notice .= $line . "\n"; } } } /** * Convert the plugin version header and any links from Markdown to HTML. */ protected function <API key>() { $this->upgrade_notice = preg_replace( '/\[([^\]]*)\]\(([^\)]*)\)/', '<a href="${2}">${1}</a>', $this->upgrade_notice ); // Convert =4.0= headings to <h4 class="version">4.0</h4> tags $this->upgrade_notice = preg_replace( '/=\s*([a-zA-Z0-9\.]{3,})\s*=/', '<h4 class="version">${1}</h4>', $this->upgrade_notice ); } /** * Render the actual upgrade notice. * * Please note if plugin-specific styling is required for the message, you can * use an ID generated by WordPress for one of the message's parent elements * which takes the form "{plugin_name}-update". Example: * * #<API key> .<API key> { ... } */ public function display_message() { $notice = wp_kses_post( $this->upgrade_notice ); echo "<div class='<API key>'> $notice </div>"; } }
-- Key assertion, -- inner select clause binds departmentid to department.departmentid select * from department JOIN employee USING(departmentid) WHERE departmentid = (SELECT z FROM t1 WHERE t1.x = departmentid)
// // // // //# 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 # // // // // // // //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // WARNING: DO NOT MODIFY the content of this file package ims.generalmedical.vo; /** * Linked to core.clinical.<API key> business object (ID: 1003100055). */ public class <API key> extends ims.core.clinical.vo.<API key> implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public <API key>() { } public <API key>(Integer id, int version) { super(id, version); } public <API key>(ims.generalmedical.vo.beans.<API key> bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.<API key>.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.beans.<API key> bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.<API key>.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.generalmedical.vo.beans.<API key> bean = null; if(map != null) bean = (ims.generalmedical.vo.beans.<API key>)map.getValueObjectBean(this); if (bean == null) { bean = new ims.generalmedical.vo.beans.<API key>(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object <API key>(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.<API key>("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CHANCEOFSLEEP")) return getChanceOfSleep(); if(fieldName.equals("SLEEPSCORE")) return getSleepScore(); return super.<API key>(fieldName); } public boolean <API key>() { return this.chanceofsleep != null; } public ims.spinalinjuries.vo.lookups.<API key> getChanceOfSleep() { return this.chanceofsleep; } public void setChanceOfSleep(ims.spinalinjuries.vo.lookups.<API key> value) { this.isValidated = false; this.chanceofsleep = value; } public boolean <API key>() { return this.sleepscore != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthScore getSleepScore() { return this.sleepscore; } public void setSleepScore(ims.spinalinjuries.vo.lookups.SleepEpworthScore value) { this.isValidated = false; this.sleepscore = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; <API key> clone = new <API key>(this.id, this.version); if(this.chanceofsleep == null) clone.chanceofsleep = null; else clone.chanceofsleep = (ims.spinalinjuries.vo.lookups.<API key>)this.chanceofsleep.clone(); if(this.sleepscore == null) clone.sleepscore = null; else clone.sleepscore = (ims.spinalinjuries.vo.lookups.SleepEpworthScore)this.sleepscore.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(<API key>.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A <API key> object cannot be compared an Object of type " + obj.getClass().getName()); } <API key> compareObj = (<API key>)obj; int retVal = 0; if (retVal == 0) { if(this.<API key>() == null && compareObj.<API key>() != null) return -1; if(this.<API key>() != null && compareObj.<API key>() == null) return 1; if(this.<API key>() != null && compareObj.<API key>() != null) retVal = this.<API key>().compareTo(compareObj.<API key>()); } return retVal; } public synchronized static int <API key>() { return ims.vo.ValueObject.generateUniqueID(); } public int <API key>() { int count = 0; if(this.chanceofsleep != null) count++; if(this.sleepscore != null) count++; return count; } public int <API key>() { return 2; } protected ims.spinalinjuries.vo.lookups.<API key> chanceofsleep; protected ims.spinalinjuries.vo.lookups.SleepEpworthScore sleepscore; private boolean isValidated = false; private boolean isBusy = false; }
// // // // //# 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 # // // // // // // //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo.beans; public class MRSATreatmentVoBean extends ims.vo.ValueObjectBean { public MRSATreatmentVoBean() { } public MRSATreatmentVoBean(ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public ims.nursing.vo.MRSATreatmentVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.nursing.vo.MRSATreatmentVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.MRSATreatmentVo vo = null; if(map != null) vo = (ims.nursing.vo.MRSATreatmentVo)map.getValueObject(this); if(vo == null) { vo = new ims.nursing.vo.MRSATreatmentVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateBean getStartDate() { return this.startdate; } public void setStartDate(ims.framework.utils.beans.DateBean value) { this.startdate = value; } public ims.framework.utils.beans.DateBean getRescreenDate() { return this.rescreendate; } public void setRescreenDate(ims.framework.utils.beans.DateBean value) { this.rescreendate = value; } public Integer getTreatmentNumber() { return this.treatmentnumber; } public void setTreatmentNumber(Integer value) { this.treatmentnumber = value; } public ims.nursing.vo.beans.<API key>[] getTreatmentDetails() { return this.treatmentdetails; } public void setTreatmentDetails(ims.nursing.vo.beans.<API key>[] value) { this.treatmentdetails = value; } private Integer id; private int version; private ims.framework.utils.beans.DateBean startdate; private ims.framework.utils.beans.DateBean rescreendate; private Integer treatmentnumber; private ims.nursing.vo.beans.<API key>[] treatmentdetails; }
// // // // //# 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 # // // // // // // //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo; /** * Linked to nursing.assessment.Transfers business object (ID: 1015100016). */ public class Transfers extends ims.nursing.assessment.vo.TransfersRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public Transfers() { } public Transfers(Integer id, int version) { super(id, version); } public Transfers(ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.<API key>() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.<API key>()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.<API key>() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.<API key>()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.beans.TransfersBean bean = null; if(map != null) bean = (ims.nursing.vo.beans.TransfersBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.nursing.vo.beans.TransfersBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object <API key>(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.<API key>("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("PATIENTTRANSFERS")) return getPatientTransfers(); if(fieldName.equals("ASSISTANCEREQUIRED")) return <API key>(); return super.<API key>(fieldName); } public boolean <API key>() { return this.patienttransfers != null; } public ims.nursing.vo.lookups.Transfers getPatientTransfers() { return this.patienttransfers; } public void setPatientTransfers(ims.nursing.vo.lookups.Transfers value) { this.isValidated = false; this.patienttransfers = value; } public boolean <API key>() { return this.assistancerequired != null; } public ims.nursing.vo.lookups.Ability <API key>() { return this.assistancerequired; } public void <API key>(ims.nursing.vo.lookups.Ability value) { this.isValidated = false; this.assistancerequired = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; Transfers clone = new Transfers(this.id, this.version); if(this.patienttransfers == null) clone.patienttransfers = null; else clone.patienttransfers = (ims.nursing.vo.lookups.Transfers)this.patienttransfers.clone(); if(this.assistancerequired == null) clone.assistancerequired = null; else clone.assistancerequired = (ims.nursing.vo.lookups.Ability)this.assistancerequired.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(Transfers.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A Transfers object cannot be compared an Object of type " + obj.getClass().getName()); } Transfers compareObj = (Transfers)obj; int retVal = 0; if (retVal == 0) { if(this.getID_Transfers() == null && compareObj.getID_Transfers() != null) return -1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() == null) return 1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() != null) retVal = this.getID_Transfers().compareTo(compareObj.getID_Transfers()); } return retVal; } public synchronized static int <API key>() { return ims.vo.ValueObject.generateUniqueID(); } public int <API key>() { int count = 0; if(this.patienttransfers != null) count++; if(this.assistancerequired != null) count++; return count; } public int <API key>() { return 2; } protected ims.nursing.vo.lookups.Transfers patienttransfers; protected ims.nursing.vo.lookups.Ability assistancerequired; private boolean isValidated = false; private boolean isBusy = false; }
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo; /** * Linked to RefMan.CatsReferral business object (ID: 1004100035). */ public class <API key> extends ims.RefMan.vo.CatsReferralRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public <API key>() { } public <API key>(Integer id, int version) { super(id, version); } public <API key>(ims.RefMan.vo.beans.<API key> bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.<API key> bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(map); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.beans.<API key> bean = null; if(map != null) bean = (ims.RefMan.vo.beans.<API key>)map.getValueObjectBean(this); if (bean == null) { bean = new ims.RefMan.vo.beans.<API key>(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object <API key>(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.<API key>("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("REFERRALDETAILS")) return getReferralDetails(); if(fieldName.equals("CURRENTSTATUS")) return getCurrentStatus(); return super.<API key>(fieldName); } public boolean <API key>() { return this.referraldetails != null; } public ims.RefMan.vo.<API key> getReferralDetails() { return this.referraldetails; } public void setReferralDetails(ims.RefMan.vo.<API key> value) { this.isValidated = false; this.referraldetails = value; } public boolean <API key>() { return this.currentstatus != null; } public ims.RefMan.vo.<API key> getCurrentStatus() { return this.currentstatus; } public void setCurrentStatus(ims.RefMan.vo.<API key> value) { this.isValidated = false; this.currentstatus = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; <API key> clone = new <API key>(this.id, this.version); if(this.referraldetails == null) clone.referraldetails = null; else clone.referraldetails = (ims.RefMan.vo.<API key>)this.referraldetails.clone(); if(this.currentstatus == null) clone.currentstatus = null; else clone.currentstatus = (ims.RefMan.vo.<API key>)this.currentstatus.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(<API key>.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A <API key> object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((<API key>)obj).getBoId() == null) return -1; return this.id.compareTo(((<API key>)obj).getBoId()); } public synchronized static int <API key>() { return ims.vo.ValueObject.generateUniqueID(); } public int <API key>() { int count = 0; if(this.referraldetails != null) count++; if(this.currentstatus != null) count++; return count; } public int <API key>() { return 2; } protected ims.RefMan.vo.<API key> referraldetails; protected ims.RefMan.vo.<API key> currentstatus; private boolean isValidated = false; private boolean isBusy = false; }
<?php /** * Dummy theme. */ function i18n_theme_test() { return __( 'This is a dummy theme', '<API key>' ); }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Unit Testing Class : CodeIgniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../nav/nav.js"></script> <script type="text/javascript" src="../nav/prototype.lite.js"></script> <script type="text/javascript" src="../nav/moo.fx.js"></script> <script type="text/javascript" src="../nav/user_guide_menu.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='ExpressionEngine Dev Team' /> <meta name='description' content='CodeIgniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>CodeIgniter User Guide Version 1.7.2</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; Unit Testing Class </td> <td id="searchbox"><form method="get" action="http: </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <h1>Unit Testing Class</h1> <p>Unit testing is an approach to software development in which tests are written for each function in your application. If you are not familiar with the concept you might do a little googling on the subject.</p> <p>CodeIgniter's Unit Test class is quite simple, consisting of an evaluation function and two result functions. It's not intended to be a full-blown test suite but rather a simple mechanism to evaluate your code to determine if it is producing the correct data type and result. </p> <h2>Initializing the Class</h2> <p>Like most other classes in CodeIgniter, the Unit Test class is initialized in your controller using the <dfn>$this->load->library</dfn> function:</p> <code>$this->load->library('unit_test');</code> <p>Once loaded, the Unit Test object will be available using: <dfn>$this->unit</dfn></p> <h2>Running Tests</h2> <p>Running a test involves supplying a test and an expected result to the following function:</p> <h2>$this->unit->run( <var>test</var>, <var>expected result</var>, '<var>test name</var>' );</h2> <p>Where <var>test</var> is the result of the code you wish to test, <var>expected result</var> is the data type you expect, and <var>test name</var> is an optional name you can give your test. Example:</p> <code>$test = 1 + 1;<br /> <br /> $expected_result = 2;<br /> <br /> $test_name = 'Adds one plus one';<br /> <br /> $this->unit->run($test, $expected_result, $test_name);</code> <p>The expected result you supply can either be a literal match, or a data type match. Here's an example of a literal:</p> <code>$this->unit->run('Foo', 'Foo');</code> <p>Here is an example of a data type match:</p> <code>$this->unit->run('Foo', 'is_string');</code> <p>Notice the use of "is_string" in the second parameter? This tells the function to evaluate whether your test is producing a string as the result. Here is a list of allowed comparison types:</p> <ul> <li>is_string</li> <li>is_bool</li> <li>is_true</li> <li>is_false</li> <li>is_int</li> <li>is_numeric</li> <li>is_float</li> <li>is_double</li> <li>is_array</li> <li>is_null</li> </ul> <h2>Generating Reports</h2> <p>You can either display results after each test, or your can run several tests and generate a report at the end. To show a report directly simply echo or return the <var>run</var> function:</p> <code>echo $this->unit->run($test, $expected_result);</code> <p>To run a full report of all tests, use this:</p> <code>echo $this->unit->report();</code> <p>The report will be formatted in an HTML table for viewing. If you prefer the raw data you can retrieve an array using:</p> <code>echo $this->unit->result();</code> <h2>Strict Mode</h2> <p>By default the unit test class evaluates literal matches loosely. Consider this example:</p> <code>$this->unit->run(1, TRUE);</code> <p>The test is evaluating an integer, but the expected result is a boolean. PHP, however, due to it's loose data-typing will evaluate the above code as TRUE using a normal equality test:</p> <code>if (1 == TRUE) echo 'This evaluates as true';</code> <p>If you prefer, you can put the unit test class in to strict mode, which will compare the data type as well as the value:</p> <code>if (1 === TRUE) echo 'This evaluates as FALSE';</code> <p>To enable strict mode use this:</p> <code>$this->unit->use_strict(TRUE);</code> <h2>Enabling/Disabling Unit Testing</h2> <p>If you would like to leave some testing in place in your scripts, but not have it run unless you need it, you can disable unit testing using:</p> <code>$this->unit->active(FALSE)</code> <h2>Creating a Template</h2> <p>If you would like your test results formatted differently then the default you can set your own template. Here is an example of a simple template. Note the required pseudo-variables:</p> <code> $str = '<br /> &lt;table border="0" cellpadding="4" cellspacing="1"><br /> &nbsp;&nbsp;&nbsp;&nbsp;<kbd>{rows}</kbd><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;tr><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;td><kbd>{item}</kbd>&lt;/td><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;td><kbd>{result}</kbd>&lt;/td><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/tr><br /> &nbsp;&nbsp;&nbsp;&nbsp;<kbd>{/rows}</kbd><br /> &lt;/table>';<br /> <br /> $this->unit->set_template($str); </code> <p class="important"><strong>Note:</strong> Your template must be declared <strong>before</strong> running the unit test process.</p> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="typography.html">Typography Class</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="uri.html">URI Class</a> </p> <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright & </div> </body> </html>
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "SMESH_ControlsDef.hxx" #include "SMDS_BallElement.hxx" #include "SMDS_Iterator.hxx" #include "SMDS_Mesh.hxx" #include "SMDS_MeshElement.hxx" #include "SMDS_MeshNode.hxx" #include "SMDS_QuadraticEdge.hxx" #include "<API key>.hxx" #include "SMDS_VolumeTool.hxx" #include "SMESHDS_GroupBase.hxx" #include "<API key>.hxx" #include "SMESHDS_Mesh.hxx" #include "SMESH_MeshAlgos.hxx" #include "SMESH_OctreeNode.hxx" #include <Basics_Utils.hxx> #include <BRepAdaptor_Surface.hxx> #include <<API key>.hxx> #include <BRep_Tool.hxx> #include <<API key>.hxx> #include <Geom_Plane.hxx> #include <Geom_Surface.hxx> #include <Precision.hxx> #include <<API key>.hxx> #include <<API key>.hxx> #include <<API key>.hxx> #include <TColgp_Array1OfXYZ.hxx> #include <TopAbs.hxx> #include <TopExp.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <TopoDS_Iterator.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS_Vertex.hxx> #include <gp_Ax3.hxx> #include <gp_Cylinder.hxx> #include <gp_Dir.hxx> #include <gp_Pln.hxx> #include <gp_Pnt.hxx> #include <gp_Vec.hxx> #include <gp_XYZ.hxx> #include <vtkMeshQuality.h> #include <set> #include <limits> /* AUXILIARY METHODS */ namespace { const double theEps = 1e-100; const double theInf = 1e+100; inline gp_XYZ gpXYZ(const SMDS_MeshNode* aNode ) { return gp_XYZ(aNode->X(), aNode->Y(), aNode->Z() ); } inline double getAngle( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 ) { gp_Vec v1( P1 - P2 ), v2( P3 - P2 ); return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0 : v1.Angle( v2 ); } inline double getArea( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 ) { gp_Vec aVec1( P2 - P1 ); gp_Vec aVec2( P3 - P1 ); return ( aVec1 ^ aVec2 ).Magnitude() * 0.5; } inline double getArea( const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3 ) { return getArea( P1.XYZ(), P2.XYZ(), P3.XYZ() ); } inline double getDistance( const gp_XYZ& P1, const gp_XYZ& P2 ) { double aDist = gp_Pnt( P1 ).Distance( gp_Pnt( P2 ) ); return aDist; } int <API key>( const SMDS_Mesh* theMesh, const int theId ) { if ( theMesh == 0 ) return 0; const SMDS_MeshElement* anEdge = theMesh->FindElement( theId ); if ( anEdge == 0 || anEdge->GetType() != SMDSAbs_Edge/* || anEdge->NbNodes() != 2 */) return 0; // for each pair of nodes in anEdge (there are 2 pairs in a quadratic edge) // count elements containing both nodes of the pair. // Note that there may be such cases for a quadratic edge (a horizontal line): // Case 1 Case 2 // result sould be 2 in both cases int aResult0 = 0, aResult1 = 0; // last node, it is a medium one in a quadratic edge const SMDS_MeshNode* aLastNode = anEdge->GetNode( anEdge->NbNodes() - 1 ); const SMDS_MeshNode* aNode0 = anEdge->GetNode( 0 ); const SMDS_MeshNode* aNode1 = anEdge->GetNode( 1 ); if ( aNode1 == aLastNode ) aNode1 = 0; <API key> anElemIter = aLastNode-><API key>(); while( anElemIter->more() ) { const SMDS_MeshElement* anElem = anElemIter->next(); if ( anElem != 0 && anElem->GetType() != SMDSAbs_Edge ) { <API key> anIter = anElem->nodesIterator(); while ( anIter->more() ) { if ( const SMDS_MeshElement* anElemNode = anIter->next() ) { if ( anElemNode == aNode0 ) { aResult0++; if ( !aNode1 ) break; // not a quadratic edge } else if ( anElemNode == aNode1 ) aResult1++; } } } } int aResult = std::max ( aResult0, aResult1 ); return aResult; } gp_XYZ getNormale( const SMDS_MeshFace* theFace, bool* ok=0 ) { int aNbNode = theFace->NbNodes(); gp_XYZ q1 = gpXYZ( theFace->GetNode(1)) - gpXYZ( theFace->GetNode(0)); gp_XYZ q2 = gpXYZ( theFace->GetNode(2)) - gpXYZ( theFace->GetNode(0)); gp_XYZ n = q1 ^ q2; if ( aNbNode > 3 ) { gp_XYZ q3 = gpXYZ( theFace->GetNode(3)) - gpXYZ( theFace->GetNode(0)); n += q2 ^ q3; } double len = n.Modulus(); bool zeroLen = ( len <= numeric_limits<double>::min()); if ( !zeroLen ) n /= len; if (ok) *ok = !zeroLen; return n; } } using namespace SMESH::Controls; /* * FUNCTORS */ /* Class : NumericalFunctor Description : Base class for numerical functors */ NumericalFunctor::NumericalFunctor(): myMesh(NULL) { myPrecision = -1; } void NumericalFunctor::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool NumericalFunctor::GetPoints(const int theId, TSequenceOfXYZ& theRes ) const { theRes.clear(); if ( myMesh == 0 ) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem || anElem->GetType() != this->GetType() ) return false; return GetPoints( anElem, theRes ); } bool NumericalFunctor::GetPoints(const SMDS_MeshElement* anElem, TSequenceOfXYZ& theRes ) { theRes.clear(); if ( anElem == 0 ) return false; theRes.reserve( anElem->NbNodes() ); theRes.setElement( anElem ); // Get nodes of the element <API key> anIter; if ( anElem->IsQuadratic() ) { switch ( anElem->GetType() ) { case SMDSAbs_Edge: anIter = dynamic_cast<const SMDS_VtkEdge*> (anElem)-><API key>(); break; case SMDSAbs_Face: anIter = dynamic_cast<const SMDS_VtkFace*> (anElem)-><API key>(); break; default: anIter = anElem->nodesIterator(); } } else { anIter = anElem->nodesIterator(); } if ( anIter ) { double xyz[3]; while( anIter->more() ) { if ( const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( anIter->next() )) { aNode->GetXYZ( xyz ); theRes.push_back( gp_XYZ( xyz[0], xyz[1], xyz[2] )); } } } return true; } long NumericalFunctor::GetPrecision() const { return myPrecision; } void NumericalFunctor::SetPrecision( const long thePrecision ) { myPrecision = thePrecision; myPrecisionValue = pow( 10., (double)( myPrecision ) ); } double NumericalFunctor::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); TSequenceOfXYZ P; if ( GetPoints( theId, P )) // elem type is checked here aVal = Round( GetValue( P )); return aVal; } double NumericalFunctor::Round( const double & aVal ) { return ( myPrecision >= 0 ) ? floor( aVal * myPrecisionValue + 0.5 ) / myPrecisionValue : aVal; } /*! * \brief Return histogram of functor values * \param nbIntervals - number of intervals * \param nbEvents - number of mesh elements having values within i-th interval * \param funValues - boundaries of intervals * \param elements - elements to check vulue of; empty list means "of all" * \param minmax - boundaries of diapason of values to divide into intervals */ void NumericalFunctor::GetHistogram(int nbIntervals, std::vector<int>& nbEvents, std::vector<double>& funValues, const vector<int>& elements, const double* minmax, const bool isLogarithmic) { if ( nbIntervals < 1 || !myMesh || !myMesh->GetMeshInfo().NbElements( GetType() )) return; nbEvents.resize( nbIntervals, 0 ); funValues.resize( nbIntervals+1 ); // get all values sorted std::multiset< double > values; if ( elements.empty() ) { <API key> elemIt = myMesh->elementsIterator( GetType() ); while ( elemIt->more() ) values.insert( GetValue( elemIt->next()->GetID() )); } else { vector<int>::const_iterator id = elements.begin(); for ( ; id != elements.end(); ++id ) values.insert( GetValue( *id )); } if ( minmax ) { funValues[0] = minmax[0]; funValues[nbIntervals] = minmax[1]; } else { funValues[0] = *values.begin(); funValues[nbIntervals] = *values.rbegin(); } // case nbIntervals == 1 if ( nbIntervals == 1 ) { nbEvents[0] = values.size(); return; } // case of 1 value if (funValues.front() == funValues.back()) { nbEvents.resize( 1 ); nbEvents[0] = values.size(); funValues[1] = funValues.back(); funValues.resize( 2 ); } // generic case std::multiset< double >::iterator min = values.begin(), max; for ( int i = 0; i < nbIntervals; ++i ) { // find end value of i-th interval double r = (i+1) / double(nbIntervals); if (isLogarithmic && funValues.front() > 1e-07 && funValues.back() > 1e-07) { double logmin = log10(funValues.front()); double lval = logmin + r * (log10(funValues.back()) - logmin); funValues[i+1] = pow(10.0, lval); } else { funValues[i+1] = funValues.front() * (1-r) + funValues.back() * r; } // count values in the i-th interval if there are any if ( min != values.end() && *min <= funValues[i+1] ) { // find the first value out of the interval max = values.upper_bound( funValues[i+1] ); // max is greater than funValues[i+1], or end() nbEvents[i] = std::distance( min, max ); min = max; } } // add values larger than minmax[1] nbEvents.back() += std::distance( min, values.end() ); } /* Class : Volume Description : Functor calculating volume of a 3D element */ double Volume::GetValue( long theElementId ) { if ( theElementId && myMesh ) { SMDS_VolumeTool aVolumeTool; if ( aVolumeTool.Set( myMesh->FindElement( theElementId ))) return aVolumeTool.GetSize(); } return 0; } double Volume::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType Volume::GetType() const { return SMDSAbs_Volume; } /* Class : MaxElementLength2D Description : Functor calculating maximum length of 2D element */ double MaxElementLength2D::GetValue( const TSequenceOfXYZ& P ) { if(P.size() == 0) return 0.; double aVal = 0; int len = P.size(); if( len == 3 ) { // triangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); aVal = Max(L1,Max(L2,L3)); } else if( len == 4 ) { // quadrangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double D1 = getDistance(P( 1 ),P( 3 )); double D2 = getDistance(P( 2 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2)); } else if( len == 6 ) { // quadratic triangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 )); aVal = Max(L1,Max(L2,L3)); } else if( len == 8 || len == 9 ) { // quadratic quadrangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 )); double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 )); double D1 = getDistance(P( 1 ),P( 5 )); double D2 = getDistance(P( 3 ),P( 7 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2)); } // Diagonals are undefined for concave polygons // else if ( P.getElementEntity() == <API key> && P.size() > 2 ) // quad polygon // // sides // aVal = getDistance( P( 1 ), P( P.size() )) + getDistance( P( P.size() ), P( P.size()-1 )); // for ( size_t i = 1; i < P.size()-1; i += 2 ) // double L = getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 )); // aVal = Max( aVal, L ); // // diagonals // for ( int i = P.size()-5; i > 0; i -= 2 ) // for ( int j = i + 4; j < P.size() + i - 2; i += 2 ) // double D = getDistance( P( i ), P( j )); // aVal = Max( aVal, D ); // { // polygons if( myPrecision >= 0 ) { double prec = pow( 10., (double)myPrecision ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } double MaxElementLength2D::GetValue( long theElementId ) { TSequenceOfXYZ P; return GetPoints( theElementId, P ) ? GetValue(P) : 0.0; } double MaxElementLength2D::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType MaxElementLength2D::GetType() const { return SMDSAbs_Face; } /* Class : MaxElementLength3D Description : Functor calculating maximum length of 3D element */ double MaxElementLength3D::GetValue( long theElementId ) { TSequenceOfXYZ P; if( GetPoints( theElementId, P ) ) { double aVal = 0; const SMDS_MeshElement* aElem = myMesh->FindElement( theElementId ); SMDSAbs_ElementType aType = aElem->GetType(); int len = P.size(); switch( aType ) { case SMDSAbs_Volume: if( len == 4 ) { // tetras double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); break; } else if( len == 5 ) { // pyramids double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 5 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(L7,L8)); break; } else if( len == 6 ) { // pentas double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),L9)); break; } else if( len == 8 ) { // hexas double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 5 )); double L10= getDistance(P( 2 ),P( 6 )); double L11= getDistance(P( 3 ),P( 7 )); double L12= getDistance(P( 4 ),P( 8 )); double D1 = getDistance(P( 1 ),P( 7 )); double D2 = getDistance(P( 2 ),P( 8 )); double D3 = getDistance(P( 3 ),P( 5 )); double D4 = getDistance(P( 4 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10))); aVal = Max(aVal,Max(L11,L12)); aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4))); break; } else if( len == 12 ) { // hexagonal prism for ( int i1 = 1; i1 < 12; ++i1 ) for ( int i2 = i1+1; i1 <= 12; ++i1 ) aVal = Max( aVal, getDistance(P( i1 ),P( i2 ))); break; } else if( len == 10 ) { // quadratic tetras double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); break; } else if( len == 13 ) { // quadratic pyramids double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(L7,L8)); break; } else if( len == 15 ) { // quadratic pentas double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),L9)); break; } else if( len == 20 || len == 27 ) { // quadratic hexas double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 )); double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 )); double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 )); double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 )); double D1 = getDistance(P( 1 ),P( 7 )); double D2 = getDistance(P( 2 ),P( 8 )); double D3 = getDistance(P( 3 ),P( 5 )); double D4 = getDistance(P( 4 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10))); aVal = Max(aVal,Max(L11,L12)); aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4))); break; } else if( len > 1 && aElem->IsPoly() ) { // polys // get the maximum distance between all pairs of nodes for( int i = 1; i <= len; i++ ) { for( int j = 1; j <= len; j++ ) { if( j > i ) { // optimization of the loop double D = getDistance( P(i), P(j) ); aVal = Max( aVal, D ); } } } } } if( myPrecision >= 0 ) { double prec = pow( 10., (double)myPrecision ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } return 0.; } double MaxElementLength3D::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType MaxElementLength3D::GetType() const { return SMDSAbs_Volume; } /* Class : MinimumAngle Description : Functor for calculation of minimum angle */ double MinimumAngle::GetValue( const TSequenceOfXYZ& P ) { double aMin; if (P.size() <3) return 0.; aMin = getAngle(P( P.size() ), P( 1 ), P( 2 )); aMin = Min(aMin,getAngle(P( P.size()-1 ), P( P.size() ), P( 1 ))); for ( int i = 2; i < P.size(); i++ ) { double A0 = getAngle( P( i-1 ), P( i ), P( i+1 ) ); aMin = Min(aMin,A0); } return aMin * 180.0 / M_PI; } double MinimumAngle::GetBadRate( double Value, int nbNodes ) const { //const double aBestAngle = PI / nbNodes; const double aBestAngle = 180.0 - ( 360.0 / double(nbNodes) ); return ( fabs( aBestAngle - Value )); } SMDSAbs_ElementType MinimumAngle::GetType() const { return SMDSAbs_Face; } /* Class : AspectRatio Description : Functor for calculating aspect ratio */ double AspectRatio::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); if ( myCurrElement && myCurrElement->GetVtkType() == VTK_QUAD ) { // issue 21723 vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid(); if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() )) aVal = Round( vtkMeshQuality::QuadAspectRatio( avtkCell )); } else { TSequenceOfXYZ P; if ( GetPoints( myCurrElement, P )) aVal = Round( GetValue( P )); } return aVal; } double AspectRatio::GetValue( const TSequenceOfXYZ& P ) { // According to "Mesh quality control" by Nadir Bouhamau referring to // Pascal Jean Frey and Paul-Louis George. Maillages, applications aux elements finis. // Hermes Science publications, Paris 1999 ISBN 2-7462-0024-4 // PAL10872 int nbNodes = P.size(); if ( nbNodes < 3 ) return 0; // Compute aspect ratio if ( nbNodes == 3 ) { // Compute lengths of the sides std::vector< double > aLen (nbNodes); for ( int i = 0; i < nbNodes - 1; i++ ) aLen[ i ] = getDistance( P( i + 1 ), P( i + 2 ) ); aLen[ nbNodes - 1 ] = getDistance( P( 1 ), P( nbNodes ) ); // Q = alfa * h * p / S, where // alfa = sqrt( 3 ) / 6 // h - length of the longest edge // p - half perimeter // S - triangle surface const double alfa = sqrt( 3. ) / 6.; double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) ); double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.; double anArea = getArea( P( 1 ), P( 2 ), P( 3 ) ); if ( anArea <= theEps ) return theInf; return alfa * maxLen * half_perimeter / anArea; } else if ( nbNodes == 6 ) { // quadratic triangles // Compute lengths of the sides std::vector< double > aLen (3); aLen[0] = getDistance( P(1), P(3) ); aLen[1] = getDistance( P(3), P(5) ); aLen[2] = getDistance( P(5), P(1) ); // Q = alfa * h * p / S, where // alfa = sqrt( 3 ) / 6 // h - length of the longest edge // p - half perimeter // S - triangle surface const double alfa = sqrt( 3. ) / 6.; double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) ); double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.; double anArea = getArea( P(1), P(3), P(5) ); if ( anArea <= theEps ) return theInf; return alfa * maxLen * half_perimeter / anArea; } else if( nbNodes == 4 ) { // quadrangle // Compute lengths of the sides std::vector< double > aLen (4); aLen[0] = getDistance( P(1), P(2) ); aLen[1] = getDistance( P(2), P(3) ); aLen[2] = getDistance( P(3), P(4) ); aLen[3] = getDistance( P(4), P(1) ); // Compute lengths of the diagonals std::vector< double > aDia (2); aDia[0] = getDistance( P(1), P(3) ); aDia[1] = getDistance( P(2), P(4) ); // Compute areas of all triangles which can be built // taking three nodes of the quadrangle std::vector< double > anArea (4); anArea[0] = getArea( P(1), P(2), P(3) ); anArea[1] = getArea( P(1), P(2), P(4) ); anArea[2] = getArea( P(1), P(3), P(4) ); anArea[3] = getArea( P(2), P(3), P(4) ); // Q = alpha * L * C1 / C2, where // alpha = sqrt( 1/32 ) // L = max( L1, L2, L3, L4, D1, D2 ) // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 ) // C2 = min( S1, S2, S3, S4 ) // Li - lengths of the edges // Di - lengths of the diagonals // Si - areas of the triangles const double alpha = sqrt( 1 / 32. ); double L = Max( aLen[ 0 ], Max( aLen[ 1 ], Max( aLen[ 2 ], Max( aLen[ 3 ], Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) ); double C1 = sqrt( ( aLen[0] * aLen[0] + aLen[1] * aLen[1] + aLen[2] * aLen[2] + aLen[3] * aLen[3] ) / 4. ); double C2 = Min( anArea[ 0 ], Min( anArea[ 1 ], Min( anArea[ 2 ], anArea[ 3 ] ) ) ); if ( C2 <= theEps ) return theInf; return alpha * L * C1 / C2; } else if( nbNodes == 8 || nbNodes == 9 ) { // nbNodes==8 - quadratic quadrangle // Compute lengths of the sides std::vector< double > aLen (4); aLen[0] = getDistance( P(1), P(3) ); aLen[1] = getDistance( P(3), P(5) ); aLen[2] = getDistance( P(5), P(7) ); aLen[3] = getDistance( P(7), P(1) ); // Compute lengths of the diagonals std::vector< double > aDia (2); aDia[0] = getDistance( P(1), P(5) ); aDia[1] = getDistance( P(3), P(7) ); // Compute areas of all triangles which can be built // taking three nodes of the quadrangle std::vector< double > anArea (4); anArea[0] = getArea( P(1), P(3), P(5) ); anArea[1] = getArea( P(1), P(3), P(7) ); anArea[2] = getArea( P(1), P(5), P(7) ); anArea[3] = getArea( P(3), P(5), P(7) ); // Q = alpha * L * C1 / C2, where // alpha = sqrt( 1/32 ) // L = max( L1, L2, L3, L4, D1, D2 ) // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 ) // C2 = min( S1, S2, S3, S4 ) // Li - lengths of the edges // Di - lengths of the diagonals // Si - areas of the triangles const double alpha = sqrt( 1 / 32. ); double L = Max( aLen[ 0 ], Max( aLen[ 1 ], Max( aLen[ 2 ], Max( aLen[ 3 ], Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) ); double C1 = sqrt( ( aLen[0] * aLen[0] + aLen[1] * aLen[1] + aLen[2] * aLen[2] + aLen[3] * aLen[3] ) / 4. ); double C2 = Min( anArea[ 0 ], Min( anArea[ 1 ], Min( anArea[ 2 ], anArea[ 3 ] ) ) ); if ( C2 <= theEps ) return theInf; return alpha * L * C1 / C2; } return 0; } double AspectRatio::GetBadRate( double Value, int /*nbNodes*/ ) const { // the aspect ratio is in the range [1.0,infinity] // < 1.0 = very bad, zero area // 1.0 = good // infinity = bad return ( Value < 0.9 ) ? 1000 : Value / 1000.; } SMDSAbs_ElementType AspectRatio::GetType() const { return SMDSAbs_Face; } /* Class : AspectRatio3D Description : Functor for calculating aspect ratio */ namespace{ inline double getHalfPerimeter(double theTria[3]){ return (theTria[0] + theTria[1] + theTria[2])/2.0; } inline double getArea(double theHalfPerim, double theTria[3]){ return sqrt(theHalfPerim* (<API key>[0])* (<API key>[1])* (<API key>[2])); } inline double getVolume(double theLen[6]){ double a2 = theLen[0]*theLen[0]; double b2 = theLen[1]*theLen[1]; double c2 = theLen[2]*theLen[2]; double d2 = theLen[3]*theLen[3]; double e2 = theLen[4]*theLen[4]; double f2 = theLen[5]*theLen[5]; double P = 4.0*a2*b2*d2; double Q = a2*(b2+d2-e2)-b2*(a2+d2-f2)-d2*(a2+b2-c2); double R = (b2+d2-e2)*(a2+d2-f2)*(a2+d2-f2); return sqrt(P-Q+R)/12.0; } inline double getVolume2(double theLen[6]){ double a2 = theLen[0]*theLen[0]; double b2 = theLen[1]*theLen[1]; double c2 = theLen[2]*theLen[2]; double d2 = theLen[3]*theLen[3]; double e2 = theLen[4]*theLen[4]; double f2 = theLen[5]*theLen[5]; double P = a2*e2*(b2+c2+d2+f2-a2-e2); double Q = b2*f2*(a2+c2+d2+e2-b2-f2); double R = c2*d2*(a2+b2+e2+f2-c2-d2); double S = a2*b2*d2+b2*c2*e2+a2*c2*f2+d2*e2*f2; return sqrt(P+Q+R-S)/12.0; } inline double getVolume(const TSequenceOfXYZ& P){ gp_Vec aVec1( P( 2 ) - P( 1 ) ); gp_Vec aVec2( P( 3 ) - P( 1 ) ); gp_Vec aVec3( P( 4 ) - P( 1 ) ); gp_Vec anAreaVec( aVec1 ^ aVec2 ); return fabs(aVec3 * anAreaVec) / 6.0; } inline double getMaxHeight(double theLen[6]) { double aHeight = std::max(theLen[0],theLen[1]); aHeight = std::max(aHeight,theLen[2]); aHeight = std::max(aHeight,theLen[3]); aHeight = std::max(aHeight,theLen[4]); aHeight = std::max(aHeight,theLen[5]); return aHeight; } } double AspectRatio3D::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); if ( myCurrElement && myCurrElement->GetVtkType() == VTK_TETRA ) { // Action from CoTech | ACTION 31.3: // EURIWARE BO: Homogenize the formulas used to calculate the Controls in SMESH to fit with // those of ParaView. The library used by ParaView for those calculations can be reused in SMESH. vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid(); if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() )) aVal = Round( vtkMeshQuality::TetAspectRatio( avtkCell )); } else { TSequenceOfXYZ P; if ( GetPoints( myCurrElement, P )) aVal = Round( GetValue( P )); } return aVal; } double AspectRatio3D::GetValue( const TSequenceOfXYZ& P ) { double aQuality = 0.0; if(myCurrElement->IsPoly()) return aQuality; int nbNodes = P.size(); if(myCurrElement->IsQuadratic()) { if(nbNodes==10) nbNodes=4; // quadratic tetrahedron else if(nbNodes==13) nbNodes=5; // quadratic pyramid else if(nbNodes==15) nbNodes=6; // quadratic pentahedron else if(nbNodes==20) nbNodes=8; // quadratic hexahedron else if(nbNodes==27) nbNodes=8; // quadratic hexahedron else return aQuality; } switch(nbNodes) { case 4:{ double aLen[6] = { getDistance(P( 1 ),P( 2 )), getDistance(P( 2 ),P( 3 )), getDistance(P( 3 ),P( 1 )), getDistance(P( 2 ),P( 4 )), getDistance(P( 3 ),P( 4 )), getDistance(P( 1 ),P( 4 )) }; double aTria[4][3] = { {aLen[0],aLen[1],aLen[2]}, // abc {aLen[0],aLen[3],aLen[5]}, // adf {aLen[1],aLen[3],aLen[4]}, // bde {aLen[2],aLen[4],aLen[5]} // cef }; double aSumArea = 0.0; double aHalfPerimeter = getHalfPerimeter(aTria[0]); double anArea = getArea(aHalfPerimeter,aTria[0]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[1]); anArea = getArea(aHalfPerimeter,aTria[1]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[2]); anArea = getArea(aHalfPerimeter,aTria[2]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[3]); anArea = getArea(aHalfPerimeter,aTria[3]); aSumArea += anArea; double aVolume = getVolume(P); //double aVolume = getVolume(aLen); double aHeight = getMaxHeight(aLen); static double aCoeff = sqrt(2.0)/12.0; if ( aVolume > DBL_MIN ) aQuality = aCoeff*aHeight*aSumArea/aVolume; break; } case 5:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 3 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 3 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 6:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 8:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 5 ),P( 8 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 4 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 6 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 6 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 5 ),P( 6 ),P( 8 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 7 ),P( 8 ),P( 6 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 2 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 12: { gp_XYZ aXYZ[8] = {P( 1 ),P( 2 ),P( 4 ),P( 5 ),P( 7 ),P( 8 ),P( 10 ),P( 11 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } { gp_XYZ aXYZ[8] = {P( 2 ),P( 3 ),P( 5 ),P( 6 ),P( 8 ),P( 9 ),P( 11 ),P( 12 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } { gp_XYZ aXYZ[8] = {P( 3 ),P( 4 ),P( 6 ),P( 1 ),P( 9 ),P( 10 ),P( 12 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } break; } // switch(nbNodes) if ( nbNodes > 4 ) { // avaluate aspect ratio of quadranle faces AspectRatio aspect2D; SMDS_VolumeTool::VolumeType type = SMDS_VolumeTool::GetType( nbNodes ); int nbFaces = SMDS_VolumeTool::NbFaces( type ); TSequenceOfXYZ points(4); for ( int i = 0; i < nbFaces; ++i ) { // loop on faces of a volume if ( SMDS_VolumeTool::NbFaceNodes( type, i ) != 4 ) continue; const int* pInd = SMDS_VolumeTool::GetFaceNodesIndices( type, i, true ); for ( int p = 0; p < 4; ++p ) // loop on nodes of a quadranle face points( p + 1 ) = P( pInd[ p ] + 1 ); aQuality = std::max( aQuality, aspect2D.GetValue( points )); } } return aQuality; } double AspectRatio3D::GetBadRate( double Value, int /*nbNodes*/ ) const { // the aspect ratio is in the range [1.0,infinity] // 1.0 = good // infinity = bad return Value / 1000.; } SMDSAbs_ElementType AspectRatio3D::GetType() const { return SMDSAbs_Volume; } /* Class : Warping Description : Functor for calculating warping */ double Warping::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 4 ) return 0; gp_XYZ G = ( P( 1 ) + P( 2 ) + P( 3 ) + P( 4 ) ) / 4.; double A1 = ComputeA( P( 1 ), P( 2 ), P( 3 ), G ); double A2 = ComputeA( P( 2 ), P( 3 ), P( 4 ), G ); double A3 = ComputeA( P( 3 ), P( 4 ), P( 1 ), G ); double A4 = ComputeA( P( 4 ), P( 1 ), P( 2 ), G ); double val = Max( Max( A1, A2 ), Max( A3, A4 ) ); const double eps = 0.1; // val is in degrees return val < eps ? 0. : val; } double Warping::ComputeA( const gp_XYZ& thePnt1, const gp_XYZ& thePnt2, const gp_XYZ& thePnt3, const gp_XYZ& theG ) const { double aLen1 = gp_Pnt( thePnt1 ).Distance( gp_Pnt( thePnt2 ) ); double aLen2 = gp_Pnt( thePnt2 ).Distance( gp_Pnt( thePnt3 ) ); double L = Min( aLen1, aLen2 ) * 0.5; if ( L < theEps ) return theInf; gp_XYZ GI = ( thePnt2 + thePnt1 ) / 2. - theG; gp_XYZ GJ = ( thePnt3 + thePnt2 ) / 2. - theG; gp_XYZ N = GI.Crossed( GJ ); if ( N.Modulus() < gp::Resolution() ) return M_PI / 2; N.Normalize(); double H = ( thePnt2 - theG ).Dot( N ); return asin( fabs( H / L ) ) * 180. / M_PI; } double Warping::GetBadRate( double Value, int /*nbNodes*/ ) const { // the warp is in the range [0.0,PI/2] // 0.0 = good (no warp) // PI/2 = bad (face pliee) return Value; } SMDSAbs_ElementType Warping::GetType() const { return SMDSAbs_Face; } /* Class : Taper Description : Functor for calculating taper */ double Taper::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 4 ) return 0.; // Compute taper double J1 = getArea( P( 4 ), P( 1 ), P( 2 ) ); double J2 = getArea( P( 3 ), P( 1 ), P( 2 ) ); double J3 = getArea( P( 2 ), P( 3 ), P( 4 ) ); double J4 = getArea( P( 3 ), P( 4 ), P( 1 ) ); double JA = 0.25 * ( J1 + J2 + J3 + J4 ); if ( JA <= theEps ) return theInf; double T1 = fabs( ( J1 - JA ) / JA ); double T2 = fabs( ( J2 - JA ) / JA ); double T3 = fabs( ( J3 - JA ) / JA ); double T4 = fabs( ( J4 - JA ) / JA ); double val = Max( Max( T1, T2 ), Max( T3, T4 ) ); const double eps = 0.01; return val < eps ? 0. : val; } double Taper::GetBadRate( double Value, int /*nbNodes*/ ) const { // the taper is in the range [0.0,1.0] // 0.0 = good (no taper) // 1.0 = bad (les cotes opposes sont allignes) return Value; } SMDSAbs_ElementType Taper::GetType() const { return SMDSAbs_Face; } /* Class : Skew Description : Functor for calculating skew in degrees */ static inline double skewAngle( const gp_XYZ& p1, const gp_XYZ& p2, const gp_XYZ& p3 ) { gp_XYZ p12 = ( p2 + p1 ) / 2.; gp_XYZ p23 = ( p3 + p2 ) / 2.; gp_XYZ p31 = ( p3 + p1 ) / 2.; gp_Vec v1( p31 - p2 ), v2( p12 - p23 ); return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0. : v1.Angle( v2 ); } double Skew::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 3 && P.size() != 4 ) return 0.; // Compute skew const double PI2 = M_PI / 2.; if ( P.size() == 3 ) { double A0 = fabs( PI2 - skewAngle( P( 3 ), P( 1 ), P( 2 ) ) ); double A1 = fabs( PI2 - skewAngle( P( 1 ), P( 2 ), P( 3 ) ) ); double A2 = fabs( PI2 - skewAngle( P( 2 ), P( 3 ), P( 1 ) ) ); return Max( A0, Max( A1, A2 ) ) * 180. / M_PI; } else { gp_XYZ p12 = ( P( 1 ) + P( 2 ) ) / 2.; gp_XYZ p23 = ( P( 2 ) + P( 3 ) ) / 2.; gp_XYZ p34 = ( P( 3 ) + P( 4 ) ) / 2.; gp_XYZ p41 = ( P( 4 ) + P( 1 ) ) / 2.; gp_Vec v1( p34 - p12 ), v2( p23 - p41 ); double A = v1.Magnitude() <= gp::Resolution() || v2.Magnitude() <= gp::Resolution() ? 0. : fabs( PI2 - v1.Angle( v2 ) ); double val = A * 180. / M_PI; const double eps = 0.1; // val is in degrees return val < eps ? 0. : val; } } double Skew::GetBadRate( double Value, int /*nbNodes*/ ) const { // the skew is in the range [0.0,PI/2]. // 0.0 = good // PI/2 = bad return Value; } SMDSAbs_ElementType Skew::GetType() const { return SMDSAbs_Face; } /* Class : Area Description : Functor for calculating area */ double Area::GetValue( const TSequenceOfXYZ& P ) { double val = 0.0; if ( P.size() > 2 ) { gp_Vec aVec1( P(2) - P(1) ); gp_Vec aVec2( P(3) - P(1) ); gp_Vec SumVec = aVec1 ^ aVec2; for (int i=4; i<=P.size(); i++) { gp_Vec aVec1( P(i-1) - P(1) ); gp_Vec aVec2( P(i) - P(1) ); gp_Vec tmp = aVec1 ^ aVec2; SumVec.Add(tmp); } val = SumVec.Magnitude() * 0.5; } return val; } double Area::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType Area::GetType() const { return SMDSAbs_Face; } /* Class : Length Description : Functor for calculating length of edge */ double Length::GetValue( const TSequenceOfXYZ& P ) { switch ( P.size() ) { case 2: return getDistance( P( 1 ), P( 2 ) ); case 3: return getDistance( P( 1 ), P( 2 ) ) + getDistance( P( 2 ), P( 3 ) ); default: return 0.; } } double Length::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType Length::GetType() const { return SMDSAbs_Edge; } /* Class : Length2D Description : Functor for calculating minimal length of edge */ double Length2D::GetValue( long theElementId ) { TSequenceOfXYZ P; if ( GetPoints( theElementId, P )) { double aVal = 0; int len = P.size(); SMDSAbs_EntityType aType = P.getElementEntity(); switch (aType) { case SMDSEntity_Edge: if (len == 2) aVal = getDistance( P( 1 ), P( 2 ) ); break; case <API key>: if (len == 3) // quadratic edge aVal = getDistance(P( 1 ),P( 3 )) + getDistance(P( 3 ),P( 2 )); break; case SMDSEntity_Triangle: if (len == 3){ // triangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); aVal = Min(L1,Min(L2,L3)); } break; case <API key>: if (len == 4){ // quadrangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); aVal = Min(Min(L1,L2),Min(L3,L4)); } break; case <API key>: case <API key>: if (len >= 6){ // quadratic triangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 )); aVal = Min(L1,Min(L2,L3)); } break; case <API key>: case <API key>: if (len >= 8){ // quadratic quadrangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 )); double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 )); aVal = Min(Min(L1,L2),Min(L3,L4)); } break; case SMDSEntity_Tetra: if (len == 4){ // tetrahedra double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 4 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); } break; case SMDSEntity_Pyramid: if (len == 5){ // piramids double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 5 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(L7,L8)); } break; case SMDSEntity_Penta: if (len == 6) { // pentaidres double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 6 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),L9)); } break; case SMDSEntity_Hexa: if (len == 8){ // hexahedron double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 5 )); double L10= getDistance(P( 2 ),P( 6 )); double L11= getDistance(P( 3 ),P( 7 )); double L12= getDistance(P( 4 ),P( 8 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10))); aVal = Min(aVal,Min(L11,L12)); } break; case <API key>: if (len == 10){ // quadratic tetraidrs double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); } break; case <API key>: if (len == 13){ // quadratic piramids double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(L7,L8)); } break; case <API key>: if (len == 15){ // quadratic pentaidres double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),L9)); } break; case <API key>: case <API key>: if (len >= 20) { // quadratic hexaider double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 )); double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 )); double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 )); double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10))); aVal = Min(aVal,Min(L11,L12)); } break; case SMDSEntity_Polygon: if ( len > 1 ) { aVal = getDistance( P(1), P( P.size() )); for ( size_t i = 1; i < P.size(); ++i ) aVal = Min( aVal, getDistance( P( i ), P( i+1 ))); } break; #ifndef VTK_NO_QUAD_POLY case <API key>: if ( len > 2 ) { aVal = getDistance( P(1), P( P.size() )) + getDistance( P(P.size()), P( P.size()-1 )); for ( size_t i = 1; i < P.size()-1; i += 2 ) aVal = Min( aVal, getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 ))); } break; #endif case <API key>: if (len == 12) { // hexagonal prism double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 1 )); double L7 = getDistance(P( 7 ), P( 8 )); double L8 = getDistance(P( 8 ), P( 9 )); double L9 = getDistance(P( 9 ), P( 10 )); double L10= getDistance(P( 10 ),P( 11 )); double L11= getDistance(P( 11 ),P( 12 )); double L12= getDistance(P( 12 ),P( 7 )); double L13 = getDistance(P( 1 ),P( 7 )); double L14 = getDistance(P( 2 ),P( 8 )); double L15 = getDistance(P( 3 ),P( 9 )); double L16 = getDistance(P( 4 ),P( 10 )); double L17 = getDistance(P( 5 ),P( 11 )); double L18 = getDistance(P( 6 ),P( 12 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal, Min(Min(Min(L7,L8),Min(L9,L10)),Min(L11,L12))); aVal = Min(aVal, Min(Min(Min(L13,L14),Min(L15,L16)),Min(L17,L18))); } break; case <API key>: { } break; default: return 0; } if (aVal < 0 ) { return 0.; } if ( myPrecision >= 0 ) { double prec = pow( 10., (double)( myPrecision ) ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } return 0.; } double Length2D::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType Length2D::GetType() const { return SMDSAbs_Face; } Length2D::Value::Value(double theLength,long thePntId1, long thePntId2): myLength(theLength) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool Length2D::Value::operator<(const Length2D::Value& x) const { if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } void Length2D::GetValues(TValues& theValues) { TValues aValues; <API key> anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); if(anElem->IsQuadratic()) { const SMDS_VtkFace* F = dynamic_cast<const SMDS_VtkFace*>(anElem); // use special nodes iterator <API key> anIter = F-><API key>(); long aNodeId[4]; gp_Pnt P[4]; double aLength; const SMDS_MeshElement* aNode; if(anIter->more()){ aNode = anIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aNodeId[0] = aNodeId[1] = aNode->GetID(); aLength = 0; } for(; anIter->more(); ){ const SMDS_MeshNode* N1 = static_cast<const SMDS_MeshNode*> (anIter->next()); P[2] = gp_Pnt(N1->X(),N1->Y(),N1->Z()); aNodeId[2] = N1->GetID(); aLength = P[1].Distance(P[2]); if(!anIter->more()) break; const SMDS_MeshNode* N2 = static_cast<const SMDS_MeshNode*> (anIter->next()); P[3] = gp_Pnt(N2->X(),N2->Y(),N2->Z()); aNodeId[3] = N2->GetID(); aLength += P[2].Distance(P[3]); Value aValue1(aLength,aNodeId[1],aNodeId[2]); Value aValue2(aLength,aNodeId[2],aNodeId[3]); P[1] = P[3]; aNodeId[1] = aNodeId[3]; theValues.insert(aValue1); theValues.insert(aValue2); } aLength += P[2].Distance(P[0]); Value aValue1(aLength,aNodeId[1],aNodeId[2]); Value aValue2(aLength,aNodeId[2],aNodeId[0]); theValues.insert(aValue1); theValues.insert(aValue2); } else { <API key> aNodesIter = anElem->nodesIterator(); long aNodeId[2]; gp_Pnt P[3]; double aLength; const SMDS_MeshElement* aNode; if(aNodesIter->more()){ aNode = aNodesIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aNodeId[0] = aNodeId[1] = aNode->GetID(); aLength = 0; } for(; aNodesIter->more(); ){ aNode = aNodesIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; long anId = aNode->GetID(); P[2] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aLength = P[1].Distance(P[2]); Value aValue(aLength,aNodeId[1],anId); aNodeId[1] = anId; P[1] = P[2]; theValues.insert(aValue); } aLength = P[0].Distance(P[1]); Value aValue(aLength,aNodeId[0],aNodeId[1]); theValues.insert(aValue); } } } /* Class : MultiConnection Description : Functor for calculating number of faces conneted to the edge */ double MultiConnection::GetValue( const TSequenceOfXYZ& P ) { return 0; } double MultiConnection::GetValue( long theId ) { return <API key>( myMesh, theId ); } double MultiConnection::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType MultiConnection::GetType() const { return SMDSAbs_Edge; } /* Class : MultiConnection2D Description : Functor for calculating number of faces conneted to the edge */ double MultiConnection2D::GetValue( const TSequenceOfXYZ& P ) { return 0; } double MultiConnection2D::GetValue( long theElementId ) { int aResult = 0; const SMDS_MeshElement* aFaceElem = myMesh->FindElement(theElementId); SMDSAbs_ElementType aType = aFaceElem->GetType(); switch (aType) { case SMDSAbs_Face: { int i = 0, len = aFaceElem->NbNodes(); <API key> anIter = aFaceElem->nodesIterator(); if (!anIter) break; const SMDS_MeshNode *aNode, *aNode0; <API key> aMap, aMapPrev; for (i = 0; i <= len; i++) { aMapPrev = aMap; aMap.Clear(); int aNb = 0; if (anIter->more()) { aNode = (SMDS_MeshNode*)anIter->next(); } else { if (i == len) aNode = aNode0; else break; } if (!aNode) break; if (i == 0) aNode0 = aNode; <API key> anElemIter = aNode-><API key>(); while (anElemIter->more()) { const SMDS_MeshElement* anElem = anElemIter->next(); if (anElem != 0 && anElem->GetType() == SMDSAbs_Face) { int anId = anElem->GetID(); aMap.Add(anId); if (aMapPrev.Contains(anId)) { aNb++; } } } aResult = Max(aResult, aNb); } } break; default: aResult = 0; } return aResult; } double MultiConnection2D::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType MultiConnection2D::GetType() const { return SMDSAbs_Face; } MultiConnection2D::Value::Value(long thePntId1, long thePntId2) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool MultiConnection2D::Value::operator<(const MultiConnection2D::Value& x) const { if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } void MultiConnection2D::GetValues(MValues& theValues) { if ( !myMesh ) return; <API key> anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); <API key> aNodesIter; if ( anElem->IsQuadratic() ) aNodesIter = dynamic_cast<const SMDS_VtkFace*> (anElem)-><API key>(); else aNodesIter = anElem->nodesIterator(); long aNodeId[3]; //int aNbConnects=0; const SMDS_MeshNode* aNode0; const SMDS_MeshNode* aNode1; const SMDS_MeshNode* aNode2; if(aNodesIter->more()){ aNode0 = (SMDS_MeshNode*) aNodesIter->next(); aNode1 = aNode0; const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode1; aNodeId[0] = aNodeId[1] = aNodes->GetID(); } for(; aNodesIter->more(); ) { aNode2 = (SMDS_MeshNode*) aNodesIter->next(); long anId = aNode2->GetID(); aNodeId[2] = anId; Value aValue(aNodeId[1],aNodeId[2]); MValues::iterator aItr = theValues.find(aValue); if (aItr != theValues.end()){ aItr->second += 1; //aNbConnects = nb; } else { theValues[aValue] = 1; //aNbConnects = 1; } //cout << "NodeIds: "<<aNodeId[1]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl; aNodeId[1] = aNodeId[2]; aNode1 = aNode2; } Value aValue(aNodeId[0],aNodeId[2]); MValues::iterator aItr = theValues.find(aValue); if (aItr != theValues.end()) { aItr->second += 1; //aNbConnects = nb; } else { theValues[aValue] = 1; //aNbConnects = 1; } //cout << "NodeIds: "<<aNodeId[0]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl; } } /* Class : BallDiameter Description : Functor returning diameter of a ball element */ double BallDiameter::GetValue( long theId ) { double diameter = 0; if ( const SMDS_BallElement* ball = dynamic_cast<const SMDS_BallElement*>( myMesh->FindElement( theId ))) { diameter = ball->GetDiameter(); } return diameter; } double BallDiameter::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType BallDiameter::GetType() const { return SMDSAbs_Ball; } /* PREDICATES */ /* Class : BadOrientedVolume Description : Predicate bad oriented volumes */ BadOrientedVolume::BadOrientedVolume() { myMesh = 0; } void BadOrientedVolume::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool BadOrientedVolume::IsSatisfy( long theId ) { if ( myMesh == 0 ) return false; SMDS_VolumeTool vTool( myMesh->FindElement( theId )); return !vTool.IsForward(); } SMDSAbs_ElementType BadOrientedVolume::GetType() const { return SMDSAbs_Volume; } /* Class : BareBorderVolume */ bool BareBorderVolume::IsSatisfy(long theElementId ) { SMDS_VolumeTool myTool; if ( myTool.Set( myMesh->FindElement(theElementId))) { for ( int iF = 0; iF < myTool.NbFaces(); ++iF ) if ( myTool.IsFreeFace( iF )) { const SMDS_MeshNode** n = myTool.GetFaceNodes(iF); vector< const SMDS_MeshNode*> nodes( n, n+myTool.NbFaceNodes(iF)); if ( !myMesh->FindElement( nodes, SMDSAbs_Face, /*Nomedium=*/false)) return true; } } return false; } /* Class : BareBorderFace */ bool BareBorderFace::IsSatisfy(long theElementId ) { bool ok = false; if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId)) { if ( face->GetType() == SMDSAbs_Face ) { int nbN = face->NbCornerNodes(); for ( int i = 0; i < nbN && !ok; ++i ) { // check if a link is shared by another face const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN ); <API key> fIt = n1-><API key>( SMDSAbs_Face ); bool isShared = false; while ( !isShared && fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); isShared = ( f != face && f->GetNodeIndex(n2) != -1 ); } if ( !isShared ) { const int iQuad = face->IsQuadratic(); myLinkNodes.resize( 2 + iQuad); myLinkNodes[0] = n1; myLinkNodes[1] = n2; if ( iQuad ) myLinkNodes[2] = face->GetNode( i+nbN ); ok = !myMesh->FindElement( myLinkNodes, SMDSAbs_Edge, /*noMedium=*/false); } } } } return ok; } /* Class : <API key> */ bool <API key>::IsSatisfy(long theElementId ) { // An element is over-constrained if it has N-1 free borders where // N is the number of edges/faces for a 2D/3D element. SMDS_VolumeTool myTool; if ( myTool.Set( myMesh->FindElement(theElementId))) { int nbSharedFaces = 0; for ( int iF = 0; iF < myTool.NbFaces(); ++iF ) if ( !myTool.IsFreeFace( iF ) && ++nbSharedFaces > 1 ) break; return ( nbSharedFaces == 1 ); } return false; } /* Class : OverConstrainedFace */ bool OverConstrainedFace::IsSatisfy(long theElementId ) { // An element is over-constrained if it has N-1 free borders where // N is the number of edges/faces for a 2D/3D element. if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId)) if ( face->GetType() == SMDSAbs_Face ) { int nbSharedBorders = 0; int nbN = face->NbCornerNodes(); for ( int i = 0; i < nbN; ++i ) { // check if a link is shared by another face const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN ); <API key> fIt = n1-><API key>( SMDSAbs_Face ); bool isShared = false; while ( !isShared && fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); isShared = ( f != face && f->GetNodeIndex(n2) != -1 ); } if ( isShared && ++nbSharedBorders > 1 ) break; } return ( nbSharedBorders == 1 ); } return false; } /* Class : CoincidentNodes Description : Predicate of Coincident nodes */ CoincidentNodes::CoincidentNodes() { myToler = 1e-5; } bool CoincidentNodes::IsSatisfy( long theElementId ) { return myCoincidentIDs.Contains( theElementId ); } SMDSAbs_ElementType CoincidentNodes::GetType() const { return SMDSAbs_Node; } void CoincidentNodes::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { TIDSortedNodeSet nodesToCheck; <API key> nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true); while ( nIt->more() ) nodesToCheck.insert( nodesToCheck.end(), nIt->next() ); list< list< const SMDS_MeshNode*> > nodeGroups; SMESH_OctreeNode::FindCoincidentNodes ( nodesToCheck, &nodeGroups, myToler ); myCoincidentIDs.Clear(); list< list< const SMDS_MeshNode*> >::iterator groupIt = nodeGroups.begin(); for ( ; groupIt != nodeGroups.end(); ++groupIt ) { list< const SMDS_MeshNode*>& coincNodes = *groupIt; list< const SMDS_MeshNode*>::iterator n = coincNodes.begin(); for ( ; n != coincNodes.end(); ++n ) myCoincidentIDs.Add( (*n)->GetID() ); } } } /* Class : CoincidentElements Description : Predicate of Coincident Elements Note : This class is suitable only for visualization of Coincident Elements */ CoincidentElements::CoincidentElements() { myMesh = 0; } void CoincidentElements::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool CoincidentElements::IsSatisfy( long theElementId ) { if ( !myMesh ) return false; if ( const SMDS_MeshElement* e = myMesh->FindElement( theElementId )) { if ( e->GetType() != GetType() ) return false; set< const SMDS_MeshNode* > elemNodes( e->begin_nodes(), e->end_nodes() ); const int nbNodes = e->NbNodes(); <API key> invIt = (*elemNodes.begin())-><API key>( GetType() ); while ( invIt->more() ) { const SMDS_MeshElement* e2 = invIt->next(); if ( e2 == e || e2->NbNodes() != nbNodes ) continue; bool sameNodes = true; for ( size_t i = 0; i < elemNodes.size() && sameNodes; ++i ) sameNodes = ( elemNodes.count( e2->GetNode( i ))); if ( sameNodes ) return true; } } return false; } SMDSAbs_ElementType <API key>::GetType() const { return SMDSAbs_Edge; } SMDSAbs_ElementType <API key>::GetType() const { return SMDSAbs_Face; } SMDSAbs_ElementType <API key>::GetType() const { return SMDSAbs_Volume; } /* Class : FreeBorders Description : Predicate for free borders */ FreeBorders::FreeBorders() { myMesh = 0; } void FreeBorders::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeBorders::IsSatisfy( long theId ) { return <API key>( myMesh, theId ) == 1; } SMDSAbs_ElementType FreeBorders::GetType() const { return SMDSAbs_Edge; } /* Class : FreeEdges Description : Predicate for free Edges */ FreeEdges::FreeEdges() { myMesh = 0; } void FreeEdges::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeEdges::IsFreeEdge( const SMDS_MeshNode** theNodes, const int theFaceId ) { <API key> aMap; for ( int i = 0; i < 2; i++ ) { <API key> anElemIter = theNodes[ i ]-><API key>(SMDSAbs_Face); while( anElemIter->more() ) { if ( const SMDS_MeshElement* anElem = anElemIter->next()) { const int anId = anElem->GetID(); if ( anId != theFaceId && !aMap.Add( anId )) return false; } } } return true; } bool FreeEdges::IsSatisfy( long theId ) { if ( myMesh == 0 ) return false; const SMDS_MeshElement* aFace = myMesh->FindElement( theId ); if ( aFace == 0 || aFace->GetType() != SMDSAbs_Face || aFace->NbNodes() < 3 ) return false; <API key> anIter = aFace-><API key>(); if ( !anIter ) return false; int i = 0, nbNodes = aFace->NbNodes(); std::vector <const SMDS_MeshNode*> aNodes( nbNodes+1 ); while( anIter->more() ) if ( ! ( aNodes[ i++ ] = anIter->next() )) return false; aNodes[ nbNodes ] = aNodes[ 0 ]; for ( i = 0; i < nbNodes; i++ ) if ( IsFreeEdge( &aNodes[ i ], theId ) ) return true; return false; } SMDSAbs_ElementType FreeEdges::GetType() const { return SMDSAbs_Face; } FreeEdges::Border::Border(long theElemId, long thePntId1, long thePntId2): myElemId(theElemId) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool FreeEdges::Border::operator<(const FreeEdges::Border& x) const{ if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } inline void UpdateBorders(const FreeEdges::Border& theBorder, FreeEdges::TBorders& theRegistry, FreeEdges::TBorders& theContainer) { if(theRegistry.find(theBorder) == theRegistry.end()){ theRegistry.insert(theBorder); theContainer.insert(theBorder); }else{ theContainer.erase(theBorder); } } void FreeEdges::GetBoreders(TBorders& theBorders) { TBorders aRegistry; <API key> anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); long anElemId = anElem->GetID(); <API key> aNodesIter; if ( anElem->IsQuadratic() ) aNodesIter = static_cast<const SMDS_VtkFace*>(anElem)-> <API key>(); else aNodesIter = anElem->nodesIterator(); long aNodeId[2]; const SMDS_MeshElement* aNode; if(aNodesIter->more()){ aNode = aNodesIter->next(); aNodeId[0] = aNodeId[1] = aNode->GetID(); } for(; aNodesIter->more(); ){ aNode = aNodesIter->next(); long anId = aNode->GetID(); Border aBorder(anElemId,aNodeId[1],anId); aNodeId[1] = anId; UpdateBorders(aBorder,aRegistry,theBorders); } Border aBorder(anElemId,aNodeId[0],aNodeId[1]); UpdateBorders(aBorder,aRegistry,theBorders); } } /* Class : FreeNodes Description : Predicate for free nodes */ FreeNodes::FreeNodes() { myMesh = 0; } void FreeNodes::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeNodes::IsSatisfy( long theNodeId ) { const SMDS_MeshNode* aNode = myMesh->FindNode( theNodeId ); if (!aNode) return false; return (aNode->NbInverseElements() < 1); } SMDSAbs_ElementType FreeNodes::GetType() const { return SMDSAbs_Node; } /* Class : FreeFaces Description : Predicate for free faces */ FreeFaces::FreeFaces() { myMesh = 0; } void FreeFaces::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeFaces::IsSatisfy( long theId ) { if (!myMesh) return false; // check that faces nodes refers to less than two common volumes const SMDS_MeshElement* aFace = myMesh->FindElement( theId ); if ( !aFace || aFace->GetType() != SMDSAbs_Face ) return false; int nbNode = aFace->NbNodes(); // collect volumes to check that number of volumes with count equal nbNode not less than 2 typedef map< SMDS_MeshElement*, int > TMapOfVolume; // map of volume counters typedef map< SMDS_MeshElement*, int >::iterator TItrMapOfVolume; // iterator TMapOfVolume mapOfVol; <API key> nodeItr = aFace->nodesIterator(); while ( nodeItr->more() ) { const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(nodeItr->next()); if ( !aNode ) continue; <API key> volItr = aNode-><API key>(SMDSAbs_Volume); while ( volItr->more() ) { SMDS_MeshElement* aVol = (SMDS_MeshElement*)volItr->next(); TItrMapOfVolume itr = mapOfVol.insert(make_pair(aVol, 0)).first; (*itr).second++; } } int nbVol = 0; TItrMapOfVolume volItr = mapOfVol.begin(); TItrMapOfVolume volEnd = mapOfVol.end(); for ( ; volItr != volEnd; ++volItr ) if ( (*volItr).second >= nbNode ) nbVol++; // face is not free if number of volumes constructed on thier nodes more than one return (nbVol < 2); } SMDSAbs_ElementType FreeFaces::GetType() const { return SMDSAbs_Face; } /* Class : LinearOrQuadratic Description : Predicate to verify whether a mesh element is linear */ LinearOrQuadratic::LinearOrQuadratic() { myMesh = 0; } void LinearOrQuadratic::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool LinearOrQuadratic::IsSatisfy( long theId ) { if (!myMesh) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem || (myType != SMDSAbs_All && anElem->GetType() != myType) ) return false; return (!anElem->IsQuadratic()); } void LinearOrQuadratic::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType LinearOrQuadratic::GetType() const { return myType; } /* Class : GroupColor Description : Functor for check color of group to whic mesh element belongs to */ GroupColor::GroupColor() { } bool GroupColor::IsSatisfy( long theId ) { return myIDs.count( theId ); } void GroupColor::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType GroupColor::GetType() const { return myType; } static bool isEqual( const Quantity_Color& theColor1, const Quantity_Color& theColor2 ) { // tolerance to compare colors const double tol = 5*1e-3; return ( fabs( theColor1.Red() - theColor2.Red() ) < tol && fabs( theColor1.Green() - theColor2.Green() ) < tol && fabs( theColor1.Blue() - theColor2.Blue() ) < tol ); } void GroupColor::SetMesh( const SMDS_Mesh* theMesh ) { myIDs.clear(); const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh); if ( !aMesh ) return; int nbGrp = aMesh->GetNbGroups(); if ( !nbGrp ) return; // iterates on groups and find necessary elements ids const std::set<SMESHDS_GroupBase*>& aGroups = aMesh->GetGroups(); set<SMESHDS_GroupBase*>::const_iterator GrIt = aGroups.begin(); for (; GrIt != aGroups.end(); GrIt++) { SMESHDS_GroupBase* aGrp = (*GrIt); if ( !aGrp ) continue; // check type and color of group if ( !isEqual( myColor, aGrp->GetColor() )) continue; // IPAL52867 (prevent infinite recursion via GroupOnFilter) if ( <API key> * gof = dynamic_cast< <API key>* >( aGrp )) if ( gof->GetPredicate().get() == this ) continue; SMDSAbs_ElementType aGrpElType = (SMDSAbs_ElementType)aGrp->GetType(); if ( myType == aGrpElType || (myType == SMDSAbs_All && aGrpElType != SMDSAbs_Node) ) { // add elements IDS into control int aSize = aGrp->Extent(); for (int i = 0; i < aSize; i++) myIDs.insert( aGrp->GetID(i+1) ); } } } void GroupColor::SetColorStr( const <API key>& theStr ) { Kernel_Utils::Localizer loc; <API key> aStr = theStr; aStr.RemoveAll( ' ' ); aStr.RemoveAll( '\t' ); for ( int aPos = aStr.Search( ";;" ); aPos != -1; aPos = aStr.Search( ";;" ) ) aStr.Remove( aPos, 2 ); Standard_Real clr[3]; clr[0] = clr[1] = clr[2] = 0.; for ( int i = 0; i < 3; i++ ) { <API key> tmpStr = aStr.Token( ";", i+1 ); if ( !tmpStr.IsEmpty() && tmpStr.IsRealValue() ) clr[i] = tmpStr.RealValue(); } myColor = Quantity_Color( clr[0], clr[1], clr[2], Quantity_TOC_RGB ); } // name : GetRangeStr // Purpose : Get range as a string. // Example: "1,2,3,50-60,63,67,70-" void GroupColor::GetColorStr( <API key>& theResStr ) const { theResStr.Clear(); theResStr += <API key>( myColor.Red() ); theResStr += <API key>( ";" ) + <API key>( myColor.Green() ); theResStr += <API key>( ";" ) + <API key>( myColor.Blue() ); } /* Class : ElemGeomType Description : Predicate to check element geometry type */ ElemGeomType::ElemGeomType() { myMesh = 0; myType = SMDSAbs_All; myGeomType = SMDSGeom_TRIANGLE; } void ElemGeomType::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool ElemGeomType::IsSatisfy( long theId ) { if (!myMesh) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem ) return false; const SMDSAbs_ElementType anElemType = anElem->GetType(); if ( myType != SMDSAbs_All && anElemType != myType ) return false; bool isOk = ( anElem->GetGeomType() == myGeomType ); return isOk; } void ElemGeomType::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType ElemGeomType::GetType() const { return myType; } void ElemGeomType::SetGeomType( <API key> theType ) { myGeomType = theType; } <API key> ElemGeomType::GetGeomType() const { return myGeomType; } /* Class : ElemEntityType Description : Predicate to check element entity type */ ElemEntityType::ElemEntityType(): myMesh( 0 ), myType( SMDSAbs_All ), myEntityType( SMDSEntity_0D ) { } void ElemEntityType::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool ElemEntityType::IsSatisfy( long theId ) { if ( !myMesh ) return false; if ( myType == SMDSAbs_Node ) return myMesh->FindNode( theId ); const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); return ( anElem && myEntityType == anElem->GetEntityType() ); } void ElemEntityType::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType ElemEntityType::GetType() const { return myType; } void ElemEntityType::SetElemEntityType( SMDSAbs_EntityType theEntityType ) { myEntityType = theEntityType; } SMDSAbs_EntityType ElemEntityType::GetElemEntityType() const { return myEntityType; } /*! * \brief Class ConnectedElements */ ConnectedElements::ConnectedElements(): myNodeID(0), myType( SMDSAbs_All ), myOkIDsReady( false ) {} SMDSAbs_ElementType ConnectedElements::GetType() const { return myType; } int ConnectedElements::GetNode() const { return myXYZ.empty() ? myNodeID : 0; } // myNodeID can be found by myXYZ std::vector<double> ConnectedElements::GetPoint() const { return myXYZ; } void ConnectedElements::clearOkIDs() { myOkIDsReady = false; myOkIDs.clear(); } void ConnectedElements::SetType( SMDSAbs_ElementType theType ) { if ( myType != theType || myMeshModifTracer.IsMeshModified() ) clearOkIDs(); myType = theType; } void ConnectedElements::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { clearOkIDs(); if ( !myXYZ.empty() ) SetPoint( myXYZ[0], myXYZ[1], myXYZ[2] ); // find a node near myXYZ it in a new mesh } } void ConnectedElements::SetNode( int nodeID ) { myNodeID = nodeID; myXYZ.clear(); bool isSameDomain = false; if ( myOkIDsReady && myMeshModifTracer.GetMesh() && !myMeshModifTracer.IsMeshModified() ) if ( const SMDS_MeshNode* n = myMeshModifTracer.GetMesh()->FindNode( myNodeID )) { <API key> eIt = n-><API key>( myType ); while ( !isSameDomain && eIt->more() ) isSameDomain = IsSatisfy( eIt->next()->GetID() ); } if ( !isSameDomain ) clearOkIDs(); } void ConnectedElements::SetPoint( double x, double y, double z ) { myXYZ.resize(3); myXYZ[0] = x; myXYZ[1] = y; myXYZ[2] = z; myNodeID = 0; bool isSameDomain = false; // find myNodeID by myXYZ if possible if ( myMeshModifTracer.GetMesh() ) { auto_ptr<<API key>> searcher ( SMESH_MeshAlgos::GetElementSearcher( (SMDS_Mesh&) *myMeshModifTracer.GetMesh() )); vector< const SMDS_MeshElement* > foundElems; searcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_All, foundElems ); if ( !foundElems.empty() ) { myNodeID = foundElems[0]->GetNode(0)->GetID(); if ( myOkIDsReady && !myMeshModifTracer.IsMeshModified() ) isSameDomain = IsSatisfy( foundElems[0]->GetID() ); } } if ( !isSameDomain ) clearOkIDs(); } bool ConnectedElements::IsSatisfy( long theElementId ) { // Here we do NOT check if the mesh has changed, we do it in Set...() only!!! if ( !myOkIDsReady ) { if ( !myMeshModifTracer.GetMesh() ) return false; const SMDS_MeshNode* node0 = myMeshModifTracer.GetMesh()->FindNode( myNodeID ); if ( !node0 ) return false; list< const SMDS_MeshNode* > nodeQueue( 1, node0 ); std::set< int > checkedNodeIDs; // algo: // foreach node in nodeQueue: // foreach element sharing a node: // add ID of an element of myType to myOkIDs; // push all element nodes absent from checkedNodeIDs to nodeQueue; while ( !nodeQueue.empty() ) { const SMDS_MeshNode* node = nodeQueue.front(); nodeQueue.pop_front(); // loop on elements sharing the node <API key> eIt = node-><API key>(); while ( eIt->more() ) { // keep elements of myType const SMDS_MeshElement* element = eIt->next(); if ( element->GetType() == myType ) myOkIDs.insert( myOkIDs.end(), element->GetID() ); // enqueue nodes of the element <API key> nIt = element->nodesIterator(); while ( nIt->more() ) { const SMDS_MeshNode* n = static_cast< const SMDS_MeshNode* >( nIt->next() ); if ( checkedNodeIDs.insert( n->GetID() ).second ) nodeQueue.push_back( n ); } } } if ( myType == SMDSAbs_Node ) std::swap( myOkIDs, checkedNodeIDs ); size_t totalNbElems = myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType ); if ( myOkIDs.size() == totalNbElems ) myOkIDs.clear(); myOkIDsReady = true; } return myOkIDs.empty() ? true : myOkIDs.count( theElementId ); } /*! * \brief Class CoplanarFaces */ CoplanarFaces::CoplanarFaces() : myFaceID(0), myToler(0) { } void CoplanarFaces::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { // Build a set of coplanar face ids myCoplanarIDs.clear(); if ( !myMeshModifTracer.GetMesh() || !myFaceID || !myToler ) return; const SMDS_MeshElement* face = myMeshModifTracer.GetMesh()->FindElement( myFaceID ); if ( !face || face->GetType() != SMDSAbs_Face ) return; bool normOK; gp_Vec myNorm = getNormale( static_cast<const SMDS_MeshFace*>(face), &normOK ); if (!normOK) return; const double radianTol = myToler * M_PI / 180.; std::set< SMESH_TLink > checkedLinks; std::list< pair< const SMDS_MeshElement*, gp_Vec > > faceQueue; faceQueue.push_back( make_pair( face, myNorm )); while ( !faceQueue.empty() ) { face = faceQueue.front().first; myNorm = faceQueue.front().second; faceQueue.pop_front(); for ( int i = 0, nbN = face->NbCornerNodes(); i < nbN; ++i ) { const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode(( i+1 )%nbN); if ( !checkedLinks.insert( SMESH_TLink( n1, n2 )).second ) continue; <API key> fIt = n1-><API key>(SMDSAbs_Face); while ( fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); if ( f->GetNodeIndex( n2 ) > -1 ) { gp_Vec norm = getNormale( static_cast<const SMDS_MeshFace*>(f), &normOK ); if (!normOK || myNorm.Angle( norm ) <= radianTol) { myCoplanarIDs.insert( f->GetID() ); faceQueue.push_back( make_pair( f, norm )); } } } } } } } bool CoplanarFaces::IsSatisfy( long theElementId ) { return myCoplanarIDs.count( theElementId ); } /* *Class : RangeOfIds *Description : Predicate for Range of Ids. * Range may be specified with two ways. * 1. Using AddToRange method * 2. With SetRangeStr method. Parameter of this method is a string * like as "1,2,3,50-60,63,67,70-" */ // name : RangeOfIds // Purpose : Constructor RangeOfIds::RangeOfIds() { myMesh = 0; myType = SMDSAbs_All; } // name : SetMesh // Purpose : Set mesh void RangeOfIds::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } // name : AddToRange // Purpose : Add ID to the range bool RangeOfIds::AddToRange( long theEntityId ) { myIds.Add( theEntityId ); return true; } // name : GetRangeStr // Purpose : Get range as a string. // Example: "1,2,3,50-60,63,67,70-" void RangeOfIds::GetRangeStr( <API key>& theResStr ) { theResStr.Clear(); <API key> anIntSeq; <API key> aStrSeq; <API key> anIter( myIds ); for ( ; anIter.More(); anIter.Next() ) { int anId = anIter.Key(); <API key> aStr( anId ); anIntSeq.Append( anId ); aStrSeq.Append( aStr ); } for ( int i = 1, n = myMin.Length(); i <= n; i++ ) { int aMinId = myMin( i ); int aMaxId = myMax( i ); <API key> aStr; if ( aMinId != IntegerFirst() ) aStr += aMinId; aStr += "-"; if ( aMaxId != IntegerLast() ) aStr += aMaxId; // find position of the string in result sequence and insert string in it if ( anIntSeq.Length() == 0 ) { anIntSeq.Append( aMinId ); aStrSeq.Append( aStr ); } else { if ( aMinId < anIntSeq.First() ) { anIntSeq.Prepend( aMinId ); aStrSeq.Prepend( aStr ); } else if ( aMinId > anIntSeq.Last() ) { anIntSeq.Append( aMinId ); aStrSeq.Append( aStr ); } else for ( int j = 1, k = anIntSeq.Length(); j <= k; j++ ) if ( aMinId < anIntSeq( j ) ) { anIntSeq.InsertBefore( j, aMinId ); aStrSeq.InsertBefore( j, aStr ); break; } } } if ( aStrSeq.Length() == 0 ) return; theResStr = aStrSeq( 1 ); for ( int j = 2, k = aStrSeq.Length(); j <= k; j++ ) { theResStr += ","; theResStr += aStrSeq( j ); } } // name : SetRangeStr // Purpose : Define range with string // Example of entry string: "1,2,3,50-60,63,67,70-" bool RangeOfIds::SetRangeStr( const <API key>& theStr ) { myMin.Clear(); myMax.Clear(); myIds.Clear(); <API key> aStr = theStr; //aStr.RemoveAll( ' ' ); //aStr.RemoveAll( '\t' ); for ( int i = 1; i <= aStr.Length(); ++i ) if ( isspace( aStr.Value( i ))) aStr.SetValue( i, ','); for ( int aPos = aStr.Search( ",," ); aPos != -1; aPos = aStr.Search( ",," ) ) aStr.Remove( aPos, 1 ); <API key> tmpStr = aStr.Token( ",", 1 ); int i = 1; while ( tmpStr != "" ) { tmpStr = aStr.Token( ",", i++ ); int aPos = tmpStr.Search( '-' ); if ( aPos == -1 ) { if ( tmpStr.IsIntegerValue() ) myIds.Add( tmpStr.IntegerValue() ); else return false; } else { <API key> aMaxStr = tmpStr.Split( aPos ); <API key> aMinStr = tmpStr; while ( aMinStr.Search( "-" ) != -1 ) aMinStr.RemoveAll( '-' ); while ( aMaxStr.Search( "-" ) != -1 ) aMaxStr.RemoveAll( '-' ); if ( (!aMinStr.IsEmpty() && !aMinStr.IsIntegerValue()) || (!aMaxStr.IsEmpty() && !aMaxStr.IsIntegerValue()) ) return false; myMin.Append( aMinStr.IsEmpty() ? IntegerFirst() : aMinStr.IntegerValue() ); myMax.Append( aMaxStr.IsEmpty() ? IntegerLast() : aMaxStr.IntegerValue() ); } } return true; } // name : GetType // Purpose : Get type of supported entities SMDSAbs_ElementType RangeOfIds::GetType() const { return myType; } // name : SetType // Purpose : Set type of supported entities void RangeOfIds::SetType( SMDSAbs_ElementType theType ) { myType = theType; } // name : IsSatisfy // Purpose : Verify whether entity satisfies to this rpedicate bool RangeOfIds::IsSatisfy( long theId ) { if ( !myMesh ) return false; if ( myType == SMDSAbs_Node ) { if ( myMesh->FindNode( theId ) == 0 ) return false; } else { const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( anElem == 0 || (myType != anElem->GetType() && myType != SMDSAbs_All )) return false; } if ( myIds.Contains( theId ) ) return true; for ( int i = 1, n = myMin.Length(); i <= n; i++ ) if ( theId >= myMin( i ) && theId <= myMax( i ) ) return true; return false; } /* Class : Comparator Description : Base class for comparators */ Comparator::Comparator(): myMargin(0) {} Comparator::~Comparator() {} void Comparator::SetMesh( const SMDS_Mesh* theMesh ) { if ( myFunctor ) myFunctor->SetMesh( theMesh ); } void Comparator::SetMargin( double theValue ) { myMargin = theValue; } void Comparator::SetNumFunctor( NumericalFunctorPtr theFunct ) { myFunctor = theFunct; } SMDSAbs_ElementType Comparator::GetType() const { return myFunctor ? myFunctor->GetType() : SMDSAbs_All; } double Comparator::GetMargin() { return myMargin; } /* Class : LessThan Description : Comparator "<" */ bool LessThan::IsSatisfy( long theId ) { return myFunctor && myFunctor->GetValue( theId ) < myMargin; } /* Class : MoreThan Description : Comparator ">" */ bool MoreThan::IsSatisfy( long theId ) { return myFunctor && myFunctor->GetValue( theId ) > myMargin; } /* Class : EqualTo Description : Comparator "=" */ EqualTo::EqualTo(): myToler(Precision::Confusion()) {} bool EqualTo::IsSatisfy( long theId ) { return myFunctor && fabs( myFunctor->GetValue( theId ) - myMargin ) < myToler; } void EqualTo::SetTolerance( double theToler ) { myToler = theToler; } double EqualTo::GetTolerance() { return myToler; } /* Class : LogicalNOT Description : Logical NOT predicate */ LogicalNOT::LogicalNOT() {} LogicalNOT::~LogicalNOT() {} bool LogicalNOT::IsSatisfy( long theId ) { return myPredicate && !myPredicate->IsSatisfy( theId ); } void LogicalNOT::SetMesh( const SMDS_Mesh* theMesh ) { if ( myPredicate ) myPredicate->SetMesh( theMesh ); } void LogicalNOT::SetPredicate( PredicatePtr thePred ) { myPredicate = thePred; } SMDSAbs_ElementType LogicalNOT::GetType() const { return myPredicate ? myPredicate->GetType() : SMDSAbs_All; } /* Class : LogicalBinary Description : Base class for binary logical predicate */ LogicalBinary::LogicalBinary() {} LogicalBinary::~LogicalBinary() {} void LogicalBinary::SetMesh( const SMDS_Mesh* theMesh ) { if ( myPredicate1 ) myPredicate1->SetMesh( theMesh ); if ( myPredicate2 ) myPredicate2->SetMesh( theMesh ); } void LogicalBinary::SetPredicate1( PredicatePtr thePredicate ) { myPredicate1 = thePredicate; } void LogicalBinary::SetPredicate2( PredicatePtr thePredicate ) { myPredicate2 = thePredicate; } SMDSAbs_ElementType LogicalBinary::GetType() const { if ( !myPredicate1 || !myPredicate2 ) return SMDSAbs_All; SMDSAbs_ElementType aType1 = myPredicate1->GetType(); SMDSAbs_ElementType aType2 = myPredicate2->GetType(); return aType1 == aType2 ? aType1 : SMDSAbs_All; } /* Class : LogicalAND Description : Logical AND */ bool LogicalAND::IsSatisfy( long theId ) { return myPredicate1 && myPredicate2 && myPredicate1->IsSatisfy( theId ) && myPredicate2->IsSatisfy( theId ); } /* Class : LogicalOR Description : Logical OR */ bool LogicalOR::IsSatisfy( long theId ) { return myPredicate1 && myPredicate2 && (myPredicate1->IsSatisfy( theId ) || myPredicate2->IsSatisfy( theId )); } /* FILTER */ // #ifdef WITH_TBB // #include <tbb/parallel_for.h> // #include <tbb/<API key>.h> // namespace Parallel // typedef tbb::<API key>< TIdSequence > TIdSeq; // struct Predicate // const SMDS_Mesh* myMesh; // PredicatePtr myPredicate; // TIdSeq & myOKIds; // Predicate( const SMDS_Mesh* m, PredicatePtr p, TIdSeq & ids ): // myMesh(m), myPredicate(p->Duplicate()), myOKIds(ids) {} // void operator() ( const tbb::blocked_range<size_t>& r ) const // for ( size_t i = r.begin(); i != r.end(); ++i ) // if ( myPredicate->IsSatisfy( i )) // myOKIds.local().push_back(); // #endif Filter::Filter() {} Filter::~Filter() {} void Filter::SetPredicate( PredicatePtr thePredicate ) { myPredicate = thePredicate; } void Filter::GetElementsId( const SMDS_Mesh* theMesh, PredicatePtr thePredicate, TIdSequence& theSequence ) { theSequence.clear(); if ( !theMesh || !thePredicate ) return; thePredicate->SetMesh( theMesh ); <API key> elemIt = theMesh->elementsIterator( thePredicate->GetType() ); if ( elemIt ) { while ( elemIt->more() ) { const SMDS_MeshElement* anElem = elemIt->next(); long anId = anElem->GetID(); if ( thePredicate->IsSatisfy( anId ) ) theSequence.push_back( anId ); } } } void Filter::GetElementsId( const SMDS_Mesh* theMesh, Filter::TIdSequence& theSequence ) { GetElementsId(theMesh,myPredicate,theSequence); } /* ManifoldPart */ typedef std::set<SMDS_MeshFace*> TMapOfFacePtr; /* Internal class Link */ ManifoldPart::Link::Link( SMDS_MeshNode* theNode1, SMDS_MeshNode* theNode2 ) { myNode1 = theNode1; myNode2 = theNode2; } ManifoldPart::Link::~Link() { myNode1 = 0; myNode2 = 0; } bool ManifoldPart::Link::IsEqual( const ManifoldPart::Link& theLink ) const { if ( myNode1 == theLink.myNode1 && myNode2 == theLink.myNode2 ) return true; else if ( myNode1 == theLink.myNode2 && myNode2 == theLink.myNode1 ) return true; else return false; } bool ManifoldPart::Link::operator<( const ManifoldPart::Link& x ) const { if(myNode1 < x.myNode1) return true; if(myNode1 == x.myNode1) if(myNode2 < x.myNode2) return true; return false; } bool ManifoldPart::IsEqual( const ManifoldPart::Link& theLink1, const ManifoldPart::Link& theLink2 ) { return theLink1.IsEqual( theLink2 ); } ManifoldPart::ManifoldPart() { myMesh = 0; myAngToler = Precision::Angular(); myIsOnlyManifold = true; } ManifoldPart::~ManifoldPart() { myMesh = 0; } void ManifoldPart::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; process(); } SMDSAbs_ElementType ManifoldPart::GetType() const { return SMDSAbs_Face; } bool ManifoldPart::IsSatisfy( long theElementId ) { return myMapIds.Contains( theElementId ); } void ManifoldPart::SetAngleTolerance( const double theAngToler ) { myAngToler = theAngToler; } double ManifoldPart::GetAngleTolerance() const { return myAngToler; } void ManifoldPart::SetIsOnlyManifold( const bool theIsOnly ) { myIsOnlyManifold = theIsOnly; } void ManifoldPart::SetStartElem( const long theStartId ) { myStartElemId = theStartId; } bool ManifoldPart::process() { myMapIds.Clear(); myMapBadGeomIds.Clear(); myAllFacePtr.clear(); myAllFacePtrIntDMap.clear(); if ( !myMesh ) return false; // collect all faces into own map <API key> anFaceItr = myMesh->facesIterator(); for (; anFaceItr->more(); ) { SMDS_MeshFace* aFacePtr = (SMDS_MeshFace*)anFaceItr->next(); myAllFacePtr.push_back( aFacePtr ); myAllFacePtrIntDMap[aFacePtr] = myAllFacePtr.size()-1; } SMDS_MeshFace* aStartFace = (SMDS_MeshFace*)myMesh->FindElement( myStartElemId ); if ( !aStartFace ) return false; // the map of non manifold links and bad geometry TMapOfLink aMapOfNonManifold; <API key> aMapOfTreated; // begin cycle on faces from start index and run on vector till the end // and from begin to start index to cover whole vector const int aStartIndx = myAllFacePtrIntDMap[aStartFace]; bool isStartTreat = false; for ( int fi = aStartIndx; !isStartTreat || fi != aStartIndx ; fi++ ) { if ( fi == aStartIndx ) isStartTreat = true; // as result next time when fi will be equal to aStartIndx SMDS_MeshFace* aFacePtr = myAllFacePtr[ fi ]; if ( aMapOfTreated.Contains( aFacePtr->GetID() ) ) continue; aMapOfTreated.Add( aFacePtr->GetID() ); <API key> aResFaces; if ( !findConnected( myAllFacePtrIntDMap, aFacePtr, aMapOfNonManifold, aResFaces ) ) continue; <API key> anItr( aResFaces ); for ( ; anItr.More(); anItr.Next() ) { int aFaceId = anItr.Key(); aMapOfTreated.Add( aFaceId ); myMapIds.Add( aFaceId ); } if ( fi == ( myAllFacePtr.size() - 1 ) ) fi = 0; } // end run on vector of faces return !myMapIds.IsEmpty(); } static void getLinks( const SMDS_MeshFace* theFace, ManifoldPart::TVectorOfLink& theLinks ) { int aNbNode = theFace->NbNodes(); <API key> aNodeItr = theFace->nodesIterator(); int i = 1; SMDS_MeshNode* aNode = 0; for ( ; aNodeItr->more() && i <= aNbNode; ) { SMDS_MeshNode* aN1 = (SMDS_MeshNode*)aNodeItr->next(); if ( i == 1 ) aNode = aN1; i++; SMDS_MeshNode* aN2 = ( i >= aNbNode ) ? aNode : (SMDS_MeshNode*)aNodeItr->next(); i++; ManifoldPart::Link aLink( aN1, aN2 ); theLinks.push_back( aLink ); } } bool ManifoldPart::findConnected ( const ManifoldPart::TDataMapFacePtrInt& theAllFacePtrInt, SMDS_MeshFace* theStartFace, ManifoldPart::TMapOfLink& theNonManifold, <API key>& theResFaces ) { theResFaces.Clear(); if ( !theAllFacePtrInt.size() ) return false; if ( getNormale( theStartFace ).SquareModulus() <= gp::Resolution() ) { myMapBadGeomIds.Add( theStartFace->GetID() ); return false; } ManifoldPart::TMapOfLink aMapOfBoundary, aMapToSkip; ManifoldPart::TVectorOfLink aSeqOfBoundary; theResFaces.Add( theStartFace->GetID() ); ManifoldPart::<API key> aDMapLinkFace; expandBoundary( aMapOfBoundary, aSeqOfBoundary, aDMapLinkFace, theNonManifold, theStartFace ); bool isDone = false; while ( !isDone && aMapOfBoundary.size() != 0 ) { bool isToReset = false; ManifoldPart::TVectorOfLink::iterator pLink = aSeqOfBoundary.begin(); for ( ; !isToReset && pLink != aSeqOfBoundary.end(); ++pLink ) { ManifoldPart::Link aLink = *pLink; if ( aMapToSkip.find( aLink ) != aMapToSkip.end() ) continue; // each link could be treated only once aMapToSkip.insert( aLink ); ManifoldPart::TVectorOfFacePtr aFaces; // find next if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) ) continue; else { getFacesByLink( aLink, aFaces ); // filter the element to keep only indicated elements ManifoldPart::TVectorOfFacePtr aFiltered; ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin(); for ( ; pFace != aFaces.end(); ++pFace ) { SMDS_MeshFace* aFace = *pFace; if ( myAllFacePtrIntDMap.find( aFace ) != myAllFacePtrIntDMap.end() ) aFiltered.push_back( aFace ); } aFaces = aFiltered; if ( aFaces.size() < 2 ) // no neihgbour faces continue; else if ( myIsOnlyManifold && aFaces.size() > 2 ) // non manifold case { theNonManifold.insert( aLink ); continue; } } // compare normal with normals of neighbor element SMDS_MeshFace* aPrevFace = aDMapLinkFace[ aLink ]; ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin(); for ( ; pFace != aFaces.end(); ++pFace ) { SMDS_MeshFace* aNextFace = *pFace; if ( aPrevFace == aNextFace ) continue; int anNextFaceID = aNextFace->GetID(); if ( myIsOnlyManifold && theResFaces.Contains( anNextFaceID ) ) // should not be with non manifold restriction. probably bad topology continue; // check if face was treated and skipped if ( myMapBadGeomIds.Contains( anNextFaceID ) || !isInPlane( aPrevFace, aNextFace ) ) continue; // add new element to connected and extend the boundaries. theResFaces.Add( anNextFaceID ); expandBoundary( aMapOfBoundary, aSeqOfBoundary, aDMapLinkFace, theNonManifold, aNextFace ); isToReset = true; } } isDone = !isToReset; } return !theResFaces.IsEmpty(); } bool ManifoldPart::isInPlane( const SMDS_MeshFace* theFace1, const SMDS_MeshFace* theFace2 ) { gp_Dir aNorm1 = gp_Dir( getNormale( theFace1 ) ); gp_XYZ aNorm2XYZ = getNormale( theFace2 ); if ( aNorm2XYZ.SquareModulus() <= gp::Resolution() ) { myMapBadGeomIds.Add( theFace2->GetID() ); return false; } if ( aNorm1.IsParallel( gp_Dir( aNorm2XYZ ), myAngToler ) ) return true; return false; } void ManifoldPart::expandBoundary ( ManifoldPart::TMapOfLink& theMapOfBoundary, ManifoldPart::TVectorOfLink& theSeqOfBoundary, ManifoldPart::<API key>& theDMapLinkFacePtr, ManifoldPart::TMapOfLink& theNonManifold, SMDS_MeshFace* theNextFace ) const { ManifoldPart::TVectorOfLink aLinks; getLinks( theNextFace, aLinks ); int aNbLink = (int)aLinks.size(); for ( int i = 0; i < aNbLink; i++ ) { ManifoldPart::Link aLink = aLinks[ i ]; if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) ) continue; if ( theMapOfBoundary.find( aLink ) != theMapOfBoundary.end() ) { if ( myIsOnlyManifold ) { // remove from boundary theMapOfBoundary.erase( aLink ); ManifoldPart::TVectorOfLink::iterator pLink = theSeqOfBoundary.begin(); for ( ; pLink != theSeqOfBoundary.end(); ++pLink ) { ManifoldPart::Link aBoundLink = *pLink; if ( aBoundLink.IsEqual( aLink ) ) { theSeqOfBoundary.erase( pLink ); break; } } } } else { theMapOfBoundary.insert( aLink ); theSeqOfBoundary.push_back( aLink ); theDMapLinkFacePtr[ aLink ] = theNextFace; } } } void ManifoldPart::getFacesByLink( const ManifoldPart::Link& theLink, ManifoldPart::TVectorOfFacePtr& theFaces ) const { std::set<SMDS_MeshCell *> aSetOfFaces; // take all faces that shared first node <API key> anItr = theLink.myNode1->facesIterator(); for ( ; anItr->more(); ) { SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next(); if ( !aFace ) continue; aSetOfFaces.insert( aFace ); } // take all faces that shared second node anItr = theLink.myNode2->facesIterator(); // find the common part of two sets for ( ; anItr->more(); ) { SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next(); if ( aSetOfFaces.count( aFace ) ) theFaces.push_back( aFace ); } } /* Class : BelongToMeshGroup Description : Verify whether a mesh element is included into a mesh group */ BelongToMeshGroup::BelongToMeshGroup(): myGroup( 0 ) { } void BelongToMeshGroup::SetGroup( SMESHDS_GroupBase* g ) { myGroup = g; } void BelongToMeshGroup::SetStoreName( const std::string& sn ) { myStoreName = sn; } void BelongToMeshGroup::SetMesh( const SMDS_Mesh* theMesh ) { if ( myGroup && myGroup->GetMesh() != theMesh ) { myGroup = 0; } if ( !myGroup && !myStoreName.empty() ) { if ( const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh)) { const std::set<SMESHDS_GroupBase*>& grps = aMesh->GetGroups(); std::set<SMESHDS_GroupBase*>::const_iterator g = grps.begin(); for ( ; g != grps.end() && !myGroup; ++g ) if ( *g && myStoreName == (*g)->GetStoreName() ) myGroup = *g; } } if ( myGroup ) { myGroup->IsEmpty(); // make GroupOnFilter update its predicate } } bool BelongToMeshGroup::IsSatisfy( long theElementId ) { return myGroup ? myGroup->Contains( theElementId ) : false; } SMDSAbs_ElementType BelongToMeshGroup::GetType() const { return myGroup ? myGroup->GetType() : SMDSAbs_All; } /* ElementsOnSurface */ ElementsOnSurface::ElementsOnSurface() { myIds.Clear(); myType = SMDSAbs_All; mySurf.Nullify(); myToler = Precision::Confusion(); myUseBoundaries = false; } ElementsOnSurface::~ElementsOnSurface() { } void ElementsOnSurface::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified()) process(); } bool ElementsOnSurface::IsSatisfy( long theElementId ) { return myIds.Contains( theElementId ); } SMDSAbs_ElementType ElementsOnSurface::GetType() const { return myType; } void ElementsOnSurface::SetTolerance( const double theToler ) { if ( myToler != theToler ) myIds.Clear(); myToler = theToler; } double ElementsOnSurface::GetTolerance() const { return myToler; } void ElementsOnSurface::SetUseBoundaries( bool theUse ) { if ( myUseBoundaries != theUse ) { myUseBoundaries = theUse; SetSurface( mySurf, myType ); } } void ElementsOnSurface::SetSurface( const TopoDS_Shape& theShape, const SMDSAbs_ElementType theType ) { myIds.Clear(); myType = theType; mySurf.Nullify(); if ( theShape.IsNull() || theShape.ShapeType() != TopAbs_FACE ) return; mySurf = TopoDS::Face( theShape ); BRepAdaptor_Surface SA( mySurf, myUseBoundaries ); Standard_Real u1 = SA.FirstUParameter(), u2 = SA.LastUParameter(), v1 = SA.FirstVParameter(), v2 = SA.LastVParameter(); Handle(Geom_Surface) surf = BRep_Tool::Surface( mySurf ); myProjector.Init( surf, u1,u2, v1,v2 ); process(); } void ElementsOnSurface::process() { myIds.Clear(); if ( mySurf.IsNull() ) return; if ( !myMeshModifTracer.GetMesh() ) return; myIds.ReSize( myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType )); <API key> anIter = myMeshModifTracer.GetMesh()->elementsIterator( myType ); for(; anIter->more(); ) process( anIter->next() ); } void ElementsOnSurface::process( const SMDS_MeshElement* theElemPtr ) { <API key> aNodeItr = theElemPtr->nodesIterator(); bool isSatisfy = true; for ( ; aNodeItr->more(); ) { SMDS_MeshNode* aNode = (SMDS_MeshNode*)aNodeItr->next(); if ( !isOnSurface( aNode ) ) { isSatisfy = false; break; } } if ( isSatisfy ) myIds.Add( theElemPtr->GetID() ); } bool ElementsOnSurface::isOnSurface( const SMDS_MeshNode* theNode ) { if ( mySurf.IsNull() ) return false; gp_Pnt aPnt( theNode->X(), theNode->Y(), theNode->Z() ); // double aToler2 = myToler * myToler; // if ( mySurf->IsKind(STANDARD_TYPE(Geom_Plane))) // gp_Pln aPln = Handle(Geom_Plane)::DownCast(mySurf)->Pln(); // if ( aPln.SquareDistance( aPnt ) > aToler2 ) // return false; // else if ( mySurf->IsKind(STANDARD_TYPE(<API key>))) // gp_Cylinder aCyl = Handle(<API key>)::DownCast(mySurf)->Cylinder(); // double aRad = aCyl.Radius(); // gp_Ax3 anAxis = aCyl.Position(); // gp_XYZ aLoc = aCyl.Location().XYZ(); // double aXDist = anAxis.XDirection().XYZ() * ( aPnt.XYZ() - aLoc ); // double aYDist = anAxis.YDirection().XYZ() * ( aPnt.XYZ() - aLoc ); // if ( fabs(aXDist*aXDist + aYDist*aYDist - aRad*aRad) > aToler2 ) // return false; // else // return false; myProjector.Perform( aPnt ); bool isOn = ( myProjector.IsDone() && myProjector.LowerDistance() <= myToler ); return isOn; } /* ElementsOnShape */ ElementsOnShape::ElementsOnShape() : //myMesh(0), myType(SMDSAbs_All), myToler(Precision::Confusion()), myAllNodesFlag(false) { } ElementsOnShape::~ElementsOnShape() { clearClassifiers(); } SMDSAbs_ElementType ElementsOnShape::GetType() const { return myType; } void ElementsOnShape::SetTolerance (const double theToler) { if (myToler != theToler) { myToler = theToler; SetShape(myShape, myType); } } double ElementsOnShape::GetTolerance() const { return myToler; } void ElementsOnShape::SetAllNodes (bool theAllNodes) { myAllNodesFlag = theAllNodes; } void ElementsOnShape::SetMesh (const SMDS_Mesh* theMesh) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified()) { size_t nbNodes = theMesh ? theMesh->NbNodes() : 0; if ( myNodeIsChecked.size() == nbNodes ) { std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false ); } else { SMESHUtils::FreeVector( myNodeIsChecked ); SMESHUtils::FreeVector( myNodeIsOut ); myNodeIsChecked.resize( nbNodes, false ); myNodeIsOut.resize( nbNodes ); } } } bool ElementsOnShape::getNodeIsOut( const SMDS_MeshNode* n, bool& isOut ) { if ( n->GetID() >= (int) myNodeIsChecked.size() || !myNodeIsChecked[ n->GetID() ]) return false; isOut = myNodeIsOut[ n->GetID() ]; return true; } void ElementsOnShape::setNodeIsOut( const SMDS_MeshNode* n, bool isOut ) { if ( n->GetID() < (int) myNodeIsChecked.size() ) { myNodeIsChecked[ n->GetID() ] = true; myNodeIsOut [ n->GetID() ] = isOut; } } void ElementsOnShape::SetShape (const TopoDS_Shape& theShape, const SMDSAbs_ElementType theType) { myType = theType; myShape = theShape; if ( myShape.IsNull() ) return; <API key> shapesMap; TopAbs_ShapeEnum shapeTypes[4] = { TopAbs_SOLID, TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX }; TopExp_Explorer sub; for ( int i = 0; i < 4; ++i ) { if ( shapesMap.IsEmpty() ) for ( sub.Init( myShape, shapeTypes[i] ); sub.More(); sub.Next() ) shapesMap.Add( sub.Current() ); if ( i > 0 ) for ( sub.Init( myShape, shapeTypes[i], shapeTypes[i-1] ); sub.More(); sub.Next() ) shapesMap.Add( sub.Current() ); } clearClassifiers(); myClassifiers.resize( shapesMap.Extent() ); for ( int i = 0; i < shapesMap.Extent(); ++i ) myClassifiers[ i ] = new TClassifier( shapesMap( i+1 ), myToler ); if ( theType == SMDSAbs_Node ) { SMESHUtils::FreeVector( myNodeIsChecked ); SMESHUtils::FreeVector( myNodeIsOut ); } else { std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false ); } } void ElementsOnShape::clearClassifiers() { for ( size_t i = 0; i < myClassifiers.size(); ++i ) delete myClassifiers[ i ]; myClassifiers.clear(); } bool ElementsOnShape::IsSatisfy (long elemId) { const SMDS_Mesh* mesh = myMeshModifTracer.GetMesh(); const SMDS_MeshElement* elem = ( myType == SMDSAbs_Node ? mesh->FindNode( elemId ) : mesh->FindElement( elemId )); if ( !elem || myClassifiers.empty() ) return false; bool isSatisfy = myAllNodesFlag, isNodeOut; gp_XYZ centerXYZ (0, 0, 0); <API key> aNodeItr = elem->nodesIterator(); while (aNodeItr->more() && (isSatisfy == myAllNodesFlag)) { SMESH_TNodeXYZ aPnt( aNodeItr->next() ); centerXYZ += aPnt; isNodeOut = true; if ( !getNodeIsOut( aPnt._node, isNodeOut )) { for ( size_t i = 0; i < myClassifiers.size() && isNodeOut; ++i ) isNodeOut = myClassifiers[i]->IsOut( aPnt ); setNodeIsOut( aPnt._node, isNodeOut ); } isSatisfy = !isNodeOut; } // Check the center point for volumes MantisBug 0020168 if (isSatisfy && myAllNodesFlag && myClassifiers[0]->ShapeType() == TopAbs_SOLID) { centerXYZ /= elem->NbNodes(); isSatisfy = false; for ( size_t i = 0; i < myClassifiers.size() && !isSatisfy; ++i ) isSatisfy = ! myClassifiers[i]->IsOut( centerXYZ ); } return isSatisfy; } TopAbs_ShapeEnum ElementsOnShape::TClassifier::ShapeType() const { return myShape.ShapeType(); } bool ElementsOnShape::TClassifier::IsOut(const gp_Pnt& p) { return (this->*myIsOutFun)( p ); } void ElementsOnShape::TClassifier::Init (const TopoDS_Shape& theShape, double theTol) { myShape = theShape; myTol = theTol; switch ( myShape.ShapeType() ) { case TopAbs_SOLID: { if ( isBox( theShape )) { myIsOutFun = & ElementsOnShape::TClassifier::isOutOfBox; } else { mySolidClfr.Load(theShape); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfSolid; } break; } case TopAbs_FACE: { Standard_Real u1,u2,v1,v2; Handle(Geom_Surface) surf = BRep_Tool::Surface( TopoDS::Face( theShape )); surf->Bounds( u1,u2,v1,v2 ); myProjFace.Init(surf, u1,u2, v1,v2, myTol ); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfFace; break; } case TopAbs_EDGE: { Standard_Real u1, u2; Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge(theShape), u1, u2); myProjEdge.Init(curve, u1, u2); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfEdge; break; } case TopAbs_VERTEX:{ myVertexXYZ = BRep_Tool::Pnt( TopoDS::Vertex( theShape ) ); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfVertex; break; } default: throw SALOME_Exception("Programmer error in usage of ElementsOnShape::TClassifier"); } } bool ElementsOnShape::TClassifier::isOutOfSolid (const gp_Pnt& p) { mySolidClfr.Perform( p, myTol ); return ( mySolidClfr.State() != TopAbs_IN && mySolidClfr.State() != TopAbs_ON ); } bool ElementsOnShape::TClassifier::isOutOfBox (const gp_Pnt& p) { return myBox.IsOut( p.XYZ() ); } bool ElementsOnShape::TClassifier::isOutOfFace (const gp_Pnt& p) { myProjFace.Perform( p ); if ( myProjFace.IsDone() && myProjFace.LowerDistance() <= myTol ) { // check relatively to the face Quantity_Parameter u, v; myProjFace.<API key>(u, v); gp_Pnt2d aProjPnt (u, v); <API key> aClsf ( TopoDS::Face( myShape ), aProjPnt, myTol ); if ( aClsf.State() == TopAbs_IN || aClsf.State() == TopAbs_ON ) return false; } return true; } bool ElementsOnShape::TClassifier::isOutOfEdge (const gp_Pnt& p) { myProjEdge.Perform( p ); return ! ( myProjEdge.NbPoints() > 0 && myProjEdge.LowerDistance() <= myTol ); } bool ElementsOnShape::TClassifier::isOutOfVertex(const gp_Pnt& p) { return ( myVertexXYZ.Distance( p ) > myTol ); } bool ElementsOnShape::TClassifier::isBox (const TopoDS_Shape& theShape) { <API key> vMap; TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap ); if ( vMap.Extent() != 8 ) return false; myBox.Clear(); for ( int i = 1; i <= 8; ++i ) myBox.Add( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))).XYZ() ); gp_XYZ pMin = myBox.CornerMin(), pMax = myBox.CornerMax(); for ( int i = 1; i <= 8; ++i ) { gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))); for ( int iC = 1; iC <= 3; ++ iC ) { double d1 = Abs( pMin.Coord( iC ) - p.Coord( iC )); double d2 = Abs( pMax.Coord( iC ) - p.Coord( iC )); if ( Min( d1, d2 ) > myTol ) return false; } } myBox.Enlarge( myTol ); return true; } /* Class : BelongToGeom Description : Predicate for verifying whether entity belongs to specified geometrical support */ BelongToGeom::BelongToGeom() : myMeshDS(NULL), myType(SMDSAbs_All), myIsSubshape(false), myTolerance(Precision::Confusion()) {} void BelongToGeom::SetMesh( const SMDS_Mesh* theMesh ) { myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh); init(); } void BelongToGeom::SetGeom( const TopoDS_Shape& theShape ) { myShape = theShape; init(); } static bool IsSubShape (const <API key>& theMap, const TopoDS_Shape& theShape) { if (theMap.Contains(theShape)) return true; if (theShape.ShapeType() == TopAbs_COMPOUND || theShape.ShapeType() == TopAbs_COMPSOLID) { TopoDS_Iterator anIt (theShape, Standard_True, Standard_True); for (; anIt.More(); anIt.Next()) { if (!IsSubShape(theMap, anIt.Value())) { return false; } } return true; } return false; } void BelongToGeom::init() { if (!myMeshDS || myShape.IsNull()) return; // is sub-shape of main shape? TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh(); if (aMainShape.IsNull()) { myIsSubshape = false; } else { <API key> aMap; TopExp::MapShapes(aMainShape, aMap); myIsSubshape = IsSubShape(aMap, myShape); } //if (!myIsSubshape) // to be always ready to check an element not bound to geometry { <API key>.reset(new ElementsOnShape()); <API key>->SetTolerance(myTolerance); <API key>->SetAllNodes(true); // "belong", while false means "lays on" <API key>->SetMesh(myMeshDS); <API key>->SetShape(myShape, myType); } } static bool IsContains( const SMESHDS_Mesh* theMeshDS, const TopoDS_Shape& theShape, const SMDS_MeshElement* theElem, TopAbs_ShapeEnum theFindShapeEnum, TopAbs_ShapeEnum theAvoidShapeEnum = TopAbs_SHAPE ) { TopExp_Explorer anExp( theShape,theFindShapeEnum,theAvoidShapeEnum ); while( anExp.More() ) { const TopoDS_Shape& aShape = anExp.Current(); if( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape ) ){ if( aSubMesh->Contains( theElem ) ) return true; } anExp.Next(); } return false; } bool BelongToGeom::IsSatisfy (long theId) { if (myMeshDS == 0 || myShape.IsNull()) return false; if (!myIsSubshape) { return <API key>->IsSatisfy(theId); } // Case of submesh if (myType == SMDSAbs_Node) { if( const SMDS_MeshNode* aNode = myMeshDS->FindNode( theId ) ) { if ( aNode->getshapeId() < 1 ) return <API key>->IsSatisfy(theId); const SMDS_PositionPtr& aPosition = aNode->GetPosition(); SMDS_TypeOfPosition aTypeOfPosition = aPosition->GetTypeOfPosition(); switch( aTypeOfPosition ) { case SMDS_TOP_VERTEX : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_VERTEX )); case SMDS_TOP_EDGE : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_EDGE )); case SMDS_TOP_FACE : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_FACE )); case SMDS_TOP_3DSPACE: return ( IsContains( myMeshDS,myShape,aNode,TopAbs_SOLID ) || IsContains( myMeshDS,myShape,aNode,TopAbs_SHELL )); } } } else { if ( const SMDS_MeshElement* anElem = myMeshDS->FindElement( theId )) { if ( anElem->getshapeId() < 1 ) return <API key>->IsSatisfy(theId); if( myType == SMDSAbs_All ) { return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE ) || IsContains( myMeshDS,myShape,anElem,TopAbs_FACE ) || IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )|| IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL )); } else if( myType == anElem->GetType() ) { switch( myType ) { case SMDSAbs_Edge : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE )); case SMDSAbs_Face : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_FACE )); case SMDSAbs_Volume: return ( IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )|| IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL )); } } } } return false; } void BelongToGeom::SetType (SMDSAbs_ElementType theType) { myType = theType; init(); } SMDSAbs_ElementType BelongToGeom::GetType() const { return myType; } TopoDS_Shape BelongToGeom::GetShape() { return myShape; } const SMESHDS_Mesh* BelongToGeom::GetMeshDS() const { return myMeshDS; } void BelongToGeom::SetTolerance (double theTolerance) { myTolerance = theTolerance; if (!myIsSubshape) init(); } double BelongToGeom::GetTolerance() { return myTolerance; } /* Class : LyingOnGeom Description : Predicate for verifying whether entiy lying or partially lying on specified geometrical support */ LyingOnGeom::LyingOnGeom() : myMeshDS(NULL), myType(SMDSAbs_All), myIsSubshape(false), myTolerance(Precision::Confusion()) {} void LyingOnGeom::SetMesh( const SMDS_Mesh* theMesh ) { myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh); init(); } void LyingOnGeom::SetGeom( const TopoDS_Shape& theShape ) { myShape = theShape; init(); } void LyingOnGeom::init() { if (!myMeshDS || myShape.IsNull()) return; // is sub-shape of main shape? TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh(); if (aMainShape.IsNull()) { myIsSubshape = false; } else { myIsSubshape = myMeshDS->IsGroupOfSubShapes( myShape ); } if (myIsSubshape) { <API key> shapes; TopExp::MapShapes( myShape, shapes ); mySubShapesIDs.Clear(); for ( int i = 1; i <= shapes.Extent(); ++i ) { int subID = myMeshDS->ShapeToIndex( shapes( i )); if ( subID > 0 ) mySubShapesIDs.Add( subID ); } } else { <API key>.reset(new ElementsOnShape()); <API key>->SetTolerance(myTolerance); <API key>->SetAllNodes(false); // lays on, while true means "belong" <API key>->SetMesh(myMeshDS); <API key>->SetShape(myShape, myType); } } bool LyingOnGeom::IsSatisfy( long theId ) { if ( myMeshDS == 0 || myShape.IsNull() ) return false; if (!myIsSubshape) { return <API key>->IsSatisfy(theId); } // Case of sub-mesh const SMDS_MeshElement* elem = ( myType == SMDSAbs_Node ) ? myMeshDS->FindNode( theId ) : myMeshDS->FindElement( theId ); if ( mySubShapesIDs.Contains( elem->getshapeId() )) return true; if ( elem->GetType() != SMDSAbs_Node ) { <API key> nodeItr = elem->nodesIterator(); while ( nodeItr->more() ) { const SMDS_MeshElement* aNode = nodeItr->next(); if ( mySubShapesIDs.Contains( aNode->getshapeId() )) return true; } } return false; } void LyingOnGeom::SetType( SMDSAbs_ElementType theType ) { myType = theType; init(); } SMDSAbs_ElementType LyingOnGeom::GetType() const { return myType; } TopoDS_Shape LyingOnGeom::GetShape() { return myShape; } const SMESHDS_Mesh* LyingOnGeom::GetMeshDS() const { return myMeshDS; } void LyingOnGeom::SetTolerance (double theTolerance) { myTolerance = theTolerance; if (!myIsSubshape) init(); } double LyingOnGeom::GetTolerance() { return myTolerance; } bool LyingOnGeom::Contains( const SMESHDS_Mesh* theMeshDS, const TopoDS_Shape& theShape, const SMDS_MeshElement* theElem, TopAbs_ShapeEnum theFindShapeEnum, TopAbs_ShapeEnum theAvoidShapeEnum ) { // if (IsContains(theMeshDS, theShape, theElem, theFindShapeEnum, theAvoidShapeEnum)) // return true; // TopTools_MapOfShape aSubShapes; // TopExp_Explorer exp( theShape, theFindShapeEnum, theAvoidShapeEnum ); // for ( ; exp.More(); exp.Next() ) // const TopoDS_Shape& aShape = exp.Current(); // if ( !aSubShapes.Add( aShape )) continue; // if ( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape )) // if ( aSubMesh->Contains( theElem )) // return true; // <API key> nodeItr = theElem->nodesIterator(); // while ( nodeItr->more() ) // const SMDS_MeshElement* aNode = nodeItr->next(); // if ( aSubMesh->Contains( aNode )) // return true; return false; } TSequenceOfXYZ::TSequenceOfXYZ(): myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(size_type n) : myArray(n), myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(size_type n, const gp_XYZ& t) : myArray(n,t), myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(const TSequenceOfXYZ& theSequenceOfXYZ) : myArray(theSequenceOfXYZ.myArray), myElem(theSequenceOfXYZ.myElem) {} template <class InputIterator> TSequenceOfXYZ::TSequenceOfXYZ(InputIterator theBegin, InputIterator theEnd): myArray(theBegin,theEnd), myElem(0) {} TSequenceOfXYZ::~TSequenceOfXYZ() {} TSequenceOfXYZ& TSequenceOfXYZ::operator=(const TSequenceOfXYZ& theSequenceOfXYZ) { myArray = theSequenceOfXYZ.myArray; myElem = theSequenceOfXYZ.myElem; return *this; } gp_XYZ& TSequenceOfXYZ::operator()(size_type n) { return myArray[n-1]; } const gp_XYZ& TSequenceOfXYZ::operator()(size_type n) const { return myArray[n-1]; } void TSequenceOfXYZ::clear() { myArray.clear(); } void TSequenceOfXYZ::reserve(size_type n) { myArray.reserve(n); } void TSequenceOfXYZ::push_back(const gp_XYZ& v) { myArray.push_back(v); } TSequenceOfXYZ::size_type TSequenceOfXYZ::size() const { return myArray.size(); } SMDSAbs_EntityType TSequenceOfXYZ::getElementEntity() const { return myElem ? myElem->GetEntityType() : SMDSEntity_Last; } TMeshModifTracer::TMeshModifTracer(): myMeshModifTime(0), myMesh(0) { } void TMeshModifTracer::SetMesh( const SMDS_Mesh* theMesh ) { if ( theMesh != myMesh ) myMeshModifTime = 0; myMesh = theMesh; } bool TMeshModifTracer::IsMeshModified() { bool modified = false; if ( myMesh ) { modified = ( myMeshModifTime != myMesh->GetMTime() ); myMeshModifTime = myMesh->GetMTime(); } return modified; }
#include "ASTPath.h" #include <AST.h> #include <TranslationUnit.h> #ifdef DEBUG_AST_PATH # include <QDebug> # include <typeinfo> #endif // DEBUG_AST_PATH using namespace CPlusPlus; QList<AST *> ASTPath::operator()(int line, int column) { _nodes.clear(); _line = line; _column = column; if (_doc) { if (TranslationUnit *unit = _doc->translationUnit()) accept(unit->ast()); } return _nodes; } #ifdef DEBUG_AST_PATH void ASTPath::dump(const QList<AST *> nodes) { qDebug() << "ASTPath dump," << nodes.size() << "nodes:"; for (int i = 0; i < nodes.size(); ++i) qDebug() << qPrintable(QString(i + 1, QLatin1Char('-'))) << typeid(*nodes.at(i)).name(); } #endif // DEBUG_AST_PATH bool ASTPath::preVisit(AST *ast) { unsigned firstToken = ast->firstToken(); unsigned lastToken = ast->lastToken(); if (firstToken > 0) { if (lastToken <= firstToken) return false; unsigned startLine, startColumn; <API key>(firstToken, &startLine, &startColumn); if (_line > startLine || (_line == startLine && _column >= startColumn)) { unsigned endLine, endColumn; getTokenEndPosition(lastToken - 1, &endLine, &endColumn); if (_line < endLine || (_line == endLine && _column <= endColumn)) { _nodes.append(ast); return true; } } } return false; }
//Version-IE: < 9 if ( 'function' !== typeof Array.prototype.reduce ) { Array.prototype.reduce = function( callback /*, initialValue*/ ) { 'use strict'; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } var t = Object( this ), len = t.length >>> 0, k = 0, value; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k < len && ! k in t ) k++; if ( k >= len ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k++ ]; } for ( ; k < len ; k++ ) { if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } //Version-IE: < 9 if ( 'function' !== typeof Array.prototype.reduceRight ) { Array.prototype.reduceRight = function( callback /*, initialValue*/ ) { 'use strict'; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } var t = Object( this ), len = t.length >>> 0, k = len - 1, value; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k >= 0 && ! k in t ) k if ( k < 0 ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k } for ( ; k >= 0 ; k if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } //Version-IE: < 9 if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisArg */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(<span style="line-height: normal;">thisArg</span><span style="line-height: normal;">, val, i, t))</span> res.push(val); } } return res; }; } //Version-IE: < 9 if (!Array.prototype.every) { Array.prototype.every = function (callbackfn, thisArg) { "use strict"; var T, k; if (this == null) { throw new TypeError("this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the this // value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (typeof callbackfn !== "function") { throw new TypeError(); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0. k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Let testResult be the result of calling the Call internal method // of callbackfn with T as the this value and argument list // containing kValue, k, and O. var testResult = callbackfn.call(T, kValue, k, O); // iii. If ToBoolean(testResult) is false, return false. if (!testResult) { return false; } } k++; } return true; }; } //Version-IE: < 9 if (!Array.prototype.some) { Array.prototype.some = function(fun /*, thisArg */) { 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t)) return true; } return false; }; } // Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.com/#x15.4.4.19 //Version-IE: < 9 if (!Array.prototype.map) { Array.prototype.map = function (callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let A be a new array created as if by the expression new Array( len) where Array is // the standard built-in constructor with that name and len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal method of callback // with T as the this value and argument list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor {Value: mappedValue, Writable: true, Enumerable: true, Configurable: true}, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty( A, k, { value: mappedValue, writable: true, enumerable: true, configurable: true }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; } // Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.com/#x15.4.4.18 //Version-IE: < 9 if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0 k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Call the Call internal method of callback with T as the this value and // argument list containing kValue, k, and O. callback.call(T, kValue, k, O); } // d. Increase k by 1. k++; } // 8. return undefined }; }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ECShop_mobile</title> </head> <body> <p align='left'> <br/> <a href='user.php?act=order_list'></a><br/> <br/> {foreach from=$best_goods item=best_data} <a href='goods.php?id={$best_data.id}'>{$best_data.name}</a>[{$best_data.shop_price}]<br/> {/foreach} <a href='index.php'></a> {$footer} </p> </body> </html>
#include <gadget/gadgetConfig.h> #include <jccl/Config/ConfigElement.h> #include <gadget/Devices/Sim/SimDigital.h> namespace gadget { /** Default Constructor */ SimDigital::SimDigital() { vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::SimDigital()\n"<< vprDEBUG_FLUSH; } /** Destructor */ SimDigital::~SimDigital() { } std::string SimDigital::getElementType() { return "<API key>"; } bool SimDigital::config(jccl::ConfigElementPtr element) { if (! (Input::config(element) && Digital::config(element) && SimInput::config(element)) ) { return false; } std::vector<jccl::ConfigElementPtr> key_list; int key_count = element->getNum("key_pair"); for ( int i = 0; i < key_count; ++i ) { key_list.push_back(element->getProperty<jccl::ConfigElementPtr>("key_pair", i)); } mSimKeys = readKeyList(key_list); return true; } /** * Updates the state of the digital data vector. * * @note Digital is on when key is held down. * When key is release, digital goes to off state. */ void SimDigital::updateData() { std::vector<DigitalData> digital_data_sample(mSimKeys.size()); // The digital data that makes up the sample for (unsigned int i = 0; i < mSimKeys.size(); ++i) { // Set the time for the digital data to the KeyboardMouse timestamp digital_data_sample[i].setTime(mKeyboardMouse->getTimeStamp()); // ON if keys pressed, OFF otherwise. digital_data_sample[i] = checkKeyPair(mSimKeys[i]) ? DigitalState::ON : DigitalState::OFF; } // Add a sample addDigitalSample(digital_data_sample); swapDigitalBuffers(); } } // End of gadget namespace
// modification, are permitted provided that the following conditions are met: // with the distribution. // * Neither the name of Preferred Infrastructure nor the names of other // contributors may be used to endorse or promote products derived // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** Range minimum query (rmq) in O(log N) time and O(N) precomputed information. */ /* Implementation is based on Johannes Fischer, Volker Heun. "Theoretical and Practical Improvements on the RMQ-Problem, with Applications to LCA and LCE", Proceedings of the 17th Annual Symposium on Combinatorial Pattern Matching (CPM'06), Lecture Notes in Computer Science 4009, 36-48, Springer-Verlag, 2006. and Johannes Fischer, Volker Heun. "A New Succinct Representation of RMQ-Information and Improvements in the Enhanced Suffix Array", Proceedings of the International Symposium on Combinatorics, Algorithms, Probabilistic and Experimental Methodologies (ESCAPE'07), Lecture Notes in Computer Science 4614, 459-470, Springer-Verlag, 2007. but modified for simplicity. There are two differences in Fischer'07 and this implementation: * Blocks / superblocks are replaced by Catalan number representation. * Use precomputed Catalan number table for all blocks. * Use O(16/7 N) bits Drawback of this method is query time of order O(log(8)N). It takes about 10 recursion to calculate RMQ if N = 1e9. FIXME: compare speed with another implementation. especially when RMQ is changed to Bender & Farach's (O(NlogN),O(1)) */ #include <vector> #include <iterator> #include <climits> // new in C99, but // nowadays almost all compilers should have it #include <stdint.h> namespace jubatus { namespace util { namespace data { namespace suffix_array { namespace { enum { block_bits = 3, block_size = 1 << block_bits, block_size_sq = block_size * (block_size+1) / 2, block_access_depth = 3 }; // enough to fit in int16 typedef int16_t block_type; /** Ballot number table. Generated from balgen.hs, with s = 8 */ const int ballot_table[block_size+1][block_size+1] = { #include "ballot_num8.dat" }; /** Minimum position table for cartesian types */ const unsigned char cartesian_table[][block_size_sq] = { #include "cartesian_table8.dat" }; /** RMQ(i,j) -> cartesian_table[foo][access_table[i][j]] conversion */ const int access_table[block_size][block_size] = { { 0, 1, 2, 3, 4, 5, 6, 7, }, { -1, 8, 9, 10, 11, 12, 13, 14, }, { -1, -1, 15, 16, 17, 18, 19, 20, }, { -1, -1, -1, 21, 22, 23, 24, 25, }, { -1, -1, -1, -1, 26, 27, 28, 29, }, { -1, -1, -1, -1, -1, 30, 31, 32, }, { -1, -1, -1, -1, -1, -1, 33, 34, }, { -1, -1, -1, -1, -1, -1, -1, 35, }, }; const int msb_table[256] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, }; const int all_block = access_table[0][block_size - 1]; int get_msb(unsigned int b){ if(b >= (1 << 24)) return 24 + msb_table[b >> 24]; if(b >= (1 << 16)) return 16 + msb_table[b >> 16]; if(b >= (1 << 8)) return 8 + msb_table[b >> 8]; return msb_table[b]; } /** Calculate cartesian tree's "type". See J. Fischer and V. Heun, "New succinct ... " @param b Beginning of iterator that points to the sequence of number @return cartesian tree type */ const int infty = INT_MAX; const int neg_infty = INT_MIN; template<typename IT> int cartesian_type(IT b){ const size_t s = block_size; // FIXME: remove this "R" reconstruction for speeding up std::vector<int> R(s+1); R[0] = neg_infty; int q = s; int N = 0; for(size_t i = 0; i < s; ++i){ while(R[q + i - s] > *(b+i)){ N += ballot_table[s-(i+1)][q]; --q; } R[q+i+1-s] = *(b+i); } return N; } /** This routine is used if s != distance(b,e). */ template<typename IT> int cartesian_type(IT b, IT e){ const size_t real_s = std::distance(b, e); const size_t s = block_size; std::vector<int> R(s+1); R[0] = neg_infty; int q = s; int N = 0; for(size_t i = 0; i < real_s; ++i){ while(R[q + i - s] > *(b+i)){ N += ballot_table[s-(i+1)][q]; --q; } R[q+i+1-s] = *(b+i); } return N; } } /** Range-minimum-query data structure */ template<typename CONT> class rmq{ typedef typename CONT::value_type T; public: /** RMQ constructor. takes container v and precompute data structure @param v target container */ rmq(const CONT &v): orig(v), types(block_access_depth), log_rmq_table(){ construct_type(v.begin(), v.end(), 0); } /* TODO: load/save from file */ /** RMQ query in the range [l,r]. (right inclusive) @param l leftmost range @param r rightmost range (inclusive) @return position of minimum element */ int query(int l, int r){ int buf[(block_access_depth << 1) + 1]; for(size_t i = 0; i < (block_access_depth << 1) + 1; ++i) buf[i] = -1; return query_iter(l, r, 0, buf); } /** RMQ query in the range [l,r). (right exclusive) @param l leftmost range @param r rightmost range (exclusive) @return position of minimum element */ int query_exclusive(int l, int r){ return query(l, r-1); } private: const CONT &orig; std::vector<std::vector<block_type> > types; std::vector<std::vector<int> > log_rmq_table; template<typename IT> void construct_type(IT b, IT e, int level){ if(level >= block_access_depth) { construct_log_table(b, e); return; } size_t s = std::distance(b, e); size_t blks = (s + block_size - 1) >> block_bits; size_t blks_p = s >> block_bits; std::vector<block_type> &tys = types[level]; std::vector<T> rm(blks); tys.resize(blks); // cartesian type calculation { IT it(b); for(size_t i = 0; i < blks_p; ++i){ int ty = cartesian_type(it); tys[i] = ty; rm[i] = *(it + cartesian_table[ty][all_block]); it += block_size; } if(blks != blks_p){ int ty = cartesian_type(it, e); tys[blks_p] = ty; rm[blks_p] = *(it + cartesian_table[ty][all_block]); } } // FIXME: is this tail-recursive? construct_type(rm.begin(), rm.end(), level + 1); } template<typename IT> void construct_log_table(IT b, IT e){ // four-russian-trick size_t s = std::distance(b, e); log_rmq_table.clear(); { // first pass: fill k = 1 case log_rmq_table.push_back(std::vector<int>(s-1)); std::vector<int> &log_cur_table = log_rmq_table.back(); int lmin_ = -1; IT it(b); for(size_t i = 0; i < s-1; ++i, ++it){ if(*it < *(it+1)){ log_cur_table[i] = (lmin_ >= 0 ? lmin_: <API key>(i)); lmin_ = -1; }else{ int rmin = <API key>(i+1); log_cur_table[i] = rmin; lmin_ = rmin; } } } for(size_t k = 2; (1U<<k) < s; ++k){ int prev_size = 1 << (k-1); int cur_size = 1 << k; log_rmq_table.push_back(std::vector<int>(s-cur_size+1)); std::vector<int> &prev = log_rmq_table[k-2]; std::vector<int> &cur = log_rmq_table.back(); for(size_t i = 0; i < s - cur_size + 1; ++i){ // try not to call <API key> again int lm_ = prev[i]; int lm = lm_ >> (block_bits * block_access_depth); int rm_ = prev[i + prev_size]; int rm = rm_ >> (block_bits * block_access_depth); cur[i] = (*(b+lm) < *(b+rm) ? lm_ : rm_); } } } int <API key>(int level, int blockpos){ int ty = types[level][blockpos]; return cartesian_table[ty][all_block]; } int <API key>(int level, int super_blockpos){ int pos = super_blockpos; for(int l = level; l >= 0; --l){ pos = (pos << block_bits) + <API key>(l, pos); } return pos; } int <API key>(int super_blockpos){ return <API key>(block_access_depth - 1, super_blockpos); } int query_iter(int l, int r, int level, int* buf){ if(level >= block_access_depth) return <API key>(l, r, buf); int lb = l >> block_bits; int lh = l & (block_size - 1); int rb = r >> block_bits; int rh = r & (block_size - 1); std::vector<block_type> &tys = types[level]; if(lb >= rb){ // in-block query if(l <= r){ buf[block_access_depth] = <API key>(level - 1, // level = 0 -> ok (lb << block_bits) + cartesian_table[tys[lb]][access_table[lh][rh]]); } return best_in_buf(buf); }else{ // out-of-block query if(lh != 0){ buf[level] = <API key>(level-1, (lb << block_bits) + cartesian_table[tys[lb]][access_table[lh][block_size-1]]); lb++; } if(rh != block_size - 1){ buf[(block_access_depth << 1) - level] = <API key>(level-1, (rb << block_bits) + cartesian_table[tys[rb]][access_table[0][rh]]); rb } return query_iter(lb, rb, level + 1, buf); } } int <API key>(int l, int r, int *buf){ r++; int s = r - l; if(s <= 0) return best_in_buf(buf); if(s == 1) { buf[block_access_depth] = <API key>(block_access_depth - 1, l); return best_in_buf(buf); } int b = get_msb(s); int bl = 1 << (b-1); int leftix = log_rmq_table[b-2][l]; int rightix = log_rmq_table[b-2][r-bl]; buf[block_access_depth] = (orig[leftix] < orig[rightix] ? leftix : rightix); return best_in_buf(buf); } int best_in_buf(int *buf){ int cur_min_ix = -1; T cur_min = T(); for(int i = 0; i < (block_access_depth << 1) + 1; ++i){ int m = buf[i]; if(m == -1) continue; T mval = orig[m]; if(cur_min_ix == -1 || mval < cur_min){ cur_min_ix = m; cur_min = mval; } } return cur_min_ix; } }; } // suffix_array } // data } // util } // jubatus
/** * @ingroup cpu_stm32f4 * @{ * * @file * @brief CPU specific definitions for internal peripheral handling * * @author Hauke Petersen <hauke.peterse@fu-berlin.de> */ #ifndef PERIPH_CPU_H #define PERIPH_CPU_H #include "cpu.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Overwrite the default gpio_t type definition * @{ */ #define HAVE_GPIO_T typedef uint32_t gpio_t; /** * @brief Definition of a fitting UNDEF value */ #define GPIO_UNDEF (0xffffffff) /** * @brief Define a CPU specific GPIO pin generator macro */ #define GPIO_PIN(x, y) ((GPIOA_BASE + (x << 10)) | y) /** * @brief declare needed generic SPI functions * @{ */ #define <API key> #define <API key> #define <API key> /** * @brief Available ports on the STM32F4 family */ enum { PORT_A = 0, /**< port A */ PORT_B = 1, /**< port B */ PORT_C = 2, /**< port C */ PORT_D = 3, /**< port D */ PORT_E = 4, /**< port E */ PORT_F = 5, /**< port F */ PORT_G = 6, /**< port G */ PORT_H = 7, /**< port H */ PORT_I = 8 /**< port I */ }; /** * @brief Available MUX values for configuring a pin's alternate function */ typedef enum { GPIO_AF0 = 0, /**< use alternate function 0 */ GPIO_AF1, /**< use alternate function 1 */ GPIO_AF2, /**< use alternate function 2 */ GPIO_AF3, /**< use alternate function 3 */ GPIO_AF4, /**< use alternate function 4 */ GPIO_AF5, /**< use alternate function 5 */ GPIO_AF6, /**< use alternate function 6 */ GPIO_AF7, /**< use alternate function 7 */ GPIO_AF8, /**< use alternate function 8 */ GPIO_AF9, /**< use alternate function 9 */ GPIO_AF10, /**< use alternate function 10 */ GPIO_AF11, /**< use alternate function 11 */ GPIO_AF12, /**< use alternate function 12 */ GPIO_AF13, /**< use alternate function 13 */ GPIO_AF14 /**< use alternate function 14 */ } gpio_af_t; /** * @brief Structure for UART configuration data * @{ */ typedef struct { USART_TypeDef *dev; /**< UART device base register address */ uint32_t rcc_mask; /**< bit in clock enable register */ gpio_t rx_pin; /**< RX pin */ gpio_t tx_pin; /**< TX pin */ gpio_af_t af; /**< alternate pin function to use */ uint8_t irqn; /**< IRQ channel */ uint8_t dma_stream; /**< DMA stream used for TX */ uint8_t dma_chan; /**< DMA channel used for TX */ } uart_conf_t; /** * @brief Configure the alternate function for the given pin * * @note This is meant for internal use in STM32F4 peripheral drivers only * * @param[in] pin pin to configure * @param[in] af alternate function to use */ void gpio_init_af(gpio_t pin, gpio_af_t af); /** * @brief Power on the DMA device the given stream belongs to * * @param[in] stream logical DMA stream */ static inline void dma_poweron(int stream) { if (stream < 8) { RCC->AHB1ENR |= RCC_AHB1ENR_DMA1EN; } else { RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN; } } /** * @brief Get DMA base register * * For simplifying DMA stream handling, we map the DMA channels transparently to * one integer number, such that DMA1 stream0 equals 0, DMA2 stream0 equals 8, * DMA2 stream 7 equals 15 and so on. * * @param[in] stream logical DMA stream */ static inline DMA_TypeDef *dma_base(int stream) { return (stream < 8) ? DMA1 : DMA2; } /** * @brief Get the DMA stream base address * * @param[in] stream logical DMA stream * * @return base address for the selected DMA stream */ static inline DMA_Stream_TypeDef *dma_stream(int stream) { uint32_t base = (uint32_t)dma_base(stream); return (DMA_Stream_TypeDef *)(base + (0x10 + (0x18 * (stream & 0x7)))); } /** * @brief Select high or low DMA interrupt register based on stream number * * @param[in] stream logical DMA stream * * @return 0 for streams 0-3, 1 for streams 3-7 */ static inline int dma_hl(int stream) { return ((stream & 0x4) >> 2); } /** * @brief Get the interrupt flag clear bit position in the DMA LIFCR register * * @param[in] stream logical DMA stream */ static inline uint32_t dma_ifc(int stream) { switch (stream & 0x3) { case 0: return (1 << 5); case 1: return (1 << 11); case 2: return (1 << 21); case 3: return (1 << 27); default: return 0; } } static inline void dma_isr_enable(int stream) { if (stream < 7) { NVIC_EnableIRQ((IRQn_Type)((int)DMA1_Stream0_IRQn + stream)); } else if (stream == 8) { NVIC_EnableIRQ(DMA1_Stream7_IRQn); } else if (stream < 14) { NVIC_EnableIRQ((IRQn_Type)((int)DMA2_Stream0_IRQn + stream)); } else if (stream < 17) { NVIC_EnableIRQ((IRQn_Type)((int)DMA2_Stream5_IRQn + stream)); } } #ifdef __cplusplus } #endif #endif /* PERIPH_CPU_H */
/*! * \file ptafunc1.c * <pre> * * Simple rearrangements * PTA *ptaSubsample() * l_int32 ptaJoin() * l_int32 ptaaJoin() * PTA *ptaReverse() * PTA *ptaTranspose() * PTA *ptaCyclicPerm() * PTA *ptaSelectRange() * * Geometric * BOX *<API key>() * l_int32 *ptaGetRange() * PTA *ptaGetInsideBox() * PTA *pixFindCornerPixels() * l_int32 ptaContainsPt() * l_int32 ptaTestIntersection() * PTA *ptaTransform() * l_int32 ptaPtInsidePolygon() * l_float32 <API key>() * * Min/max and filtering * l_int32 ptaGetMinMax() * PTA *ptaSelectByValue() * PTA *ptaCropToMask() * * Least Squares Fit * l_int32 ptaGetLinearLSF() * l_int32 ptaGetQuadraticLSF() * l_int32 ptaGetCubicLSF() * l_int32 ptaGetQuarticLSF() * l_int32 ptaNoisyLinearLSF() * l_int32 <API key>() * l_int32 applyLinearFit() * l_int32 applyQuadraticFit() * l_int32 applyCubicFit() * l_int32 applyQuarticFit() * * Interconversions with Pix * l_int32 pixPlotAlongPta() * PTA *ptaGetPixelsFromPix() * PIX *pixGenerateFromPta() * PTA *<API key>() * PTAA *<API key>() * PTAA *<API key>() * PTA *<API key>() * * Interconversion with Numa * PTA *numaConvertToPta1() * PTA *numaConvertToPta2() * l_int32 ptaConvertToNuma() * * Display Pta and Ptaa * PIX *pixDisplayPta() * PIX *<API key>() * PIX *<API key>() * PTA *ptaReplicatePattern() * PIX *pixDisplayPtaa() * </pre> */ #include <math.h> #include "allheaders.h" #ifndef M_PI #define M_PI 3.<API key> #endif /* M_PI */ /*! * \brief ptaSubsample() * * \param[in] ptas * \param[in] subfactor subsample factor, >= 1 * \return ptad evenly sampled pt values from ptas, or NULL on error */ PTA * ptaSubsample(PTA *ptas, l_int32 subfactor) { l_int32 n, i; l_float32 x, y; PTA *ptad; PROCNAME("pixSubsample"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (subfactor < 1) return (PTA *)ERROR_PTR("subfactor < 1", procName, NULL); ptad = ptaCreate(0); n = ptaGetCount(ptas); for (i = 0; i < n; i++) { if (i % subfactor != 0) continue; ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief ptaJoin() * * \param[in] ptad dest pta; add to this one * \param[in] ptas source pta; add from this one * \param[in] istart starting index in ptas * \param[in] iend ending index in ptas; use -1 to cat all * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) istart < 0 is taken to mean 'read from the start' (istart = 0) * (2) iend < 0 means 'read to the end' * (3) if ptas == NULL, this is a no-op * </pre> */ l_int32 ptaJoin(PTA *ptad, PTA *ptas, l_int32 istart, l_int32 iend) { l_int32 n, i, x, y; PROCNAME("ptaJoin"); if (!ptad) return ERROR_INT("ptad not defined", procName, 1); if (!ptas) return 0; if (istart < 0) istart = 0; n = ptaGetCount(ptas); if (iend < 0 || iend >= n) iend = n - 1; if (istart > iend) return ERROR_INT("istart > iend; no pts", procName, 1); for (i = istart; i <= iend; i++) { ptaGetIPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } return 0; } /*! * \brief ptaaJoin() * * \param[in] ptaad dest ptaa; add to this one * \param[in] ptaas source ptaa; add from this one * \param[in] istart starting index in ptaas * \param[in] iend ending index in ptaas; use -1 to cat all * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) istart < 0 is taken to mean 'read from the start' (istart = 0) * (2) iend < 0 means 'read to the end' * (3) if ptas == NULL, this is a no-op * </pre> */ l_int32 ptaaJoin(PTAA *ptaad, PTAA *ptaas, l_int32 istart, l_int32 iend) { l_int32 n, i; PTA *pta; PROCNAME("ptaaJoin"); if (!ptaad) return ERROR_INT("ptaad not defined", procName, 1); if (!ptaas) return 0; if (istart < 0) istart = 0; n = ptaaGetCount(ptaas); if (iend < 0 || iend >= n) iend = n - 1; if (istart > iend) return ERROR_INT("istart > iend; no pts", procName, 1); for (i = istart; i <= iend; i++) { pta = ptaaGetPta(ptaas, i, L_CLONE); ptaaAddPta(ptaad, pta, L_INSERT); } return 0; } /*! * \brief ptaReverse() * * \param[in] ptas * \param[in] type 0 for float values; 1 for integer values * \return ptad reversed pta, or NULL on error */ PTA * ptaReverse(PTA *ptas, l_int32 type) { l_int32 n, i, ix, iy; l_float32 x, y; PTA *ptad; PROCNAME("ptaReverse"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); if ((ptad = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("ptad not made", procName, NULL); for (i = n - 1; i >= 0; i if (type == 0) { ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } else { /* type == 1 */ ptaGetIPt(ptas, i, &ix, &iy); ptaAddPt(ptad, ix, iy); } } return ptad; } /*! * \brief ptaTranspose() * * \param[in] ptas * \return ptad with x and y values swapped, or NULL on error */ PTA * ptaTranspose(PTA *ptas) { l_int32 n, i; l_float32 x, y; PTA *ptad; PROCNAME("ptaTranspose"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); if ((ptad = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("ptad not made", procName, NULL); for (i = 0; i < n; i++) { ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, y, x); } return ptad; } /*! * \brief ptaCyclicPerm() * * \param[in] ptas * \param[in] xs, ys start point; must be in ptas * \return ptad cyclic permutation, starting and ending at (xs, ys, * or NULL on error * * <pre> * Notes: * (1) Check to insure that (a) ptas is a closed path where * the first and last points are identical, and (b) the * resulting pta also starts and ends on the same point * (which in this case is (xs, ys). * </pre> */ PTA * ptaCyclicPerm(PTA *ptas, l_int32 xs, l_int32 ys) { l_int32 n, i, x, y, j, index, state; l_int32 x1, y1, x2, y2; PTA *ptad; PROCNAME("ptaCyclicPerm"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); /* Verify input data */ ptaGetIPt(ptas, 0, &x1, &y1); ptaGetIPt(ptas, n - 1, &x2, &y2); if (x1 != x2 || y1 != y2) return (PTA *)ERROR_PTR("start and end pts not same", procName, NULL); state = L_NOT_FOUND; for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); if (x == xs && y == ys) { state = L_FOUND; break; } } if (state == L_NOT_FOUND) return (PTA *)ERROR_PTR("start pt not in ptas", procName, NULL); if ((ptad = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("ptad not made", procName, NULL); for (j = 0; j < n - 1; j++) { if (i + j < n - 1) index = i + j; else index = (i + j + 1) % n; ptaGetIPt(ptas, index, &x, &y); ptaAddPt(ptad, x, y); } ptaAddPt(ptad, xs, ys); return ptad; } /*! * \brief ptaSelectRange() * * \param[in] ptas * \param[in] first use 0 to select from the beginning * \param[in] last use 0 to select to the end * \return ptad, or NULL on error */ PTA * ptaSelectRange(PTA *ptas, l_int32 first, l_int32 last) { l_int32 n, npt, i; l_float32 x, y; PTA *ptad; PROCNAME("ptaSelectRange"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if ((n = ptaGetCount(ptas)) == 0) { L_WARNING("ptas is empty\n", procName); return ptaCopy(ptas); } first = L_MAX(0, first); if (last <= 0) last = n - 1; if (first >= n) return (PTA *)ERROR_PTR("invalid first", procName, NULL); if (first > last) return (PTA *)ERROR_PTR("first > last", procName, NULL); npt = last - first + 1; ptad = ptaCreate(npt); for (i = first; i <= last; i++) { ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief <API key>() * * \param[in] pta * \return box, or NULL on error * * <pre> * Notes: * (1) This is used when the pta represents a set of points in * a two-dimensional image. It returns the box of minimum * size containing the pts in the pta. * </pre> */ BOX * <API key>(PTA *pta) { l_int32 n, i, x, y, minx, maxx, miny, maxy; PROCNAME("<API key>"); if (!pta) return (BOX *)ERROR_PTR("pta not defined", procName, NULL); minx = 10000000; miny = 10000000; maxx = -10000000; maxy = -10000000; n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; } return boxCreate(minx, miny, maxx - minx + 1, maxy - miny + 1); } /*! * \brief ptaGetRange() * * \param[in] pta * \param[out] pminx [optional] min value of x * \param[out] pmaxx [optional] max value of x * \param[out] pminy [optional] min value of y * \param[out] pmaxy [optional] max value of y * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) We can use pts to represent pairs of floating values, that * are not necessarily tied to a two-dimension region. For * example, the pts can represent a general function y(x). * </pre> */ l_int32 ptaGetRange(PTA *pta, l_float32 *pminx, l_float32 *pmaxx, l_float32 *pminy, l_float32 *pmaxy) { l_int32 n, i; l_float32 x, y, minx, maxx, miny, maxy; PROCNAME("ptaGetRange"); if (!pminx && !pmaxx && !pminy && !pmaxy) return ERROR_INT("no output requested", procName, 1); if (pminx) *pminx = 0; if (pmaxx) *pmaxx = 0; if (pminy) *pminy = 0; if (pmaxy) *pmaxy = 0; if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) == 0) return ERROR_INT("no points in pta", procName, 1); ptaGetPt(pta, 0, &x, &y); minx = x; maxx = x; miny = y; maxy = y; for (i = 1; i < n; i++) { ptaGetPt(pta, i, &x, &y); if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; } if (pminx) *pminx = minx; if (pmaxx) *pmaxx = maxx; if (pminy) *pminy = miny; if (pmaxy) *pmaxy = maxy; return 0; } /*! * \brief ptaGetInsideBox() * * \param[in] ptas input pts * \param[in] box * \return ptad of pts in ptas that are inside the box, or NULL on error */ PTA * ptaGetInsideBox(PTA *ptas, BOX *box) { PTA *ptad; l_int32 n, i, contains; l_float32 x, y; PROCNAME("ptaGetInsideBox"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (!box) return (PTA *)ERROR_PTR("box not defined", procName, NULL); n = ptaGetCount(ptas); ptad = ptaCreate(0); for (i = 0; i < n; i++) { ptaGetPt(ptas, i, &x, &y); boxContainsPt(box, x, y, &contains); if (contains) ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief pixFindCornerPixels() * * \param[in] pixs 1 bpp * \return pta, or NULL on error * * <pre> * Notes: * (1) Finds the 4 corner-most pixels, as defined by a search * inward from each corner, using a 45 degree line. * </pre> */ PTA * pixFindCornerPixels(PIX *pixs) { l_int32 i, j, x, y, w, h, wpl, mindim, found; l_uint32 *data, *line; PTA *pta; PROCNAME("pixFindCornerPixels"); if (!pixs) return (PTA *)ERROR_PTR("pixs not defined", procName, NULL); if (pixGetDepth(pixs) != 1) return (PTA *)ERROR_PTR("pixs not 1 bpp", procName, NULL); w = pixGetWidth(pixs); h = pixGetHeight(pixs); mindim = L_MIN(w, h); data = pixGetData(pixs); wpl = pixGetWpl(pixs); if ((pta = ptaCreate(4)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = i - j; line = data + y * wpl; if (GET_DATA_BIT(line, j)) { ptaAddPt(pta, j, y); found = TRUE; break; } } if (found == TRUE) break; } for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = i - j; line = data + y * wpl; x = w - 1 - j; if (GET_DATA_BIT(line, x)) { ptaAddPt(pta, x, y); found = TRUE; break; } } if (found == TRUE) break; } for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = h - 1 - i + j; line = data + y * wpl; if (GET_DATA_BIT(line, j)) { ptaAddPt(pta, j, y); found = TRUE; break; } } if (found == TRUE) break; } for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = h - 1 - i + j; line = data + y * wpl; x = w - 1 - j; if (GET_DATA_BIT(line, x)) { ptaAddPt(pta, x, y); found = TRUE; break; } } if (found == TRUE) break; } return pta; } /*! * \brief ptaContainsPt() * * \param[in] pta * \param[in] x, y point * \return 1 if contained, 0 otherwise or on error */ l_int32 ptaContainsPt(PTA *pta, l_int32 x, l_int32 y) { l_int32 i, n, ix, iy; PROCNAME("ptaContainsPt"); if (!pta) return ERROR_INT("pta not defined", procName, 0); n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &ix, &iy); if (x == ix && y == iy) return 1; } return 0; } /*! * \brief ptaTestIntersection() * * \param[in] pta1, pta2 * \return bval which is 1 if they have any elements in common; * 0 otherwise or on error. */ l_int32 ptaTestIntersection(PTA *pta1, PTA *pta2) { l_int32 i, j, n1, n2, x1, y1, x2, y2; PROCNAME("ptaTestIntersection"); if (!pta1) return ERROR_INT("pta1 not defined", procName, 0); if (!pta2) return ERROR_INT("pta2 not defined", procName, 0); n1 = ptaGetCount(pta1); n2 = ptaGetCount(pta2); for (i = 0; i < n1; i++) { ptaGetIPt(pta1, i, &x1, &y1); for (j = 0; j < n2; j++) { ptaGetIPt(pta2, i, &x2, &y2); if (x1 == x2 && y1 == y2) return 1; } } return 0; } /*! * \brief ptaTransform() * * \param[in] ptas * \param[in] shiftx, shifty * \param[in] scalex, scaley * \return pta, or NULL on error * * <pre> * Notes: * (1) Shift first, then scale. * </pre> */ PTA * ptaTransform(PTA *ptas, l_int32 shiftx, l_int32 shifty, l_float32 scalex, l_float32 scaley) { l_int32 n, i, x, y; PTA *ptad; PROCNAME("ptaTransform"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); x = (l_int32)(scalex * (x + shiftx) + 0.5); y = (l_int32)(scaley * (y + shifty) + 0.5); ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief ptaPtInsidePolygon() * * \param[in] pta vertices of a polygon * \param[in] x, y point to be tested * \param[out] pinside 1 if inside; 0 if outside or on boundary * \return 1 if OK, 0 on error * * The abs value of the sum of the angles subtended from a point by * the sides of a polygon, when taken in order traversing the polygon, * is 0 if the point is outside the polygon and 2*pi if inside. * The sign will be positive if traversed cw and negative if ccw. */ l_int32 ptaPtInsidePolygon(PTA *pta, l_float32 x, l_float32 y, l_int32 *pinside) { l_int32 i, n; l_float32 sum, x1, y1, x2, y2, xp1, yp1, xp2, yp2; PROCNAME("ptaPtInsidePolygon"); if (!pinside) return ERROR_INT("&inside not defined", procName, 1); *pinside = 0; if (!pta) return ERROR_INT("pta not defined", procName, 1); /* Think of (x1,y1) as the end point of a vector that starts * from the origin (0,0), and ditto for (x2,y2). */ n = ptaGetCount(pta); sum = 0.0; for (i = 0; i < n; i++) { ptaGetPt(pta, i, &xp1, &yp1); ptaGetPt(pta, (i + 1) % n, &xp2, &yp2); x1 = xp1 - x; y1 = yp1 - y; x2 = xp2 - x; y2 = yp2 - y; sum += <API key>(x1, y1, x2, y2); } if (L_ABS(sum) > M_PI) *pinside = 1; return 0; } /*! * \brief <API key>() * * \param[in] x1, y1 end point of first vector * \param[in] x2, y2 end point of second vector * \return angle radians, or 0.0 on error * * <pre> * Notes: * (1) This gives the angle between two vectors, going between * vector1 (x1,y1) and vector2 (x2,y2). The angle is swept * out from 1 --> 2. If this is clockwise, the angle is * positive, but the result is folded into the interval [-pi, pi]. * </pre> */ l_float32 <API key>(l_float32 x1, l_float32 y1, l_float32 x2, l_float32 y2) { l_float64 ang; ang = atan2(y2, x2) - atan2(y1, x1); if (ang > M_PI) ang -= 2.0 * M_PI; if (ang < -M_PI) ang += 2.0 * M_PI; return ang; } /*! * \brief ptaGetMinMax() * * \param[in] pta * \param[out] pxmin [optional] min of x * \param[out] pymin [optional] min of y * \param[out] pxmax [optional] max of x * \param[out] pymax [optional] max of y * \return 0 if OK, 1 on error. If pta is empty, requested * values are returned as -1.0. */ l_int32 ptaGetMinMax(PTA *pta, l_float32 *pxmin, l_float32 *pymin, l_float32 *pxmax, l_float32 *pymax) { l_int32 i, n; l_float32 x, y, xmin, ymin, xmax, ymax; PROCNAME("ptaGetMinMax"); if (pxmin) *pxmin = -1.0; if (pymin) *pymin = -1.0; if (pxmax) *pxmax = -1.0; if (pymax) *pymax = -1.0; if (!pta) return ERROR_INT("pta not defined", procName, 1); if (!pxmin && !pxmax && !pymin && !pymax) return ERROR_INT("no output requested", procName, 1); if ((n = ptaGetCount(pta)) == 0) { L_WARNING("pta is empty\n", procName); return 0; } xmin = ymin = 1.0e20; xmax = ymax = -1.0e20; for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); if (x < xmin) xmin = x; if (y < ymin) ymin = y; if (x > xmax) xmax = x; if (y > ymax) ymax = y; } if (pxmin) *pxmin = xmin; if (pymin) *pymin = ymin; if (pxmax) *pxmax = xmax; if (pymax) *pymax = ymax; return 0; } /*! * \brief ptaSelectByValue() * * \param[in] ptas * \param[in] xth, yth threshold values * \param[in] type L_SELECT_XVAL, L_SELECT_YVAL, * L_SELECT_IF_EITHER, L_SELECT_IF_BOTH * \param[in] relation L_SELECT_IF_LT, L_SELECT_IF_GT, * L_SELECT_IF_LTE, L_SELECT_IF_GTE * \return ptad filtered set, or NULL on error */ PTA * ptaSelectByValue(PTA *ptas, l_float32 xth, l_float32 yth, l_int32 type, l_int32 relation) { l_int32 i, n; l_float32 x, y; PTA *ptad; PROCNAME("ptaSelectByValue"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (ptaGetCount(ptas) == 0) { L_WARNING("ptas is empty\n", procName); return ptaCopy(ptas); } if (type != L_SELECT_XVAL && type != L_SELECT_YVAL && type != L_SELECT_IF_EITHER && type != L_SELECT_IF_BOTH) return (PTA *)ERROR_PTR("invalid type", procName, NULL); if (relation != L_SELECT_IF_LT && relation != L_SELECT_IF_GT && relation != L_SELECT_IF_LTE && relation != L_SELECT_IF_GTE) return (PTA *)ERROR_PTR("invalid relation", procName, NULL); n = ptaGetCount(ptas); ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(ptas, i, &x, &y); if (type == L_SELECT_XVAL) { if ((relation == L_SELECT_IF_LT && x < xth) || (relation == L_SELECT_IF_GT && x > xth) || (relation == L_SELECT_IF_LTE && x <= xth) || (relation == L_SELECT_IF_GTE && x >= xth)) ptaAddPt(ptad, x, y); } else if (type == L_SELECT_YVAL) { if ((relation == L_SELECT_IF_LT && y < yth) || (relation == L_SELECT_IF_GT && y > yth) || (relation == L_SELECT_IF_LTE && y <= yth) || (relation == L_SELECT_IF_GTE && y >= yth)) ptaAddPt(ptad, x, y); } else if (type == L_SELECT_IF_EITHER) { if (((relation == L_SELECT_IF_LT) && (x < xth || y < yth)) || ((relation == L_SELECT_IF_GT) && (x > xth || y > yth)) || ((relation == L_SELECT_IF_LTE) && (x <= xth || y <= yth)) || ((relation == L_SELECT_IF_GTE) && (x >= xth || y >= yth))) ptaAddPt(ptad, x, y); } else { /* L_SELECT_IF_BOTH */ if (((relation == L_SELECT_IF_LT) && (x < xth && y < yth)) || ((relation == L_SELECT_IF_GT) && (x > xth && y > yth)) || ((relation == L_SELECT_IF_LTE) && (x <= xth && y <= yth)) || ((relation == L_SELECT_IF_GTE) && (x >= xth && y >= yth))) ptaAddPt(ptad, x, y); } } return ptad; } /*! * \brief ptaCropToMask() * * \param[in] ptas input pta * \param[in] pixm 1 bpp mask * \return ptad with only pts under the mask fg, or NULL on error */ PTA * ptaCropToMask(PTA *ptas, PIX *pixm) { l_int32 i, n, x, y; l_uint32 val; PTA *ptad; PROCNAME("ptaCropToMask"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (!pixm || pixGetDepth(pixm) != 1) return (PTA *)ERROR_PTR("pixm undefined or not 1 bpp", procName, NULL); if (ptaGetCount(ptas) == 0) { L_INFO("ptas is empty\n", procName); return ptaCopy(ptas); } n = ptaGetCount(ptas); ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); pixGetPixel(pixm, x, y, &val); if (val == 1) ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief ptaGetLinearLSF() * * \param[in] pta * \param[out] pa [optional] slope a of least square fit: y = ax + b * \param[out] pb [optional] intercept b of least square fit * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) Either or both &a and &b must be input. They determine the * type of line that is fit. * (2) If both &a and &b are defined, this returns a and b that minimize: * * sum (yi - axi -b)^2 * i * * The method is simple: differentiate this expression w/rt a and b, * and solve the resulting two equations for a and b in terms of * various sums over the input data (xi, yi). * (3) We also allow two special cases, where either a = 0 or b = 0: * (a) If &a is given and &b = null, find the linear LSF that * goes through the origin (b = 0). * (b) If &b is given and &a = null, find the linear LSF with * zero slope (a = 0). * (4) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetLinearLSF(PTA *pta, l_float32 *pa, l_float32 *pb, NUMA **pnafit) { l_int32 n, i; l_float32 a, b, factor, sx, sy, sxx, sxy, val; l_float32 *xa, *ya; PROCNAME("ptaGetLinearLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 2) return ERROR_INT("less than 2 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sxx = sxy = 0.; if (pa && pb) { /* general line */ for (i = 0; i < n; i++) { sx += xa[i]; sy += ya[i]; sxx += xa[i] * xa[i]; sxy += xa[i] * ya[i]; } factor = n * sxx - sx * sx; if (factor == 0.0) return ERROR_INT("no solution found", procName, 1); factor = 1. / factor; a = factor * ((l_float32)n * sxy - sx * sy); b = factor * (sxx * sy - sx * sxy); } else if (pa) { /* b = 0; line through origin */ for (i = 0; i < n; i++) { sxx += xa[i] * xa[i]; sxy += xa[i] * ya[i]; } if (sxx == 0.0) return ERROR_INT("no solution found", procName, 1); a = sxy / sxx; b = 0.0; } else { /* a = 0; horizontal line */ for (i = 0; i < n; i++) sy += ya[i]; a = 0.0; b = sy / (l_float32)n; } if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { val = a * xa[i] + b; numaAddNumber(*pnafit, val); } } if (pa) *pa = a; if (pb) *pb = b; return 0; } /*! * \brief ptaGetQuadraticLSF() * * \param[in] pta * \param[out] pa [optional] coeff a of LSF: y = ax^2 + bx + c * \param[out] pb [optional] coeff b of LSF: y = ax^2 + bx + c * \param[out] pc [optional] coeff c of LSF: y = ax^2 + bx + c * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a quadratic least square fit to the set of points * in %pta. That is, it finds coefficients a, b and c that minimize: * * sum (yi - a*xi*xi -b*xi -c)^2 * i * * The method is simple: differentiate this expression w/rt * a, b and c, and solve the resulting three equations for these * coefficients in terms of various sums over the input data (xi, yi). * The three equations are in the form: * f[0][0]a + f[0][1]b + f[0][2]c = g[0] * f[1][0]a + f[1][1]b + f[1][2]c = g[1] * f[2][0]a + f[2][1]b + f[2][2]c = g[2] * (2) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetQuadraticLSF(PTA *pta, l_float32 *pa, l_float32 *pb, l_float32 *pc, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, sx, sy, sx2, sx3, sx4, sxy, sx2y; l_float32 *xa, *ya; l_float32 *f[3]; l_float32 g[3]; PROCNAME("ptaGetQuadraticLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pc && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 3) return ERROR_INT("less than 3 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sx2 = sx3 = sx4 = sxy = sx2y = 0.; for (i = 0; i < n; i++) { x = xa[i]; y = ya[i]; sx += x; sy += y; sx2 += x * x; sx3 += x * x * x; sx4 += x * x * x * x; sxy += x * y; sx2y += x * x * y; } for (i = 0; i < 3; i++) f[i] = (l_float32 *)LEPT_CALLOC(3, sizeof(l_float32)); f[0][0] = sx4; f[0][1] = sx3; f[0][2] = sx2; f[1][0] = sx3; f[1][1] = sx2; f[1][2] = sx; f[2][0] = sx2; f[2][1] = sx; f[2][2] = n; g[0] = sx2y; g[1] = sxy; g[2] = sy; /* Solve for the unknowns, also putting f-inverse into f */ ret = gaussjordan(f, g, 3); for (i = 0; i < 3; i++) LEPT_FREE(f[i]); if (ret) return ERROR_INT("quadratic solution failed", procName, 1); if (pa) *pa = g[0]; if (pb) *pb = g[1]; if (pc) *pc = g[2]; if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { x = xa[i]; y = g[0] * x * x + g[1] * x + g[2]; numaAddNumber(*pnafit, y); } } return 0; } /*! * \brief ptaGetCubicLSF() * * \param[in] pta * \param[out] pa [optional] coeff a of LSF: y = ax^3 + bx^2 + cx + d * \param[out] pb [optional] coeff b of LSF * \param[out] pc [optional] coeff c of LSF * \param[out] pd [optional] coeff d of LSF * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a cubic least square fit to the set of points * in %pta. That is, it finds coefficients a, b, c and d * that minimize: * * sum (yi - a*xi*xi*xi -b*xi*xi -c*xi - d)^2 * i * * Differentiate this expression w/rt a, b, c and d, and solve * the resulting four equations for these coefficients in * terms of various sums over the input data (xi, yi). * The four equations are in the form: * f[0][0]a + f[0][1]b + f[0][2]c + f[0][3] = g[0] * f[1][0]a + f[1][1]b + f[1][2]c + f[1][3] = g[1] * f[2][0]a + f[2][1]b + f[2][2]c + f[2][3] = g[2] * f[3][0]a + f[3][1]b + f[3][2]c + f[3][3] = g[3] * (2) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetCubicLSF(PTA *pta, l_float32 *pa, l_float32 *pb, l_float32 *pc, l_float32 *pd, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, sx, sy, sx2, sx3, sx4, sx5, sx6, sxy, sx2y, sx3y; l_float32 *xa, *ya; l_float32 *f[4]; l_float32 g[4]; PROCNAME("ptaGetCubicLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pd) *pd = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pc && !pd && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 4) return ERROR_INT("less than 4 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sx2 = sx3 = sx4 = sx5 = sx6 = sxy = sx2y = sx3y = 0.; for (i = 0; i < n; i++) { x = xa[i]; y = ya[i]; sx += x; sy += y; sx2 += x * x; sx3 += x * x * x; sx4 += x * x * x * x; sx5 += x * x * x * x * x; sx6 += x * x * x * x * x * x; sxy += x * y; sx2y += x * x * y; sx3y += x * x * x * y; } for (i = 0; i < 4; i++) f[i] = (l_float32 *)LEPT_CALLOC(4, sizeof(l_float32)); f[0][0] = sx6; f[0][1] = sx5; f[0][2] = sx4; f[0][3] = sx3; f[1][0] = sx5; f[1][1] = sx4; f[1][2] = sx3; f[1][3] = sx2; f[2][0] = sx4; f[2][1] = sx3; f[2][2] = sx2; f[2][3] = sx; f[3][0] = sx3; f[3][1] = sx2; f[3][2] = sx; f[3][3] = n; g[0] = sx3y; g[1] = sx2y; g[2] = sxy; g[3] = sy; /* Solve for the unknowns, also putting f-inverse into f */ ret = gaussjordan(f, g, 4); for (i = 0; i < 4; i++) LEPT_FREE(f[i]); if (ret) return ERROR_INT("cubic solution failed", procName, 1); if (pa) *pa = g[0]; if (pb) *pb = g[1]; if (pc) *pc = g[2]; if (pd) *pd = g[3]; if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { x = xa[i]; y = g[0] * x * x * x + g[1] * x * x + g[2] * x + g[3]; numaAddNumber(*pnafit, y); } } return 0; } /*! * \brief ptaGetQuarticLSF() * * \param[in] pta * \param[out] pa [optional] coeff a of LSF: * y = ax^4 + bx^3 + cx^2 + dx + e * \param[out] pb [optional] coeff b of LSF * \param[out] pc [optional] coeff c of LSF * \param[out] pd [optional] coeff d of LSF * \param[out] pe [optional] coeff e of LSF * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a quartic least square fit to the set of points * in %pta. That is, it finds coefficients a, b, c, d and 3 * that minimize: * * sum (yi - a*xi*xi*xi*xi -b*xi*xi*xi -c*xi*xi - d*xi - e)^2 * i * * Differentiate this expression w/rt a, b, c, d and e, and solve * the resulting five equations for these coefficients in * terms of various sums over the input data (xi, yi). * The five equations are in the form: * f[0][0]a + f[0][1]b + f[0][2]c + f[0][3] + f[0][4] = g[0] * f[1][0]a + f[1][1]b + f[1][2]c + f[1][3] + f[1][4] = g[1] * f[2][0]a + f[2][1]b + f[2][2]c + f[2][3] + f[2][4] = g[2] * f[3][0]a + f[3][1]b + f[3][2]c + f[3][3] + f[3][4] = g[3] * f[4][0]a + f[4][1]b + f[4][2]c + f[4][3] + f[4][4] = g[4] * (2) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetQuarticLSF(PTA *pta, l_float32 *pa, l_float32 *pb, l_float32 *pc, l_float32 *pd, l_float32 *pe, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, sx, sy, sx2, sx3, sx4, sx5, sx6, sx7, sx8; l_float32 sxy, sx2y, sx3y, sx4y; l_float32 *xa, *ya; l_float32 *f[5]; l_float32 g[5]; PROCNAME("ptaGetQuarticLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pd) *pd = 0.0; if (pe) *pe = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pc && !pd && !pe && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 5) return ERROR_INT("less than 5 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sx2 = sx3 = sx4 = sx5 = sx6 = sx7 = sx8 = 0; sxy = sx2y = sx3y = sx4y = 0.; for (i = 0; i < n; i++) { x = xa[i]; y = ya[i]; sx += x; sy += y; sx2 += x * x; sx3 += x * x * x; sx4 += x * x * x * x; sx5 += x * x * x * x * x; sx6 += x * x * x * x * x * x; sx7 += x * x * x * x * x * x * x; sx8 += x * x * x * x * x * x * x * x; sxy += x * y; sx2y += x * x * y; sx3y += x * x * x * y; sx4y += x * x * x * x * y; } for (i = 0; i < 5; i++) f[i] = (l_float32 *)LEPT_CALLOC(5, sizeof(l_float32)); f[0][0] = sx8; f[0][1] = sx7; f[0][2] = sx6; f[0][3] = sx5; f[0][4] = sx4; f[1][0] = sx7; f[1][1] = sx6; f[1][2] = sx5; f[1][3] = sx4; f[1][4] = sx3; f[2][0] = sx6; f[2][1] = sx5; f[2][2] = sx4; f[2][3] = sx3; f[2][4] = sx2; f[3][0] = sx5; f[3][1] = sx4; f[3][2] = sx3; f[3][3] = sx2; f[3][4] = sx; f[4][0] = sx4; f[4][1] = sx3; f[4][2] = sx2; f[4][3] = sx; f[4][4] = n; g[0] = sx4y; g[1] = sx3y; g[2] = sx2y; g[3] = sxy; g[4] = sy; /* Solve for the unknowns, also putting f-inverse into f */ ret = gaussjordan(f, g, 5); for (i = 0; i < 5; i++) LEPT_FREE(f[i]); if (ret) return ERROR_INT("quartic solution failed", procName, 1); if (pa) *pa = g[0]; if (pb) *pb = g[1]; if (pc) *pc = g[2]; if (pd) *pd = g[3]; if (pe) *pe = g[4]; if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { x = xa[i]; y = g[0] * x * x * x * x + g[1] * x * x * x + g[2] * x * x + g[3] * x + g[4]; numaAddNumber(*pnafit, y); } } return 0; } /*! * \brief ptaNoisyLinearLSF() * * \param[in] pta * \param[in] factor reject outliers with error greater than this * number of medians; typically ~ 3 * \param[out] pptad [optional] with outliers removed * \param[out] pa [optional] slope a of least square fit: y = ax + b * \param[out] pb [optional] intercept b of least square fit * \param[out] pmederr [optional] median error * \param[out] pnafit [optional] numa of least square fit to ptad * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a linear least square fit to the set of points * in %pta. It then evaluates the errors and removes points * whose error is >= factor * median_error. It then re-runs * the linear LSF on the resulting points. * (2) Either or both &a and &b must be input. They determine the * type of line that is fit. * (3) The median error can give an indication of how good the fit * is likely to be. * </pre> */ l_int32 ptaNoisyLinearLSF(PTA *pta, l_float32 factor, PTA **pptad, l_float32 *pa, l_float32 *pb, l_float32 *pmederr, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, yf, val, mederr; NUMA *nafit, *naerror; PTA *ptad; PROCNAME("ptaNoisyLinearLSF"); if (pptad) *pptad = NULL; if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pmederr) *pmederr = 0.0; if (pnafit) *pnafit = NULL; if (!pptad && !pa && !pb && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if (factor <= 0.0) return ERROR_INT("factor must be > 0.0", procName, 1); if ((n = ptaGetCount(pta)) < 3) return ERROR_INT("less than 2 pts found", procName, 1); if (ptaGetLinearLSF(pta, pa, pb, &nafit) != 0) return ERROR_INT("error in linear LSF", procName, 1); /* Get the median error */ naerror = numaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(nafit, i, &yf); numaAddNumber(naerror, L_ABS(y - yf)); } numaGetMedian(naerror, &mederr); if (pmederr) *pmederr = mederr; numaDestroy(&nafit); /* Remove outliers */ ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(naerror, i, &val); if (val <= factor * mederr) /* <= in case mederr = 0 */ ptaAddPt(ptad, x, y); } numaDestroy(&naerror); /* Do LSF again */ ret = ptaGetLinearLSF(ptad, pa, pb, pnafit); if (pptad) *pptad = ptad; else ptaDestroy(&ptad); return ret; } /*! * \brief <API key>() * * \param[in] pta * \param[in] factor reject outliers with error greater than this * number of medians; typically ~ 3 * \param[out] pptad [optional] with outliers removed * \param[out] pa [optional] coeff a of LSF: y = ax^2 + bx + c * \param[out] pb [optional] coeff b of LSF: y = ax^2 + bx + c * \param[out] pc [optional] coeff c of LSF: y = ax^2 + bx + c * \param[out] pmederr [optional] median error * \param[out] pnafit [optional] numa of least square fit to ptad * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a quadratic least square fit to the set of points * in %pta. It then evaluates the errors and removes points * whose error is >= factor * median_error. It then re-runs * a quadratic LSF on the resulting points. * </pre> */ l_int32 <API key>(PTA *pta, l_float32 factor, PTA **pptad, l_float32 *pa, l_float32 *pb, l_float32 *pc, l_float32 *pmederr, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, yf, val, mederr; NUMA *nafit, *naerror; PTA *ptad; PROCNAME("<API key>"); if (pptad) *pptad = NULL; if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pmederr) *pmederr = 0.0; if (pnafit) *pnafit = NULL; if (!pptad && !pa && !pb && !pc && !pnafit) return ERROR_INT("no output requested", procName, 1); if (factor <= 0.0) return ERROR_INT("factor must be > 0.0", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 3) return ERROR_INT("less than 3 pts found", procName, 1); if (ptaGetQuadraticLSF(pta, NULL, NULL, NULL, &nafit) != 0) return ERROR_INT("error in quadratic LSF", procName, 1); /* Get the median error */ naerror = numaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(nafit, i, &yf); numaAddNumber(naerror, L_ABS(y - yf)); } numaGetMedian(naerror, &mederr); if (pmederr) *pmederr = mederr; numaDestroy(&nafit); /* Remove outliers */ ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(naerror, i, &val); if (val <= factor * mederr) /* <= in case mederr = 0 */ ptaAddPt(ptad, x, y); } numaDestroy(&naerror); n = ptaGetCount(ptad); if ((n = ptaGetCount(ptad)) < 3) { ptaDestroy(&ptad); return ERROR_INT("less than 3 pts found", procName, 1); } /* Do LSF again */ ret = ptaGetQuadraticLSF(ptad, pa, pb, pc, pnafit); if (pptad) *pptad = ptad; else ptaDestroy(&ptad); return ret; } /*! * \brief applyLinearFit() * * \param[in] a, b linear fit coefficients * \param[in] x * \param[out] py y = a * x + b * \return 0 if OK, 1 on error */ l_int32 applyLinearFit(l_float32 a, l_float32 b, l_float32 x, l_float32 *py) { PROCNAME("applyLinearFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); *py = a * x + b; return 0; } /*! * \brief applyQuadraticFit() * * \param[in] a, b, c quadratic fit coefficients * \param[in] x * \param[out] py y = a * x^2 + b * x + c * \return 0 if OK, 1 on error */ l_int32 applyQuadraticFit(l_float32 a, l_float32 b, l_float32 c, l_float32 x, l_float32 *py) { PROCNAME("applyQuadraticFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); *py = a * x * x + b * x + c; return 0; } /*! * \brief applyCubicFit() * * \param[in] a, b, c, d cubic fit coefficients * \param[in] x * \param[out] py y = a * x^3 + b * x^2 + c * x + d * \return 0 if OK, 1 on error */ l_int32 applyCubicFit(l_float32 a, l_float32 b, l_float32 c, l_float32 d, l_float32 x, l_float32 *py) { PROCNAME("applyCubicFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); *py = a * x * x * x + b * x * x + c * x + d; return 0; } /*! * \brief applyQuarticFit() * * \param[in] a, b, c, d, e quartic fit coefficients * \param[in] x * \param[out] py y = a * x^4 + b * x^3 + c * x^2 + d * x + e * \return 0 if OK, 1 on error */ l_int32 applyQuarticFit(l_float32 a, l_float32 b, l_float32 c, l_float32 d, l_float32 e, l_float32 x, l_float32 *py) { l_float32 x2; PROCNAME("applyQuarticFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); x2 = x * x; *py = a * x2 * x2 + b * x2 * x + c * x2 + d * x + e; return 0; } /*! * \brief pixPlotAlongPta() * * \param[in] pixs any depth * \param[in] pta set of points on which to plot * \param[in] outformat GPLOT_PNG, GPLOT_PS, GPLOT_EPS, GPLOT_LATEX * \param[in] title [optional] for plot; can be null * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This is a debugging function. * (2) Removes existing colormaps and clips the pta to the input %pixs. * (3) If the image is RGB, three separate plots are generated. * </pre> */ l_int32 pixPlotAlongPta(PIX *pixs, PTA *pta, l_int32 outformat, const char *title) { char buffer[128]; char *rtitle, *gtitle, *btitle; static l_int32 count = 0; /* require separate temp files for each call */ l_int32 i, x, y, d, w, h, npts, rval, gval, bval; l_uint32 val; NUMA *na, *nar, *nag, *nab; PIX *pixt; PROCNAME("pixPlotAlongPta"); lept_mkdir("lept/plot"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if (outformat != GPLOT_PNG && outformat != GPLOT_PS && outformat != GPLOT_EPS && outformat != GPLOT_LATEX) { L_WARNING("outformat invalid; using GPLOT_PNG\n", procName); outformat = GPLOT_PNG; } pixt = pixRemoveColormap(pixs, <API key>); d = pixGetDepth(pixt); w = pixGetWidth(pixt); h = pixGetHeight(pixt); npts = ptaGetCount(pta); if (d == 32) { nar = numaCreate(npts); nag = numaCreate(npts); nab = numaCreate(npts); for (i = 0; i < npts; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w) continue; if (y < 0 || y >= h) continue; pixGetPixel(pixt, x, y, &val); rval = GET_DATA_BYTE(&val, COLOR_RED); gval = GET_DATA_BYTE(&val, COLOR_GREEN); bval = GET_DATA_BYTE(&val, COLOR_BLUE); numaAddNumber(nar, rval); numaAddNumber(nag, gval); numaAddNumber(nab, bval); } snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); rtitle = stringJoin("Red: ", title); gplotSimple1(nar, outformat, buffer, rtitle); snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); gtitle = stringJoin("Green: ", title); gplotSimple1(nag, outformat, buffer, gtitle); snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); btitle = stringJoin("Blue: ", title); gplotSimple1(nab, outformat, buffer, btitle); numaDestroy(&nar); numaDestroy(&nag); numaDestroy(&nab); LEPT_FREE(rtitle); LEPT_FREE(gtitle); LEPT_FREE(btitle); } else { na = numaCreate(npts); for (i = 0; i < npts; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w) continue; if (y < 0 || y >= h) continue; pixGetPixel(pixt, x, y, &val); numaAddNumber(na, (l_float32)val); } snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); gplotSimple1(na, outformat, buffer, title); numaDestroy(&na); } pixDestroy(&pixt); return 0; } /*! * \brief ptaGetPixelsFromPix() * * \param[in] pixs 1 bpp * \param[in] box [optional] can be null * \return pta, or NULL on error * * <pre> * Notes: * (1) Generates a pta of fg pixels in the pix, within the box. * If box == NULL, it uses the entire pix. * </pre> */ PTA * ptaGetPixelsFromPix(PIX *pixs, BOX *box) { l_int32 i, j, w, h, wpl, xstart, xend, ystart, yend, bw, bh; l_uint32 *data, *line; PTA *pta; PROCNAME("ptaGetPixelsFromPix"); if (!pixs || (pixGetDepth(pixs) != 1)) return (PTA *)ERROR_PTR("pixs undefined or not 1 bpp", procName, NULL); pixGetDimensions(pixs, &w, &h, NULL); data = pixGetData(pixs); wpl = pixGetWpl(pixs); xstart = ystart = 0; xend = w - 1; yend = h - 1; if (box) { boxGetGeometry(box, &xstart, &ystart, &bw, &bh); xend = xstart + bw - 1; yend = ystart + bh - 1; } if ((pta = ptaCreate(0)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = ystart; i <= yend; i++) { line = data + i * wpl; for (j = xstart; j <= xend; j++) { if (GET_DATA_BIT(line, j)) ptaAddPt(pta, j, i); } } return pta; } /*! * \brief pixGenerateFromPta() * * \param[in] pta * \param[in] w, h of pix * \return pix 1 bpp, or NULL on error * * <pre> * Notes: * (1) Points are rounded to nearest ints. * (2) Any points outside (w,h) are silently discarded. * (3) Output 1 bpp pix has values 1 for each point in the pta. * </pre> */ PIX * pixGenerateFromPta(PTA *pta, l_int32 w, l_int32 h) { l_int32 n, i, x, y; PIX *pix; PROCNAME("pixGenerateFromPta"); if (!pta) return (PIX *)ERROR_PTR("pta not defined", procName, NULL); if ((pix = pixCreate(w, h, 1)) == NULL) return (PIX *)ERROR_PTR("pix not made", procName, NULL); n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; pixSetPixel(pix, x, y, 1); } return pix; } /*! * \brief <API key>() * * \param[in] pixs 1 bpp * \param[in] type L_BOUNDARY_FG, L_BOUNDARY_BG * \return pta, or NULL on error * * <pre> * Notes: * (1) This generates a pta of either fg or bg boundary pixels. * (2) See also <API key>() for rendering of * fg boundary pixels. * </pre> */ PTA * <API key>(PIX *pixs, l_int32 type) { PIX *pixt; PTA *pta; PROCNAME("<API key>"); if (!pixs || (pixGetDepth(pixs) != 1)) return (PTA *)ERROR_PTR("pixs undefined or not 1 bpp", procName, NULL); if (type != L_BOUNDARY_FG && type != L_BOUNDARY_BG) return (PTA *)ERROR_PTR("invalid type", procName, NULL); if (type == L_BOUNDARY_FG) pixt = pixMorphSequence(pixs, "e3.3", 0); else pixt = pixMorphSequence(pixs, "d3.3", 0); pixXor(pixt, pixt, pixs); pta = ptaGetPixelsFromPix(pixt, NULL); pixDestroy(&pixt); return pta; } /*! * \brief <API key>() * * \param[in] pixs 1 bpp * \param[in] type L_BOUNDARY_FG, L_BOUNDARY_BG * \param[in] connectivity 4 or 8 * \param[out] pboxa [optional] bounding boxes of the c.c. * \param[out] ppixa [optional] pixa of the c.c. * \return ptaa, or NULL on error * * <pre> * Notes: * (1) This generates a ptaa of either fg or bg boundary pixels, * where each pta has the boundary pixels for a connected * component. * (2) We can't simply find all the boundary pixels and then select * those within the bounding box of each component, because * bounding boxes can overlap. It is necessary to extract and * dilate or erode each component separately. Note also that * special handling is required for bg pixels when the * component touches the pix boundary. * </pre> */ PTAA * <API key>(PIX *pixs, l_int32 type, l_int32 connectivity, BOXA **pboxa, PIXA **ppixa) { l_int32 i, n, w, h, x, y, bw, bh, left, right, top, bot; BOXA *boxa; PIX *pixt1, *pixt2; PIXA *pixa; PTA *pta1, *pta2; PTAA *ptaa; PROCNAME("<API key>"); if (pboxa) *pboxa = NULL; if (ppixa) *ppixa = NULL; if (!pixs || (pixGetDepth(pixs) != 1)) return (PTAA *)ERROR_PTR("pixs undefined or not 1 bpp", procName, NULL); if (type != L_BOUNDARY_FG && type != L_BOUNDARY_BG) return (PTAA *)ERROR_PTR("invalid type", procName, NULL); if (connectivity != 4 && connectivity != 8) return (PTAA *)ERROR_PTR("connectivity not 4 or 8", procName, NULL); pixGetDimensions(pixs, &w, &h, NULL); boxa = pixConnComp(pixs, &pixa, connectivity); n = boxaGetCount(boxa); ptaa = ptaaCreate(0); for (i = 0; i < n; i++) { pixt1 = pixaGetPix(pixa, i, L_CLONE); boxaGetBoxGeometry(boxa, i, &x, &y, &bw, &bh); left = right = top = bot = 0; if (type == L_BOUNDARY_BG) { if (x > 0) left = 1; if (y > 0) top = 1; if (x + bw < w) right = 1; if (y + bh < h) bot = 1; pixt2 = pixAddBorderGeneral(pixt1, left, right, top, bot, 0); } else { pixt2 = pixClone(pixt1); } pta1 = <API key>(pixt2, type); pta2 = ptaTransform(pta1, x - left, y - top, 1.0, 1.0); ptaaAddPta(ptaa, pta2, L_INSERT); ptaDestroy(&pta1); pixDestroy(&pixt1); pixDestroy(&pixt2); } if (pboxa) *pboxa = boxa; else boxaDestroy(&boxa); if (ppixa) *ppixa = pixa; else pixaDestroy(&pixa); return ptaa; } /*! * \brief <API key>() * * \param[in] pixs 32 bpp, of indices of c.c. * \param[out] pncc [optional] number of connected components * \return ptaa, or NULL on error * * <pre> * Notes: * (1) The pixel values in %pixs are the index of the connected component * to which the pixel belongs; %pixs is typically generated from * a 1 bpp pix by <API key>(). Background pixels in * the generating 1 bpp pix are represented in %pixs by 0. * We do not check that the pixel values are correctly labelled. * (2) Each pta in the returned ptaa gives the pixel locations * correspnding to a connected component, with the label of each * given by the index of the pta into the ptaa. * (3) Initialize with the first pta in ptaa being empty and * representing the background value (index 0) in the pix. * </pre> */ PTAA * <API key>(PIX *pixs, l_int32 *pncc) { l_int32 wpl, index, i, j, w, h; l_uint32 maxval; l_uint32 *data, *line; PTA *pta; PTAA *ptaa; PROCNAME("<API key>"); if (pncc) *pncc = 0; if (!pixs || (pixGetDepth(pixs) != 32)) return (PTAA *)ERROR_PTR("pixs undef or not 32 bpp", procName, NULL); /* The number of c.c. is the maximum pixel value. Use this to * initialize ptaa with sufficient pta arrays */ <API key>(pixs, NULL, &maxval, NULL, NULL); if (pncc) *pncc = maxval; pta = ptaCreate(1); ptaa = ptaaCreate(maxval + 1); ptaaInitFull(ptaa, pta); ptaDestroy(&pta); /* Sweep over %pixs, saving the pixel coordinates of each pixel * with nonzero value in the appropriate pta, indexed by that value. */ pixGetDimensions(pixs, &w, &h, NULL); data = pixGetData(pixs); wpl = pixGetWpl(pixs); for (i = 0; i < h; i++) { line = data + wpl * i; for (j = 0; j < w; j++) { index = line[j]; if (index > 0) ptaaAddPt(ptaa, index, j, i); } } return ptaa; } /*! * \brief <API key>() * * \param[in] pixs any depth * \param[in] x, y pixel from which we search for nearest neighbors * conn (4 or 8 connectivity * \return pta, or NULL on error * * <pre> * Notes: * (1) Generates a pta of all valid neighbor pixel locations, * or NULL on error. * </pre> */ PTA * <API key>(PIX *pixs, l_int32 x, l_int32 y, l_int32 conn) { l_int32 w, h; PTA *pta; PROCNAME("<API key>"); if (!pixs) return (PTA *)ERROR_PTR("pixs not defined", procName, NULL); pixGetDimensions(pixs, &w, &h, NULL); if (x < 0 || x >= w || y < 0 || y >= h) return (PTA *)ERROR_PTR("(x,y) not in pixs", procName, NULL); if (conn != 4 && conn != 8) return (PTA *)ERROR_PTR("conn not 4 or 8", procName, NULL); pta = ptaCreate(conn); if (x > 0) ptaAddPt(pta, x - 1, y); if (x < w - 1) ptaAddPt(pta, x + 1, y); if (y > 0) ptaAddPt(pta, x, y - 1); if (y < h - 1) ptaAddPt(pta, x, y + 1); if (conn == 8) { if (x > 0) { if (y > 0) ptaAddPt(pta, x - 1, y - 1); if (y < h - 1) ptaAddPt(pta, x - 1, y + 1); } if (x < w - 1) { if (y > 0) ptaAddPt(pta, x + 1, y - 1); if (y < h - 1) ptaAddPt(pta, x + 1, y + 1); } } return pta; } /*! * \brief numaConvertToPta1() * * \param[in] na numa with implicit y(x) * \return pta if OK; null on error */ PTA * numaConvertToPta1(NUMA *na) { l_int32 i, n; l_float32 startx, delx, val; PTA *pta; PROCNAME("numaConvertToPta1"); if (!na) return (PTA *)ERROR_PTR("na not defined", procName, NULL); n = numaGetCount(na); pta = ptaCreate(n); numaGetParameters(na, &startx, &delx); for (i = 0; i < n; i++) { numaGetFValue(na, i, &val); ptaAddPt(pta, startx + i * delx, val); } return pta; } /*! * \brief numaConvertToPta2() * * \param[in] nax * \param[in] nay * \return pta if OK; null on error */ PTA * numaConvertToPta2(NUMA *nax, NUMA *nay) { l_int32 i, n, nx, ny; l_float32 valx, valy; PTA *pta; PROCNAME("numaConvertToPta2"); if (!nax || !nay) return (PTA *)ERROR_PTR("nax and nay not both defined", procName, NULL); nx = numaGetCount(nax); ny = numaGetCount(nay); n = L_MIN(nx, ny); if (nx != ny) L_WARNING("nx = %d does not equal ny = %d\n", procName, nx, ny); pta = ptaCreate(n); for (i = 0; i < n; i++) { numaGetFValue(nax, i, &valx); numaGetFValue(nay, i, &valy); ptaAddPt(pta, valx, valy); } return pta; } /*! * \brief ptaConvertToNuma() * * \param[in] pta * \param[out] pnax addr of nax * \param[out] pnay addr of nay * \return 0 if OK, 1 on error */ l_int32 ptaConvertToNuma(PTA *pta, NUMA **pnax, NUMA **pnay) { l_int32 i, n; l_float32 valx, valy; PROCNAME("ptaConvertToNuma"); if (pnax) *pnax = NULL; if (pnay) *pnay = NULL; if (!pnax || !pnay) return ERROR_INT("&nax and &nay not both defined", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); n = ptaGetCount(pta); *pnax = numaCreate(n); *pnay = numaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &valx, &valy); numaAddNumber(*pnax, valx); numaAddNumber(*pnay, valy); } return 0; } /*! * \brief pixDisplayPta() * * \param[in] pixd can be same as pixs or NULL; 32 bpp if in-place * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp * \param[in] pta of path to be plotted * \return pixd 32 bpp RGB version of pixs, with path in green. * * <pre> * Notes: * (1) To write on an existing pixs, pixs must be 32 bpp and * call with pixd == pixs: * pixDisplayPta(pixs, pixs, pta); * To write to a new pix, use pixd == NULL and call: * pixd = pixDisplayPta(NULL, pixs, pta); * (2) On error, returns pixd to avoid losing pixs if called as * pixs = pixDisplayPta(pixs, pixs, pta); * </pre> */ PIX * pixDisplayPta(PIX *pixd, PIX *pixs, PTA *pta) { l_int32 i, n, w, h, x, y; l_uint32 rpixel, gpixel, bpixel; PROCNAME("pixDisplayPta"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, pixd); if (!pta) return (PIX *)ERROR_PTR("pta not defined", procName, pixd); if (pixd && (pixd != pixs || pixGetDepth(pixd) != 32)) return (PIX *)ERROR_PTR("invalid pixd", procName, pixd); if (!pixd) pixd = pixConvertTo32(pixs); pixGetDimensions(pixd, &w, &h, NULL); composeRGBPixel(255, 0, 0, &rpixel); /* start point */ composeRGBPixel(0, 255, 0, &gpixel); composeRGBPixel(0, 0, 255, &bpixel); /* end point */ n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; if (i == 0) pixSetPixel(pixd, x, y, rpixel); else if (i < n - 1) pixSetPixel(pixd, x, y, gpixel); else pixSetPixel(pixd, x, y, bpixel); } return pixd; } /*! * \brief <API key>() * * \param[in] pixd 32 bpp * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp; 32 bpp if in place * \param[in] ptaa giving locations at which the pattern is displayed * \param[in] pixp 1 bpp pattern to be placed such that its reference * point co-locates with each point in pta * \param[in] cx, cy reference point in pattern * \return pixd 32 bpp RGB version of pixs. * * <pre> * Notes: * (1) To write on an existing pixs, pixs must be 32 bpp and * call with pixd == pixs: * <API key>(pixs, pixs, pta, ...); * To write to a new pix, use pixd == NULL and call: * pixd = <API key>(NULL, pixs, pta, ...); * (2) Puts a random color on each pattern associated with a pta. * (3) On error, returns pixd to avoid losing pixs if called as * pixs = <API key>(pixs, pixs, pta, ...); * (4) A typical pattern to be used is a circle, generated with * <API key>() * </pre> */ PIX * <API key>(PIX *pixd, PIX *pixs, PTAA *ptaa, PIX *pixp, l_int32 cx, l_int32 cy) { l_int32 i, n; l_uint32 color; PIXCMAP *cmap; PTA *pta; PROCNAME("<API key>"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, pixd); if (!ptaa) return (PIX *)ERROR_PTR("ptaa not defined", procName, pixd); if (pixd && (pixd != pixs || pixGetDepth(pixd) != 32)) return (PIX *)ERROR_PTR("invalid pixd", procName, pixd); if (!pixp) return (PIX *)ERROR_PTR("pixp not defined", procName, pixd); if (!pixd) pixd = pixConvertTo32(pixs); /* Use 256 random colors */ cmap = pixcmapCreateRandom(8, 0, 0); n = ptaaGetCount(ptaa); for (i = 0; i < n; i++) { pixcmapGetColor32(cmap, i % 256, &color); pta = ptaaGetPta(ptaa, i, L_CLONE); <API key>(pixd, pixd, pta, pixp, cx, cy, color); ptaDestroy(&pta); } pixcmapDestroy(&cmap); return pixd; } /*! * \brief <API key>() * * \param[in] pixd can be same as pixs or NULL; 32 bpp if in-place * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp * \param[in] pta giving locations at which the pattern is displayed * \param[in] pixp 1 bpp pattern to be placed such that its reference * point co-locates with each point in pta * \param[in] cx, cy reference point in pattern * \param[in] color in 0xrrggbb00 format * \return pixd 32 bpp RGB version of pixs. * * <pre> * Notes: * (1) To write on an existing pixs, pixs must be 32 bpp and * call with pixd == pixs: * <API key>(pixs, pixs, pta, ...); * To write to a new pix, use pixd == NULL and call: * pixd = <API key>(NULL, pixs, pta, ...); * (2) On error, returns pixd to avoid losing pixs if called as * pixs = <API key>(pixs, pixs, pta, ...); * (3) A typical pattern to be used is a circle, generated with * <API key>() * </pre> */ PIX * <API key>(PIX *pixd, PIX *pixs, PTA *pta, PIX *pixp, l_int32 cx, l_int32 cy, l_uint32 color) { l_int32 i, n, w, h, x, y; PTA *ptat; PROCNAME("<API key>"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, pixd); if (!pta) return (PIX *)ERROR_PTR("pta not defined", procName, pixd); if (pixd && (pixd != pixs || pixGetDepth(pixd) != 32)) return (PIX *)ERROR_PTR("invalid pixd", procName, pixd); if (!pixp) return (PIX *)ERROR_PTR("pixp not defined", procName, pixd); if (!pixd) pixd = pixConvertTo32(pixs); pixGetDimensions(pixs, &w, &h, NULL); ptat = ptaReplicatePattern(pta, pixp, NULL, cx, cy, w, h); n = ptaGetCount(ptat); for (i = 0; i < n; i++) { ptaGetIPt(ptat, i, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; pixSetPixel(pixd, x, y, color); } ptaDestroy(&ptat); return pixd; } /*! * \brief ptaReplicatePattern() * * \param[in] ptas "sparse" input pta * \param[in] pixp [optional] 1 bpp pattern, to be replicated in output pta * \param[in] ptap [optional] set of pts, to be replicated in output pta * \param[in] cx, cy reference point in pattern * \param[in] w, h clipping sizes for output pta * \return ptad with all points of replicated pattern, or NULL on error * * <pre> * Notes: * (1) You can use either the image %pixp or the set of pts %ptap. * (2) The pattern is placed with its reference point at each point * in ptas, and all the fg pixels are colleced into ptad. * For %pixp, this is equivalent to blitting pixp at each point * in ptas, and then converting the resulting pix to a pta. * </pre> */ PTA * ptaReplicatePattern(PTA *ptas, PIX *pixp, PTA *ptap, l_int32 cx, l_int32 cy, l_int32 w, l_int32 h) { l_int32 i, j, n, np, x, y, xp, yp, xf, yf; PTA *ptat, *ptad; PROCNAME("ptaReplicatePattern"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (!pixp && !ptap) return (PTA *)ERROR_PTR("no pattern is defined", procName, NULL); if (pixp && ptap) L_WARNING("pixp and ptap defined; using ptap\n", procName); n = ptaGetCount(ptas); ptad = ptaCreate(n); if (ptap) ptat = ptaClone(ptap); else ptat = ptaGetPixelsFromPix(pixp, NULL); np = ptaGetCount(ptat); for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); for (j = 0; j < np; j++) { ptaGetIPt(ptat, j, &xp, &yp); xf = x - cx + xp; yf = y - cy + yp; if (xf >= 0 && xf < w && yf >= 0 && yf < h) ptaAddPt(ptad, xf, yf); } } ptaDestroy(&ptat); return ptad; } /*! * \brief pixDisplayPtaa() * * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp * \param[in] ptaa array of paths to be plotted * \return pixd 32 bpp RGB version of pixs, with paths plotted * in different colors, or NULL on error */ PIX * pixDisplayPtaa(PIX *pixs, PTAA *ptaa) { l_int32 i, j, w, h, npta, npt, x, y, rv, gv, bv; l_uint32 *pixela; NUMA *na1, *na2, *na3; PIX *pixd; PTA *pta; PROCNAME("pixDisplayPtaa"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if (!ptaa) return (PIX *)ERROR_PTR("ptaa not defined", procName, NULL); npta = ptaaGetCount(ptaa); if (npta == 0) return (PIX *)ERROR_PTR("no pta", procName, NULL); if ((pixd = pixConvertTo32(pixs)) == NULL) return (PIX *)ERROR_PTR("pixd not made", procName, NULL); pixGetDimensions(pixd, &w, &h, NULL); /* Make a colormap for the paths */ if ((pixela = (l_uint32 *)LEPT_CALLOC(npta, sizeof(l_uint32))) == NULL) { pixDestroy(&pixd); return (PIX *)ERROR_PTR("calloc fail for pixela", procName, NULL); } na1 = <API key>(256, 14657); na2 = <API key>(256, 34631); na3 = <API key>(256, 54617); for (i = 0; i < npta; i++) { numaGetIValue(na1, i % 256, &rv); numaGetIValue(na2, i % 256, &gv); numaGetIValue(na3, i % 256, &bv); composeRGBPixel(rv, gv, bv, &pixela[i]); } numaDestroy(&na1); numaDestroy(&na2); numaDestroy(&na3); for (i = 0; i < npta; i++) { pta = ptaaGetPta(ptaa, i, L_CLONE); npt = ptaGetCount(pta); for (j = 0; j < npt; j++) { ptaGetIPt(pta, j, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; pixSetPixel(pixd, x, y, pixela[i]); } ptaDestroy(&pta); } LEPT_FREE(pixela); return pixd; }
#include <ia32/arch/<API key>.h>
/** * If x is -Infinity and y>0 and y is an odd integer, Math.pow(x,y) is -Infinity * * @path ch15/15.8/15.8.2/15.8.2.13/S15.8.2.13_A13.js * @description Checking if Math.pow(x,y) equals to -Infinity, where x is -Infinity and y>0 */ // CHECK x = -Infinity; y = new Array(); y[0] = 1; y[1] = 111; y[2] = 111111; ynum = 3; for (i = 0; i < ynum; i++) { if (Math.pow(x,y[i]) !== -Infinity) { $ERROR("#1: Math.pow(" + x + ", " + y[i] + ") !== -Infinity"); } }
var fs = require('fs') var path = require('path') var resolve = path.resolve var osenv = require('osenv') var mkdirp = require('mkdirp') var rimraf = require('rimraf') var test = require('tap').test var npm = require('../../lib/npm') var common = require('../common-tap') var chain = require('slide').chain var mockPath = resolve(__dirname, '<API key>') var parentPath = resolve(mockPath, 'parent') var <API key> = path.join(parentPath, 'node_modules') var <API key> = resolve(mockPath, 'node-modules-backup') var childPath = resolve(mockPath, 'child.git') var gitDaemon var gitDaemonPID var git var parentPackageJSON = JSON.stringify({ name: 'parent', version: '0.1.0' }) var childPackageJSON = JSON.stringify({ name: 'child', version: '0.1.0' }) test('setup', function (t) { cleanup() setup(function (err, result) { t.ifError(err, 'git started up successfully') if (!err) { gitDaemon = result[result.length - 2] gitDaemonPID = result[result.length - 1] } t.end() }) }) test('shrinkwrapped git dependency got updated', function (t) { t.comment('test for https://github.com/npm/npm/issues/12718') // Prepare the child package git repo with two commits <API key>(function (refs) { chain([ // Install & shrinkwrap child package's first commit [npm.commands.install, ['git://localhost:1234/child.git#' + refs[0]]], // Backup node_modules with the first commit [fs.rename, <API key>, <API key>], // Install & shrinkwrap child package's second commit [npm.commands.install, ['git://localhost:1234/child.git#' + refs[1]]], // Restore node_modules with the first commit [rimraf, <API key>], [fs.rename, <API key>, <API key>], // Update node_modules [npm.commands.install, []] ], function () { var childPackageJSON = require(path.join(<API key>, 'child', 'package.json')) t.equal( childPackageJSON._resolved, 'git://localhost:1234/child.git#' + refs[1], "Child package wasn't updated" ) t.end() }) }) }) test('clean', function (t) { gitDaemon.on('close', function () { cleanup() t.end() }) process.kill(gitDaemonPID) }) function setup (cb) { // Setup parent package mkdirp.sync(parentPath) fs.writeFileSync(resolve(parentPath, 'package.json'), parentPackageJSON) process.chdir(parentPath) // Setup child mkdirp.sync(childPath) fs.writeFileSync(resolve(childPath, 'package.json'), childPackageJSON) // Setup npm and then git npm.load({ registry: common.registry, loglevel: 'silent', save: true // Always install packages with --save }, function () { // It's important to initialize git after npm because it uses config initializeGit(cb) }) } function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(mockPath) rimraf.sync(common['npm_config_cache']) } function <API key> (cb) { var opts = { cwd: childPath, env: { PATH: process.env.PATH } } chain([ [fs.writeFile, path.join(childPath, 'README.md'), ''], git.chainableExec(['add', 'README.md'], opts), git.chainableExec(['commit', '-m', 'Add README'], opts), git.chainableExec(['log', '--pretty=format:"%H"', '-2'], opts) ], function () { var gitLogStdout = arguments[arguments.length - 1] var refs = gitLogStdout[gitLogStdout.length - 1].split('\n').map(function (ref) { return ref.match(/^"(.+)"$/)[1] }).reverse() // Reverse refs order: last, first -> first, last cb(refs) }) } function initializeGit (cb) { git = require('../../lib/utils/git') common.makeGitRepo({ path: childPath, commands: [startGitDaemon] }, cb) } function startGitDaemon (cb) { var daemon = git.spawn( [ 'daemon', '--verbose', '--listen=localhost', '--export-all', '--base-path=' + mockPath, // Path to the dir that contains child.git '--reuseaddr', '--port=1234' ], { cwd: parentPath, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] } ) daemon.stderr.on('data', function findChild (c) { var cpid = c.toString().match(/^\[(\d+)\]/) if (cpid[1]) { this.removeListener('data', findChild) cb(null, [daemon, cpid[1]]) } }) }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using FluentAssertions.Collections; using FluentAssertions.Common; using FluentAssertions.Equivalency; using FluentAssertions.Numeric; using FluentAssertions.Primitives; using FluentAssertions.Types; namespace FluentAssertions { <summary> Contains extension methods for custom assertions in unit tests. </summary> [DebuggerNonUserCode] internal static class <API key> { <summary> Invokes the specified action on an subject so that you can chain it with any of the ShouldThrow or ShouldNotThrow overloads. </summary> public static Action Invoking<T>(this T subject, Action<T> action) { return () => action(subject); } <summary> Forces enumerating a collection. Should be used to assert that a method that uses the <c>yield</c> keyword throws a particular exception. </summary> public static Action Enumerating(this Func<IEnumerable> enumerable) { return () => ForceEnumeration(enumerable); } <summary> Forces enumerating a collection. Should be used to assert that a method that uses the <c>yield</c> keyword throws a particular exception. </summary> public static Action Enumerating<T>(this Func<IEnumerable<T>> enumerable) { return () => ForceEnumeration(() => (IEnumerable)enumerable()); } private static void ForceEnumeration(Func<IEnumerable> enumerable) { foreach (object item in enumerable()) { // Do nothing } } <summary> Returns an <see cref="ObjectAssertions"/> object that can be used to assert the current <see cref="object"/>. </summary> public static ObjectAssertions Should(this object actualValue) { return new ObjectAssertions(actualValue); } <summary> Returns an <see cref="BooleanAssertions"/> object that can be used to assert the current <see cref="bool"/>. </summary> public static BooleanAssertions Should(this bool actualValue) { return new BooleanAssertions(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current nullable <see cref="bool"/>. </summary> public static <API key> Should(this bool? actualValue) { return new <API key>(actualValue); } <summary> Returns an <see cref="GuidAssertions"/> object that can be used to assert the current <see cref="Guid"/>. </summary> public static GuidAssertions Should(this Guid actualValue) { return new GuidAssertions(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current nullable <see cref="Guid"/>. </summary> public static <API key> Should(this Guid? actualValue) { return new <API key>(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current <see cref="IEnumerable"/>. </summary> public static <API key> Should(this IEnumerable actualValue) { return new <API key>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current <see cref="IEnumerable{T}"/>. </summary> public static <API key><T> Should<T>(this IEnumerable<T> actualValue) { return new <API key><T>(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current <see cref="IEnumerable{T}"/>. </summary> public static <API key> Should(this IEnumerable<string> @this) { return new <API key>(@this); } <summary> Returns an <see cref="<API key>{TKey, TValue}"/> object that can be used to assert the current <see cref="IDictionary{TKey, TValue}"/>. </summary> public static <API key><TKey, TValue> Should<TKey, TValue>(this IDictionary<TKey, TValue> actualValue) { return new <API key><TKey, TValue>(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current <see cref="DateTime"/>. </summary> public static <API key> Should(this DateTime actualValue) { return new <API key>(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current nullable <see cref="DateTime"/>. </summary> public static <API key> Should(this DateTime? actualValue) { return new <API key>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current <see cref="IComparable{T}"/>. </summary> public static <API key><T> Should<T>(this IComparable<T> comparableValue) { return new <API key><T>(comparableValue); } <summary> Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the current <see cref="int"/>. </summary> public static NumericAssertions<int> Should(this int actualValue) { return new NumericAssertions<int>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current nullable <see cref="int"/>. </summary> public static <API key><int> Should(this int? actualValue) { return new <API key><int>(actualValue); } <summary> Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the current <see cref="decimal"/>. </summary> public static NumericAssertions<decimal> Should(this decimal actualValue) { return new NumericAssertions<decimal>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current nullable <see cref="decimal"/>. </summary> public static <API key><decimal> Should(this decimal? actualValue) { return new <API key><decimal>(actualValue); } <summary> Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the current <see cref="byte"/>. </summary> public static NumericAssertions<byte> Should(this byte actualValue) { return new NumericAssertions<byte>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current nullable <see cref="byte"/>. </summary> public static <API key><byte> Should(this byte? actualValue) { return new <API key><byte>(actualValue); } <summary> Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the current <see cref="short"/>. </summary> public static NumericAssertions<short> Should(this short actualValue) { return new NumericAssertions<short>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current nullable <see cref="short"/>. </summary> public static <API key><short> Should(this short? actualValue) { return new <API key><short>(actualValue); } <summary> Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the current <see cref="long"/>. </summary> public static NumericAssertions<long> Should(this long actualValue) { return new NumericAssertions<long>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current nullable <see cref="long"/>. </summary> public static <API key><long> Should(this long? actualValue) { return new <API key><long>(actualValue); } <summary> Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the current <see cref="float"/>. </summary> public static NumericAssertions<float> Should(this float actualValue) { return new NumericAssertions<float>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current nullable <see cref="float"/>. </summary> public static <API key><float> Should(this float? actualValue) { return new <API key><float>(actualValue); } <summary> Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the current <see cref="double"/>. </summary> public static NumericAssertions<double> Should(this double actualValue) { return new NumericAssertions<double>(actualValue); } <summary> Returns an <see cref="<API key>{T}"/> object that can be used to assert the current nullable <see cref="double"/>. </summary> public static <API key><double> Should(this double? actualValue) { return new <API key><double>(actualValue); } <summary> Returns an <see cref="StringAssertions"/> object that can be used to assert the current <see cref="string"/>. </summary> public static StringAssertions Should(this string actualValue) { return new StringAssertions(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current <see cref="TimeSpan"/>. </summary> public static <API key> Should(this TimeSpan actualValue) { return new <API key>(actualValue); } <summary> Returns an <see cref="<API key>"/> object that can be used to assert the current nullable <see cref="TimeSpan"/>. </summary> public static <API key> Should(this TimeSpan? actualValue) { return new <API key>(actualValue); } <summary> Returns a <see cref="TypeAssertions"/> object that can be used to assert the current <see cref="System.Type"/>. </summary> public static TypeAssertions Should(this Type subject) { return new TypeAssertions(subject); } <summary> Returns a <see cref="TypeAssertions"/> object that can be used to assert the current <see cref="System.Type"/>. </summary> public static <API key> Should(this TypeSelector typeSelector) { return new <API key>(typeSelector.ToArray()); } <summary> Returns a <see cref="<API key>"/> object that can be used to assert the current <see cref="MethodInfo"/>. </summary> <seealso cref="TypeAssertions"/> public static <API key> Should(this MethodInfo methodInfo) { return new <API key>(methodInfo); } <summary> Returns a <see cref="<API key>"/> object that can be used to assert the methods returned by the current <see cref="MethodInfoSelector"/>. </summary> <seealso cref="TypeAssertions"/> public static <API key> Should(this MethodInfoSelector methodSelector) { return new <API key>(methodSelector.ToArray()); } <summary> Returns a <see cref="<API key>"/> object that can be used to assert the current <see cref="<API key>"/>. </summary> <seealso cref="TypeAssertions"/> public static <API key> Should(this PropertyInfo propertyInfo) { return new <API key>(propertyInfo); } <summary> Returns a <see cref="<API key>"/> object that can be used to assert the properties returned by the current <see cref="<API key>"/>. </summary> <seealso cref="TypeAssertions"/> public static <API key> Should(this <API key> <API key>) { return new <API key>(<API key>.ToArray()); } <summary> Asserts that an object is equivalent to another object. </summary> <remarks> Objects are equivalent when both object graphs have equally named properties with the same value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal. The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all items in the collection are structurally equal. Notice that actual behavior is determined by the <see cref="<API key>.Default"/> instance of the <see cref="<API key>"/> class. </remarks> <param name="because"> An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. </param> <param name="becauseArgs"> Zero or more objects to format using the placeholders in <see cref="because" />. </param> public static void <API key><T>(this T subject, object expectation, string because = "", params object[] becauseArgs) { <API key>(subject, expectation, config => config, because, becauseArgs); } <summary> Asserts that an object is equivalent to another object. </summary> <remarks> Objects are equivalent when both object graphs have equally named properties with the same value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal. The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all items in the collection are structurally equal. </remarks> <param name="config"> A reference to the <see cref="<API key>.Default"/> configuration object that can be used to influence the way the object graphs are compared. You can also provide an alternative instance of the <see cref="<API key>"/> class. </param> <param name="because"> An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. </param> <param name="becauseArgs"> Zero or more objects to format using the placeholders in <see cref="because" />. </param> public static void <API key><T>(this T subject, object expectation, Func<<API key><T>, <API key><T>> config, string because = "", params object[] becauseArgs) { <API key> options = config(AssertionOptions.CloneDefaults<T>()); var context = new <API key> { Subject = subject, Expectation = expectation, CompileTimeType = typeof(T), Because = because, BecauseArgs = becauseArgs, Tracer = options.TraceWriter }; new <API key>(options).AssertEquality(context); } public static void <API key><T>(this IEnumerable<T> subject, IEnumerable expectation, string because = "", params object[] becauseArgs) { <API key>(subject, expectation, config => config, because, becauseArgs); } public static void <API key><T>(this IEnumerable<T> subject, IEnumerable expectation, Func<<API key><T>, <API key><T>> config, string because = "", params object[] becauseArgs) { <API key> options = config(AssertionOptions.CloneDefaults<T>()); var context = new <API key> { Subject = subject, Expectation = expectation, CompileTimeType = typeof(T), Because = because, BecauseArgs = becauseArgs, Tracer = options.TraceWriter }; new <API key>(options).AssertEquality(context); } <summary> Safely casts the specified object to the type specified through <typeparamref name="TTo"/>. </summary> <remarks> Has been introduced to allow casting objects without breaking the fluent API. </remarks> <typeparam name="TTo"></typeparam> public static TTo As<TTo>(this object subject) { return subject is TTo ? (TTo)subject : default(TTo); } } }
// test cube var assert = require('assert'), math = require('../../../index'), error = require('../../../lib/error/index'), unit = math.unit, bignumber = math.bignumber, matrix = math.matrix, range = math.range, cube = math.cube; describe('cube', function() { it('should return the cube of a boolean', function () { assert.equal(cube(true), 1); assert.equal(cube(false), 0); }); it('should return the cube of null', function () { assert.equal(math.ceil(null), 0); }); it('should return the cube of a number', function() { assert.equal(cube(4), 64); assert.equal(cube(-2), -8); assert.equal(cube(0), 0); }); it('should return the cube of a big number', function() { assert.deepEqual(cube(bignumber(4)), bignumber(64)); assert.deepEqual(cube(bignumber(-2)), bignumber(-8)); assert.deepEqual(cube(bignumber(0)), bignumber(0)); }); it('should return the cube of a complex number', function() { assert.deepEqual(cube(math.complex('2i')), math.complex('-8i')); assert.deepEqual(cube(math.complex('2+3i')), math.complex('-46+9i')); assert.deepEqual(cube(math.complex('2')), math.complex('8')); }); it('should throw an error with strings', function() { assert.throws(function () {cube('text')}); }); it('should throw an error with units', function() { assert.throws(function () {cube(unit('5cm'))}); }); it('should throw an error if there\'s wrong number of args', function() { assert.throws(function () {cube()}, error.ArgumentsError); assert.throws(function () {cube(1, 2)}, error.ArgumentsError); }); it('should cube each element in a matrix, array or range', function() { // array, matrix, range // arrays are evaluated element wise assert.deepEqual(cube([2,3,4,5]), [8,27,64,125]); assert.deepEqual(cube(matrix([2,3,4,5])), matrix([8,27,64,125])); assert.deepEqual(cube(matrix([[1,2],[3,4]])), matrix([[1,8],[27,64]])); }); });
// Purpose: // $NoKeywords: $ #include "cbase.h" #include "hl2mp_cvars.h" // Ready restart ConVar mp_readyrestart( "mp_readyrestart", "0", FCVAR_GAMEDLL, "If non-zero, game will restart once each player gives the ready signal" ); // Ready signal ConVar mp_ready_signal( "mp_ready_signal", "ready", FCVAR_GAMEDLL, "Text that each player must speak for the match to begin" );
// This file was automatically generated. Do not modify. 'use strict'; goog.provide('Blockly.Msg.id'); goog.require('Blockly.Msg'); Blockly.Msg.ADD_COMMENT = "Tambahkan sebuah comment"; Blockly.Msg.CHANGE_VALUE_TITLE = "Ubah nilai:"; Blockly.Msg.COLLAPSE_ALL = "Tutup blok"; Blockly.Msg.COLLAPSE_BLOCK = "Tutup blok"; Blockly.Msg.<API key> = "Warna 1"; Blockly.Msg.<API key> = "Warna 2"; Blockly.Msg.<API key> = "http://meyerweb.com/eric/tools/color-blend/"; Blockly.Msg.COLOUR_BLEND_RATIO = "rasio"; Blockly.Msg.COLOUR_BLEND_TITLE = "Tertutup"; Blockly.Msg.<API key> = "mencampur dua warna secara bersamaan dengan perbandingan (0.0-1.0)."; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Color"; Blockly.Msg.<API key> = "Pilih warna dari daftar warna."; Blockly.Msg.<API key> = "http://randomcolour.com"; // untranslated Blockly.Msg.COLOUR_RANDOM_TITLE = "Warna acak"; Blockly.Msg.<API key> = "Pilih warna secara acak."; Blockly.Msg.COLOUR_RGB_BLUE = "biru"; Blockly.Msg.COLOUR_RGB_GREEN = "hijau"; Blockly.Msg.COLOUR_RGB_HELPURL = "http: Blockly.Msg.COLOUR_RGB_RED = "merah"; Blockly.Msg.COLOUR_RGB_TITLE = "Dengan warna"; Blockly.Msg.COLOUR_RGB_TOOLTIP = "Buatlah warna dengan jumlah yang ditentukan dari merah, hijau dan biru. Semua nilai harus antarai 0 sampai 100."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Loops#<API key>"; Blockly.Msg.<API key> = "Keluar dari perulangan"; Blockly.Msg.<API key> = "Lanjutkan dengan langkah penggulangan berikutnya"; Blockly.Msg.<API key> = "Keluar sementara dari perulanggan."; Blockly.Msg.<API key> = "Abaikan sisa dari loop ini, dan lanjutkan dengan iterasi berikutnya."; Blockly.Msg.<API key> = "Peringatan: Blok ini hanya dapat digunakan dalam loop."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Loops#for_each for each block"; Blockly.Msg.<API key> = "di dalam list"; Blockly.Msg.<API key> = ""; // untranslated Blockly.Msg.<API key> = "untuk setiap item"; Blockly.Msg.<API key> = "Untuk tiap-tiap item di dalam list, tetapkan variabel '%1' ke dalam item, selanjutnya kerjakan beberapa statement."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Loops#count_with"; Blockly.Msg.<API key> = "dari %1 ke %2 dengan step / penambahan %3"; Blockly.Msg.<API key> = "Cacah dengan"; Blockly.Msg.<API key> = "Menggunakan variabel %1 dengan mengambil nilai dari batas awal hingga ke batas akhir, dengan interval tertentu, dan mengerjakan block tertentu."; Blockly.Msg.<API key> = "tambahkan prasyarat ke dalam blok IF."; Blockly.Msg.<API key> = "Terakhir, tambahkan tangkap-semua kondisi kedalam blok jika (if)."; Blockly.Msg.CONTROLS_IF_HELPURL = "http://code.google.com/p/blockly/wiki/If_Then"; Blockly.Msg.<API key> = "Menambahkan, menghapus, atau menyusun kembali bagian untuk mengkonfigurasi blok IF ini."; Blockly.Msg.<API key> = "else"; Blockly.Msg.<API key> = "else if"; Blockly.Msg.CONTROLS_IF_MSG_IF = "Jika"; Blockly.Msg.<API key> = "jika nilainya benar maka kerjakan perintah berikutnya."; Blockly.Msg.<API key> = "jika nilainya benar, maka kerjakan blok perintah yang pertama. Jika tidak, kerjakan blok perintah yang kedua."; Blockly.Msg.<API key> = "Jika nilai pertama adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok pertama. Jika nilai kedua adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok kedua."; Blockly.Msg.<API key> = "Jika blok pertama adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok pertama. Atau jika blok kedua adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok kedua."; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/For_loop"; Blockly.Msg.<API key> = "kerjakan"; Blockly.Msg.<API key> = "ulangi %1 kali"; Blockly.Msg.<API key> = "ulangi"; Blockly.Msg.<API key> = "kali"; Blockly.Msg.<API key> = "Lakukan beberapa perintah beberapa kali."; Blockly.Msg.<API key> = "http://code.google.com/p/blockly/wiki/Repeat"; Blockly.Msg.<API key> = "Ulangi sampai"; Blockly.Msg.<API key> = "Ulangi jika"; Blockly.Msg.<API key> = "Jika sementara nilai tidak benar (false), maka lakukan beberapa perintah."; Blockly.Msg.<API key> = "Jika sementara nilai benar (true), maka lakukan beberapa perintah."; Blockly.Msg.DELETE_BLOCK = "Hapus blok"; Blockly.Msg.DELETE_X_BLOCKS = "Hapus %1 blok"; Blockly.Msg.DISABLE_BLOCK = "Nonaktifkan blok"; Blockly.Msg.DUPLICATE_BLOCK = "Duplikat"; Blockly.Msg.ENABLE_BLOCK = "Aktifkan blok"; Blockly.Msg.EXPAND_ALL = "Kembangkan blok-blok"; Blockly.Msg.EXPAND_BLOCK = "Kembangkan blok"; Blockly.Msg.EXTERNAL_INPUTS = "Input-input eksternal"; Blockly.Msg.HELP = "Tolong"; Blockly.Msg.INLINE_INPUTS = "Input inline"; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists"; Blockly.Msg.<API key> = "buat list kosong"; Blockly.Msg.<API key> = "Mengembalikan daftar, dengan panjang 0, tidak berisi data"; Blockly.Msg.<API key> = "list"; Blockly.Msg.<API key> = "Tambahkan, hapus, atau susun ulang bagian untuk mengkonfigurasi blok LIST (daftar) ini."; Blockly.Msg.<API key> = "buat daftar (list) dengan"; Blockly.Msg.<API key> = "Tambahkan sebuah item ke daftar (list)."; Blockly.Msg.<API key> = "Buat sebuah daftar (list) dengan sejumlah item."; Blockly.Msg.<API key> = "pertama"; Blockly.Msg.<API key> = "# dari akhir"; Blockly.Msg.<API key> = " Blockly.Msg.LISTS_GET_INDEX_GET = "dapatkan"; Blockly.Msg.<API key> = "dapatkan dan hapus"; Blockly.Msg.<API key> = "terakhir"; Blockly.Msg.<API key> = "acak"; Blockly.Msg.<API key> = "Hapus"; Blockly.Msg.<API key> = ""; // untranslated Blockly.Msg.<API key> = "Kembalikan item pertama dalam daftar (list)."; Blockly.Msg.<API key> = "Sisipkan item ke dalam posisi yang telah ditentukan didalam list (daftar). Item pertama adalah item yang terakhir."; Blockly.Msg.<API key> = "Sisipkan item ke dalam posisi yang telah ditentukan didalam list (daftar). Item pertama adalah item terakhir (yg paling akhir)."; Blockly.Msg.<API key> = "Mengembalikan item pertama dalam list (daftar)."; Blockly.Msg.<API key> = "Mengembalikan item acak dalam list (daftar)."; Blockly.Msg.<API key> = "Menghilangkan dan mengembalikan item pertama dalam list (daftar)."; Blockly.Msg.<API key> = "Menghilangkan dan mengembalikan barang di posisi tertentu dalam list (daftar). #1 adalah item terakhir."; Blockly.Msg.<API key> = "Menghilangkan dan mengembalikan barang di posisi tertentu dalam list (daftar). #1 adalah item pertama."; Blockly.Msg.<API key> = "Menghilangkan dan mengembalikan item terakhir dalam list (daftar)."; Blockly.Msg.<API key> = "Menghilangkan dan mengembalikan barang dengan acak dalam list (daftar)."; Blockly.Msg.<API key> = "Menghapus item pertama dalam daftar."; Blockly.Msg.<API key> = "Menghapus item dengan posisi tertentu dalam daftar. Item pertama adalah item yang terakhir."; Blockly.Msg.<API key> = "Menghapus item dengan posisi tertentu dalam daftar. Item pertama adalah item yang terakhir."; Blockly.Msg.<API key> = "Menghapus item terakhir dalam daftar."; Blockly.Msg.<API key> = "Menghapus sebuah item secara acak dalam list."; Blockly.Msg.<API key> = "ke # dari akhir"; Blockly.Msg.<API key> = "ke Blockly.Msg.<API key> = "ke yang paling akhir"; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Lists#Getting_a_sublist"; Blockly.Msg.<API key> = "Dapatkan bagian pertama dari list"; Blockly.Msg.<API key> = "Dapatkan bagian list nomor # dari akhir"; Blockly.Msg.<API key> = "Dapatkan bagian daftar dari Blockly.Msg.<API key> = ""; // untranslated Blockly.Msg.<API key> = "Membuat salinan dari bagian tertentu dari list."; Blockly.Msg.<API key> = "cari kejadian pertama item"; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Lists#<API key>"; Blockly.Msg.LISTS_INDEX_OF_LAST = "Cari kejadian terakhir item"; Blockly.Msg.<API key> = "Mengembalikan indeks dari kejadian pertama/terakhir item dalam daftar. Menghasilkan 0 jika teks tidak ditemukan."; Blockly.Msg.LISTS_INLIST = "dalam daftar"; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Lists#is_empty"; Blockly.Msg.<API key> = "%1 kosong"; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Lists#length_of"; Blockly.Msg.LISTS_LENGTH_TITLE = "panjang dari %1"; Blockly.Msg.<API key> = "Mengembalikan panjang daftar."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Lists#create_list_with"; Blockly.Msg.LISTS_REPEAT_TITLE = "membuat daftar dengan item %1 diulang %2 kali"; Blockly.Msg.<API key> = "Ciptakan daftar yang terdiri dari nilai yang diberikan diulang jumlah waktu yang ditentukan."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Lists#in_list_..._set"; Blockly.Msg.<API key> = "sebagai"; Blockly.Msg.<API key> = "sisipkan di"; Blockly.Msg.LISTS_SET_INDEX_SET = "tetapkan"; Blockly.Msg.<API key> = "Sisipkan item di bagian awal dari list."; Blockly.Msg.<API key> = "Sisipkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang terakhir."; Blockly.Msg.<API key> = "Sisipkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang pertama."; Blockly.Msg.<API key> = "Tambahkan item ke bagian akhir list."; Blockly.Msg.<API key> = "Sisipkan item secara acak ke dalam list."; Blockly.Msg.<API key> = "Tetapkan item pertama di dalam list."; Blockly.Msg.<API key> = "Tetapkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang terakhir."; Blockly.Msg.<API key> = "Tetapkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang pertama."; Blockly.Msg.<API key> = "Menetapkan item terakhir dalam list."; Blockly.Msg.<API key> = "Tetapkan secara acak sebuah item dalam list."; Blockly.Msg.LISTS_TOOLTIP = "Mengembalikan nilai benar (true) jika list kosong."; Blockly.Msg.LOGIC_BOOLEAN_FALSE = "Salah"; Blockly.Msg.<API key> = "http://code.google.com/p/blockly/wiki/True_False"; Blockly.Msg.<API key> = "Mengembalikan betul (true) atau salah (false)."; Blockly.Msg.LOGIC_BOOLEAN_TRUE = "Benar"; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; Blockly.Msg.<API key> = "Mengembalikan betul jika input kedua-duanya sama dengan satu sama lain."; Blockly.Msg.<API key> = "Mengembalikan nilai benar (true) jika input yang pertama lebih besar dari input yang kedua."; Blockly.Msg.<API key> = "Mengembalikan nilai benar (true) jika input yang pertama lebih besar dari atau sama dengan input yang kedua."; Blockly.Msg.<API key> = "Mengembalikan nilai benar (true) jika input yang pertama lebih kecil dari input yang kedua."; Blockly.Msg.<API key> = "Mengembalikan nilai benar (true) jika input yang pertama lebih kecil atau sama dengan input yang kedua ."; Blockly.Msg.<API key> = "Mengembalikan nilai benar (true) jika kedua input tidak sama satu dengan yang lain."; Blockly.Msg.<API key> = "http://code.google.com/p/blockly/wiki/Not"; Blockly.Msg.LOGIC_NEGATE_TITLE = "bukan (not) %1"; Blockly.Msg.<API key> = "Mengembalikan nilai benar (true) jika input false. Mengembalikan nilai salah (false) jika input true."; Blockly.Msg.LOGIC_NULL = "null"; Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; Blockly.Msg.LOGIC_NULL_TOOLTIP = "mengembalikan kosong."; Blockly.Msg.LOGIC_OPERATION_AND = "dan"; Blockly.Msg.<API key> = "http://code.google.com/p/blockly/wiki/And_Or"; Blockly.Msg.LOGIC_OPERATION_OR = "atau"; Blockly.Msg.<API key> = "Kembalikan betul jika kedua-dua input adalah betul."; Blockly.Msg.<API key> = "Mengembalikan nilai benar (true) jika setidaknya salah satu masukan nilainya benar (true)."; Blockly.Msg.<API key> = "test"; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/%3F:"; Blockly.Msg.<API key> = "jika tidak benar (false)"; Blockly.Msg.<API key> = "jika benar (true)"; Blockly.Msg.<API key> = "Periksa kondisi di \"test\". Jika kondisi benar (true), mengembalikan nilai \"jika benar\" ; Jik sebaliknya akan mengembalikan nilai \"jika salah\"."; Blockly.Msg.<API key> = "+"; Blockly.Msg.<API key> = "https://id.wikipedia.org/wiki/Aritmetika"; Blockly.Msg.<API key> = "Kembalikan jumlah dari kedua angka."; Blockly.Msg.<API key> = "Kembalikan hasil bagi dari kedua angka."; Blockly.Msg.<API key> = "Kembalikan selisih dari kedua angka."; Blockly.Msg.<API key> = "Kembalikan perkalian dari kedua angka."; Blockly.Msg.<API key> = "Kembalikan angka pertama pangkat angka kedua."; Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#<API key>"; Blockly.Msg.<API key> = "oleh"; Blockly.Msg.<API key> = "ubah"; Blockly.Msg.MATH_CHANGE_TOOLTIP = "Tambahkan angka kedalam variabel '%1'."; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/<API key>"; Blockly.Msg.<API key> = "Kembalikan salah satu konstant: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), atau ∞ (infinity)."; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; Blockly.Msg.<API key> = "Batasi %1 rendah %2 tinggi %3"; Blockly.Msg.<API key> = "Batasi angka antara batas yang ditentukan (inklusif)."; Blockly.Msg.<API key> = "÷"; Blockly.Msg.<API key> = "dibagi oleh"; Blockly.Msg.MATH_IS_EVEN = "adalah bilangan genap"; Blockly.Msg.MATH_IS_NEGATIVE = "adalah bilangan negatif"; Blockly.Msg.MATH_IS_ODD = "adalah bilangan ganjil"; Blockly.Msg.MATH_IS_POSITIVE = "adalah bilangan positif"; Blockly.Msg.MATH_IS_PRIME = "adalah bilangan pokok"; Blockly.Msg.MATH_IS_TOOLTIP = "Periksa apakah angka adalah bilangan genap, bilangan pokok, bilangan bulat, bilangan positif, bilangan negatif, atau apakan bisa dibagi oleh angka tertentu. Mengembalikan benar (true) atau salah (false)."; Blockly.Msg.MATH_IS_WHOLE = "adalah bilangan bulat"; Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; Blockly.Msg.MATH_MODULO_TITLE = "sisa %1 ÷ %2"; Blockly.Msg.MATH_MODULO_TOOLTIP = "Kembalikan sisa dari pembagian ke dua angka."; Blockly.Msg.<API key> = "×"; Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number"; Blockly.Msg.MATH_NUMBER_TOOLTIP = "Suatu angka."; Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated Blockly.Msg.<API key> = "rata-rata dari list (daftar)"; Blockly.Msg.<API key> = "maximum dari list (daftar)"; Blockly.Msg.<API key> = "median dari list (daftar)"; Blockly.Msg.<API key> = "minimum dari list (daftar)"; Blockly.Msg.<API key> = "mode-mode dari list (daftar)"; Blockly.Msg.<API key> = "item acak dari list (daftar)"; Blockly.Msg.<API key> = "deviasi standar dari list (daftar)"; Blockly.Msg.<API key> = "jumlah dari list (daftar)"; Blockly.Msg.<API key> = "Kembalikan rata-rata (mean aritmetik) dari nilai numerik dari list (daftar)."; Blockly.Msg.<API key> = "Kembalikan angka terbesar dari list."; Blockly.Msg.<API key> = "Kembalikan median dari list."; Blockly.Msg.<API key> = "Kembalikan angka terkecil dari list."; Blockly.Msg.<API key> = "Kembalikan list berisi item-item yang paling umum dari dalam list."; Blockly.Msg.<API key> = "Kembalikan element acak dari list."; Blockly.Msg.<API key> = "Kembalikan standard deviasi dari list."; Blockly.Msg.<API key> = "Kembalikan jumlah dari seluruh bilangan dari list."; Blockly.Msg.MATH_POWER_SYMBOL = "^"; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/<API key>"; Blockly.Msg.<API key> = "Nilai pecahan acak"; Blockly.Msg.<API key> = "Mengembalikan nilai acak pecahan antara 0.0 (inklusif) dan 1.0 (ekslusif)."; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/<API key>"; Blockly.Msg.<API key> = "acak bulat dari %1 sampai %2"; Blockly.Msg.<API key> = "Mengembalikan bilangan acak antara dua batas yang ditentukan, inklusif."; Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; Blockly.Msg.<API key> = "membulatkan"; Blockly.Msg.<API key> = "membulatkan kebawah"; Blockly.Msg.<API key> = "mengumpulkan"; Blockly.Msg.MATH_ROUND_TOOLTIP = "Bulatkan suatu bilangan naik atau turun."; Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root"; Blockly.Msg.<API key> = "mutlak"; Blockly.Msg.MATH_SINGLE_OP_ROOT = "akar"; Blockly.Msg.<API key> = "Kembalikan nilai absolut angka."; Blockly.Msg.<API key> = "Kembalikan 10 pangkat angka."; Blockly.Msg.<API key> = "Kembalikan logaritma natural dari angka."; Blockly.Msg.<API key> = "Kembalikan dasar logaritma 10 dari angka."; Blockly.Msg.<API key> = "Kembalikan penyangkalan terhadap angka."; Blockly.Msg.<API key> = "Kembalikan 10 pangkat angka."; Blockly.Msg.<API key> = "Kembalikan akar dari angka."; Blockly.Msg.<API key> = "-"; Blockly.Msg.MATH_TRIG_ACOS = "acos"; Blockly.Msg.MATH_TRIG_ASIN = "asin"; Blockly.Msg.MATH_TRIG_ATAN = "atan"; Blockly.Msg.MATH_TRIG_COS = "cos"; Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/<API key>"; Blockly.Msg.MATH_TRIG_SIN = "sin"; Blockly.Msg.MATH_TRIG_TAN = "tan"; Blockly.Msg.<API key> = "Kembalikan acosine dari angka."; Blockly.Msg.<API key> = "Kembalikan asin dari angka."; Blockly.Msg.<API key> = "Kembalikan atan dari angka."; Blockly.Msg.<API key> = "Kembalikan cos dari derajat (bukan radian)."; Blockly.Msg.<API key> = "Kembalikan sinus dari derajat (bukan radian)."; Blockly.Msg.<API key> = "Kembalikan tangen dari derajat (tidak radian)."; Blockly.Msg.NEW_VARIABLE = "Pembolehubah baru..."; Blockly.Msg.NEW_VARIABLE_TITLE = "Nama pembolehubah baru:"; Blockly.Msg.<API key> = ""; // untranslated Blockly.Msg.<API key> = "dengan:"; Blockly.Msg.<API key> = ""; // untranslated Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.<API key> = "Menjalankan fungsi '%1' yang ditetapkan pengguna."; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.<API key> = "Menjalankan fungsi '%1' yang ditetapkan pengguna dan menggunakan outputnya."; Blockly.Msg.<API key> = "Buat '%1'"; Blockly.Msg.<API key> = ""; // untranslated Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.<API key> = "buat sesuatu"; Blockly.Msg.<API key> = "untuk"; Blockly.Msg.<API key> = "Menciptakan sebuah fungsi dengan tiada output."; Blockly.Msg.<API key> = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.<API key> = "kembali"; Blockly.Msg.<API key> = "Menciptakan sebuah fungsi dengan satu output."; Blockly.Msg.<API key> = "Peringatan: Fungsi ini memiliki parameter duplikat."; Blockly.Msg.<API key> = "Sorot definisi fungsi"; Blockly.Msg.<API key> = "Jika nilai yang benar, kemudian kembalikan nilai kedua."; Blockly.Msg.<API key> = "Peringatan: Blok ini dapat digunakan hanya dalam definisi fungsi."; Blockly.Msg.<API key> = "masukan Nama:"; Blockly.Msg.<API key> = "input"; Blockly.Msg.REMOVE_COMMENT = "Hapus komentar"; Blockly.Msg.RENAME_VARIABLE = "namai ulang variabel..."; Blockly.Msg.<API key> = "Ubah nama semua variabel '%1' menjadi:"; Blockly.Msg.<API key> = "tambahkan teks"; Blockly.Msg.TEXT_APPEND_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; Blockly.Msg.TEXT_APPEND_TO = "untuk"; Blockly.Msg.TEXT_APPEND_TOOLTIP = "Tambahkan beberapa teks ke variabel '%1'."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Text#Adjusting_text_case"; Blockly.Msg.<API key> = "menjadi huruf kecil"; Blockly.Msg.<API key> = "menjadi huruf pertama kapital"; Blockly.Msg.<API key> = "menjadi huruf kapital"; Blockly.Msg.<API key> = "Kembalikan kopi dari text dengan kapitalisasi yang berbeda."; Blockly.Msg.TEXT_CHARAT_FIRST = "ambil huruf pertama"; Blockly.Msg.<API key> = "ambil huruf nomor # dari belakang"; Blockly.Msg.<API key> = "ambil huruf ke Blockly.Msg.TEXT_CHARAT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_text"; Blockly.Msg.<API key> = "dalam teks"; Blockly.Msg.TEXT_CHARAT_LAST = "ambil huruf terakhir"; Blockly.Msg.TEXT_CHARAT_RANDOM = "ambil huruf secara acak"; Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Kembalikan karakter dari posisi tertentu."; Blockly.Msg.<API key> = "Tambahkan suatu item ke dalam teks."; Blockly.Msg.<API key> = "join"; Blockly.Msg.<API key> = "Tambah, ambil, atau susun ulang teks blok."; Blockly.Msg.<API key> = "pada huruf nomer # dari terakhir"; Blockly.Msg.<API key> = "pada huruf Blockly.Msg.<API key> = "pada huruf terakhir"; Blockly.Msg.<API key> = "http://code.google.com/p/blockly/wiki/Text#<API key>"; Blockly.Msg.<API key> = "in teks"; Blockly.Msg.<API key> = "ambil bagian teks (substring) dari huruf pertama"; Blockly.Msg.<API key> = "ambil bagian teks (substring) dari huruf ke # dari terakhir"; Blockly.Msg.<API key> = "ambil bagian teks (substring) dari huruf no Blockly.Msg.<API key> = ""; // untranslated Blockly.Msg.<API key> = "Mengembalikan spesifik bagian dari teks."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Text#Finding_text"; Blockly.Msg.<API key> = "dalam teks"; Blockly.Msg.<API key> = "temukan kejadian pertama dalam teks"; Blockly.Msg.<API key> = "temukan kejadian terakhir dalam teks"; Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated Blockly.Msg.<API key> = "Kembalikan indeks pertama dan terakhir dari kejadian pertama/terakhir dari teks pertama dalam teks kedua. Kembalikan 0 jika teks tidak ditemukan."; Blockly.Msg.<API key> = "https://code.google.com/p/blockly/wiki/Text#<API key>"; Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 kosong"; Blockly.Msg.<API key> = "Kembalikan benar (true) jika teks yang disediakan kosong."; Blockly.Msg.TEXT_JOIN_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_creation"; Blockly.Msg.<API key> = "Buat teks dengan"; Blockly.Msg.TEXT_JOIN_TOOLTIP = "Buat teks dengan cara gabungkan sejumlah item."; Blockly.Msg.TEXT_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; Blockly.Msg.TEXT_LENGTH_TITLE = "panjang dari %1"; Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Kembalikan sejumlah huruf (termasuk spasi) dari teks yang disediakan."; Blockly.Msg.TEXT_PRINT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Printing_text"; Blockly.Msg.TEXT_PRINT_TITLE = "cetak %1"; Blockly.Msg.TEXT_PRINT_TOOLTIP = "Cetak teks yant ditentukan, angka atau ninlai lainnya."; Blockly.Msg.TEXT_PROMPT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#<API key>"; Blockly.Msg.<API key> = "Meminta pengguna untuk memberi sebuah angka."; Blockly.Msg.<API key> = "Meminta pengguna untuk memberi beberapa teks."; Blockly.Msg.<API key> = "Meminta angka dengan pesan"; Blockly.Msg.<API key> = "meminta teks dengan pesan"; Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; Blockly.Msg.TEXT_TEXT_TOOLTIP = "Huruf, kata atau baris teks."; Blockly.Msg.TEXT_TRIM_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Trimming_%28removing%29_spaces"; Blockly.Msg.<API key> = "pangkas ruang dari kedua belah sisi"; Blockly.Msg.<API key> = "pangkas ruang dari sisi kiri"; Blockly.Msg.<API key> = "pangkas ruang dari sisi kanan"; Blockly.Msg.TEXT_TRIM_TOOLTIP = "Kembali salinan teks dengan spasi dihapus dari satu atau kedua ujungnya."; Blockly.Msg.<API key> = "item"; Blockly.Msg.<API key> = "Membuat 'tetapkan %1'"; Blockly.Msg.<API key> = "http://code.google.com/p/blockly/wiki/Variables#Get"; Blockly.Msg.VARIABLES_GET_TAIL = ""; // untranslated Blockly.Msg.VARIABLES_GET_TITLE = ""; // untranslated Blockly.Msg.<API key> = "Mengembalikan nilai variabel ini."; Blockly.Msg.<API key> = "Membuat 'dapatkan %1'"; Blockly.Msg.<API key> = "http://code.google.com/p/blockly/wiki/Variables#Set"; Blockly.Msg.VARIABLES_SET_TAIL = "untuk"; Blockly.Msg.VARIABLES_SET_TITLE = "tetapkan"; Blockly.Msg.<API key> = "tetapkan variabel ini dengan input yang sama."; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.LISTS_INLIST; Blockly.Msg.<API key> = Blockly.Msg.LISTS_INLIST; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.LISTS_INLIST; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.LISTS_INLIST; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.CONTROLS_IF_MSG_IF; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>; Blockly.Msg.<API key> = Blockly.Msg.<API key>;
package servicebroker import ( "reflect" "testing" schema "github.com/lestrrat/go-jsschema" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/openshift/origin/pkg/openservicebroker/api" templateapi "github.com/openshift/origin/pkg/template/api" ) func <API key>(t *testing.T) { template := &templateapi.Template{ ObjectMeta: metav1.ObjectMeta{ Name: "name", UID: "<API key>", Annotations: map[string]string{ "description": "description", "tags": "tag1,tag2", "openshift.io/display-name": "displayName", "iconClass": "iconClass", "template.openshift.io/long-description": "longDescription", "template.openshift.io/<API key>": "providerDisplayName", "template.openshift.io/documentation-url": "documentationURL", "template.openshift.io/support-url": "supportURL", }, }, Parameters: []templateapi.Parameter{ { Name: "param1", Required: true, }, { Name: "param2", }, }, } expectedService := &api.Service{ Name: "name", ID: "<API key>", Description: "description", Tags: []string{"tag1", "tag2"}, Bindable: true, Metadata: map[string]interface{}{ "providerDisplayName": "providerDisplayName", "documentationUrl": "documentationURL", "supportUrl": "supportURL", "displayName": "displayName", "console.openshift.io/iconClass": "iconClass", "longDescription": "longDescription", }, Plans: []api.Plan{ { ID: "<API key>", Name: "default", Description: "Default plan", Free: true, Bindable: true, Schemas: api.Schema{ ServiceInstances: api.ServiceInstances{ Create: map[string]*schema.Schema{ "parameters": { Type: schema.PrimitiveTypes{schema.ObjectType}, SchemaRef: "http://json-schema.org/draft-04/schema", Required: []string{ "template.openshift.io/namespace", "template.openshift.io/requester-username", "param1", }, Properties: map[string]*schema.Schema{ "template.openshift.io/namespace": { Title: "Template service broker: namespace", Description: "OpenShift namespace in which to provision service", Type: schema.PrimitiveTypes{schema.StringType}, }, "template.openshift.io/requester-username": { Title: "Template service broker: requester username", Description: "OpenShift user requesting provision/bind", Type: schema.PrimitiveTypes{schema.StringType}, }, "param1": { Default: "", Type: schema.PrimitiveTypes{schema.StringType}, }, "param2": { Default: "", Type: schema.PrimitiveTypes{schema.StringType}, }, }, }, }, }, ServiceBindings: api.ServiceBindings{ Create: map[string]*schema.Schema{ "parameters": { Type: schema.PrimitiveTypes{schema.ObjectType}, SchemaRef: "http://json-schema.org/draft-04/schema", Required: []string{"template.openshift.io/requester-username"}, Properties: map[string]*schema.Schema{ "template.openshift.io/requester-username": { Title: "Template service broker: requester username", Description: "OpenShift user requesting provision/bind", Type: schema.PrimitiveTypes{schema.StringType}, }, }, }, }, }, }, }, }, } service := serviceFromTemplate(template) if !reflect.DeepEqual(service, expectedService) { t.Error("service did not match expectedService") } }
using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { internal static Task<RemoteHostClient.Session> <API key>( Solution solution, Cancellation<API key>) => <API key>(solution, serverCallback: null, cancellation<API key>); private static async Task<RemoteHostClient.Session> <API key>( Solution solution, object serverCallback, Cancellation<API key>) { var outOfProcessAllowed = solution.Workspace.Options.GetOption(SymbolFinderOptions.OutOfProcessAllowed); if (!outOfProcessAllowed) { return null; } var client = await solution.Workspace.<API key>(cancellationToken).ConfigureAwait(false); if (client == null) { return null; } return await client.<API key>( solution, serverCallback, cancellationToken).ConfigureAwait(false); } } }
from threading import Timer class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class TakesScreenshotTest : DriverTestFixture { [TearDown] public void SwitchToTop() { driver.SwitchTo().DefaultContent(); } [Test] public void GetScreenshotAsFile() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = simpleTestPage; string filename = Path.Combine(Path.GetTempPath(), "snapshot" + new Random().Next().ToString() + ".png"); Screenshot screenImage = <API key>.GetScreenshot(); screenImage.SaveAsFile(filename, <API key>.Png); Assert.That(File.Exists(filename), Is.True); Assert.That(new FileInfo(filename).Length, Is.GreaterThan(0)); File.Delete(filename); } [Test] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = <API key>.GetScreenshot(); string base64 = screenImage.<API key>; Assert.That(base64.Length, Is.GreaterThan(0)); } [Test] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = <API key>.GetScreenshot(); byte[] bytes = screenImage.AsByteArray; Assert.That(bytes.Length, Is.GreaterThan(0)); } [Test] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step */ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void <API key>() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); IWebElement element = driver.FindElement(By.Id("cell11")); ITakesScreenshot <API key> = element as ITakesScreenshot; if (<API key> == null) { return; } Screenshot screenImage = <API key>.GetScreenshot(); byte[] imageData = screenImage.AsByteArray; Assert.That(imageData, Is.Not.Null); Assert.That(imageData.Length, Is.GreaterThan(0)); Color pixelColor = GetPixelColor(screenImage, 1, 1); string pixelColorString = FormatColorToHex(pixelColor.ToArgb()); Assert.AreEqual("#0f12f7", pixelColorString); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_long.html"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 50, /* stepY in pixels */ 5); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_long.html"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 50); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_too_long.html"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 5); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_too_long.html"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 100); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_too_long.html"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 100); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); WaitFor(<API key>("frame1"), "Did not switch to frame1"); WaitFor(<API key>("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(<API key>("frame2"), "Did not switch to frame2"); WaitFor(<API key>("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(TitleToBe("screen test"), "Title was not expected value"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(<API key>( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.IE, "Color comparisons fail on IE")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(<API key>( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); driver.SwitchTo().Frame(driver.FindElement(By.Id("frame2"))); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(<API key>( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames after switching to a frame // will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.IE, "Color comparisons fail on IE")] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void <API key>() { ITakesScreenshot <API key> = driver as ITakesScreenshot; if (<API key> == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe2"))); Screenshot screenshot = <API key>.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = <API key>( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(<API key>( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes after switching to a Iframe // will be taken for full page CompareColors(expectedColors, actualColors); } private string FormatColorToHex(int colorValue) { string pixelColorString = string.Format("#{0:x2}{1:x2}{2:x2}", (colorValue & 0xFF0000) >> 16, (colorValue & 0x00FF00) >> 8, (colorValue & 0x0000FF)); return pixelColorString; } private void CompareColors(HashSet<string> expectedColors, HashSet<string> actualColors) { // Ignore black and white for further comparison actualColors.Remove("#000000"); actualColors.Remove("#ffffff"); Assert.That(actualColors, Is.EquivalentTo(expectedColors)); } private HashSet<string> <API key>(int initialColor, int stepColor, int numberOfSamplesX, int numberOfSamplesY) { HashSet<string> colors = new HashSet<string>(); int count = 1; for (int i = 1; i < numberOfSamplesX; i++) { for (int j = 1; j < numberOfSamplesY; j++) { int color = initialColor + (count * stepColor); string hex = FormatColorToHex(color); colors.Add(hex); count++; } } return colors; } private HashSet<string> ScanActualColors(Screenshot screenshot, int stepX, int stepY) { HashSet<string> colors = new HashSet<string>(); #if !NETCOREAPP2_0 && !NETSTANDARD2_0 try { Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); int height = bitmap.Height; int width = bitmap.Width; Assert.That(width, Is.GreaterThan(0)); Assert.That(height, Is.GreaterThan(0)); for (int i = 0; i < width; i = i + stepX) { for (int j = 0; j < height; j = j + stepY) { string hex = FormatColorToHex(bitmap.GetPixel(i, j).ToArgb()); colors.Add(hex); } } } catch (Exception e) { Assert.Fail("Unable to get actual colors from screenshot: " + e.Message); } Assert.That(colors.Count, Is.GreaterThan(0)); #endif return colors; } private Color GetPixelColor(Screenshot screenshot, int x, int y) { Color pixelColor = Color.Black; #if !NETCOREAPP2_0 && !NETSTANDARD2_0 Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); pixelColor = bitmap.GetPixel(1, 1); #endif return pixelColor; } private Func<bool> <API key>(string frameId) { return () => { try { IWebElement frameElement = driver.FindElement(By.Id(frameId)); driver.SwitchTo().Frame(frameElement); } catch(Exception) { return false; } return true; }; } private Func<bool> <API key>(string elementId) { return () => { try { IWebElement element = driver.FindElement(By.Id(elementId)); return element.Displayed; } catch(Exception) { return false; } }; } private Func<bool> TitleToBe(string desiredTitle) { return () => driver.Title == desiredTitle; } } }
#ifndef DLIB_DNN_CuDNN_H_ #define DLIB_DNN_CuDNN_H_ #ifdef DLIB_USE_CUDA #include "cuda_errors.h" namespace dlib { class tensor; class resizable_tensor; namespace cuda { class tensor_descriptor { /*! Each tensor object will carry a tensor_descriptor in it when compiled with CUDA. !*/ public: // not copyable tensor_descriptor(const tensor_descriptor&) = delete; tensor_descriptor& operator=(const tensor_descriptor&) = delete; // but is movable tensor_descriptor(tensor_descriptor&& item) : tensor_descriptor() { swap(item); } tensor_descriptor& operator=(tensor_descriptor&& item) { swap(item); return *this; } tensor_descriptor(); ~tensor_descriptor(); void set_size( int n, int k, int nr, int nc ); /*! ensures - if any of the arguments are 0 then they are all set to 0 in the tensor. !*/ void get_size ( int& n, int& k, int& nr, int& nc ) const; const void* get_handle ( ) const { return handle; } private: void swap(tensor_descriptor& item) { std::swap(handle, item.handle); } void* handle; }; void add( float beta, tensor& dest, float alpha, const tensor& src ); /*! requires - One of the following is true: - <API key>(src, dest) - src.num_samples()==1 && src.k()==dest.k() && src.nr()==1 && src.nc()==1 - src.num_samples()==1 && src.k()==dest.k() && src.nr()==dest.nr() && src.nc()==dest.nc() - src.num_samples()==1 && src.k()==1 && src.nr()==dest.nr() && src.nc()==dest.nc() - is_same_object(src,dest) == false ensures - performs: dest = beta*dest + alpha*src However, how the addition happens depends on the dimensions of src. In particular, this function adds the scaled values of one src tensor to dest. Each dimension of the src tensor must match the corresponding dimension of the dest tensor or must be equal to 1. In the latter case, the same value from the src tensor, for those dimensions, will be used to add into the dest tensor. !*/ void set_tensor ( tensor& t, float value ); /*! ensures - sets all elements in t equal to value. !*/ void scale_tensor ( tensor& t, float value ); /*! ensures - scales all elements of t by the given value. I.e. for all elements E in t, this function performs: - E = E*value !*/ void <API key> ( tensor& grad, const tensor& gradient_input ); /*! requires - grad.num_samples() == 1 - grad.k() >= 1 - grad.nr() == 1 - grad.nc() == 1 - gradient_input.k() == grad.k() - gradient_input.size() > 0 - is_same_object(grad,gradient_input) == false ensures - let BIAS be a tensor with all dimensions equal to 1 except for k which is >= 1. - let OUT be the output of add(1,OUT,1,BIAS) - let f(gradient_input,BIAS) == dot(gradient_input,OUT) - Then this function computes the gradient of f() with respect to BIAS and assigns it to grad. !*/ void <API key> ( const double eps, resizable_tensor& dest, const tensor& src, const tensor& gamma, const tensor& beta, const tensor& running_means, const tensor& running_variances ); void batch_normalize ( const double eps, resizable_tensor& dest, resizable_tensor& means, resizable_tensor& invstds, const double averaging_factor, resizable_tensor& running_means, resizable_tensor& running_variances, const tensor& src, const tensor& gamma, const tensor& beta ); void <API key>( const double eps, const tensor& gradient_input, const tensor& means, const tensor& invstds, const tensor& src, const tensor& gamma, tensor& src_grad, tensor& gamma_grad, tensor& beta_grad ); void <API key> ( const double eps, resizable_tensor& dest, const tensor& src, const tensor& gamma, const tensor& beta, const tensor& running_means, const tensor& running_variances ); void <API key> ( const double eps, resizable_tensor& dest, resizable_tensor& means, resizable_tensor& invstds, const double averaging_factor, resizable_tensor& running_means, resizable_tensor& running_variances, const tensor& src, const tensor& gamma, const tensor& beta ); void <API key>( const double eps, const tensor& gradient_input, const tensor& means, const tensor& invstds, const tensor& src, const tensor& gamma, tensor& src_grad, tensor& gamma_grad, tensor& beta_grad ); class tensor_conv { public: tensor_conv(const tensor_conv&) = delete; tensor_conv& operator=(const tensor_conv&) = delete; tensor_conv(); void clear( ); ~tensor_conv ( ); void operator() ( resizable_tensor& output, const tensor& data, const tensor& filters, int stride_y, int stride_x, int padding_y, int padding_x ); /*! requires - stride_y > 0 - stride_x > 0 - 0 <= padding_y < filters.nr() - 0 <= padding_x < filters.nc() - is_same_object(output,data) == false - is_same_object(output,filters) == false ensures - convolves filters over data. - filters contains filters.num_samples() filters. - #output.num_samples() == data.num_samples() - #output.k() == filters.num_samples() - #output.nr() == 1+(data.nr()-filters.nr()%2)/stride_y - #output.nc() == 1+(data.nc()-filters.nc()%2)/stride_x !*/ void <API key> ( const tensor& gradient_input, const tensor& filters, tensor& data_gradient ); /*! requires - filters has the same dimensions as the filters object give to the last call to operator(). - data_gradient has the same dimensions as the data object give to the last call to operator(). - gradient_input has the same dimensions as the output of operator(). - is_same_object(data_gradient,filters) == false - is_same_object(data_gradient,gradient_input) == false ensures - let OUT be the output of (*this)(OUT,data,filters). - let f(data,filters) == dot(OUT, gradient_input) - This function finds the gradient of f() with respect to data and adds this gradient to data_gradient. !*/ void <API key> ( const tensor& gradient_input, const tensor& data, tensor& filters_gradient ); /*! requires - filters_gradient has the same dimensions as the filters object give to the last call to operator(). - data has the same dimensions as the data object give to the last call to operator(). - gradient_input has the same dimensions as the output of operator(). - is_same_object(filters_gradient,data) == false - is_same_object(filters_gradient,gradient_input) == false ensures - let OUT be the output of (*this)(OUT,data,filters). - let f(data,filters) == dot(OUT, gradient_input) - This function finds the gradient of f() with respect to filters and assigns this gradient to filters_gradient. !*/ private: void setup( const tensor& data, const tensor& filters, int stride_y, int stride_x, int padding_y, int padding_x ); /*! requires - filters.k() == data.k() - stride_y > 0 - stride_x > 0 - 0 <= padding_y < filters.nr() - 0 <= padding_x < filters.nc() !*/ // These variables record the type of data given to the last call to setup(). int stride_y; int stride_x; int padding_y; int padding_x; long data_num_samples, data_k, data_nr, data_nc; long filters_num_samples, filters_k, filters_nr, filters_nc; void* filter_handle; void* conv_handle; // dimensions of the output tensor from operator() int out_num_samples; int out_k; int out_nr; int out_nc; int forward_algo; size_t <API key>; void* forward_workspace; int backward_data_algo; size_t <API key>; void* <API key>; int <API key>; size_t <API key>; void* <API key>; }; class pooling { public: pooling(const pooling&) = delete; pooling& operator=(const pooling&) = delete; pooling ( ); ~pooling( ); void clear( ); void setup_max_pooling( int window_height, int window_width, int stride_y, int stride_x, int padding_y, int padding_x ); void setup_avg_pooling( int window_height, int window_width, int stride_y, int stride_x, int padding_y, int padding_x ); bool does_max_pooling( ) const { return do_max_pooling; } void operator() ( resizable_tensor& dest, const tensor& src ); void get_gradient( const tensor& gradient_input, const tensor& dest, const tensor& src, tensor& grad ); private: void setup( int window_height, int window_width, int stride_y, int stride_x, int padding_y, int padding_x, int pooling_mode ); void* handle; int window_height; int window_width; int stride_y; int stride_x; int padding_y; int padding_x; bool do_max_pooling; }; void softmax ( tensor& dest, const tensor& src ); /*! requires - <API key>(dest, src) == true ensures - Note that the softmax function is a vector valued function: s(x) == exp(x)/sum(exp(x)) - Computes the softmax function on src and writes the results to dest. The softmax is computed per spatial location across the different channels at each location. That is, softmax() outputs a new tensor, #dest, where each of the spatial locations in dest (i.e. image idx, row idx, and column idx) contains the output of s() evaluated over the channel values at each location. - This function supports in-place operation, i.e. having is_same_object(dest, src)==true !*/ void softmax_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ); /*! requires - <API key>(dest,gradient_input) == true - <API key>(dest,grad) == true - is_same_object(grad, dest)==false ensures - We interpret dest as the output of softmax(dest,SRC) for some SRC tensor. Then let f(SRC) == dot(gradient_input,dest) Then this function computes the gradient of f() with respect to SRC and assigns it to grad. - This function supports in-place operation, i.e. having is_same_object(grad, gradient_input)==true !*/ void sigmoid ( tensor& dest, const tensor& src ); /*! requires - <API key>(dest, src) == true ensures - for all valid i: - #dest.host()[i] == 1/(1+std::exp(-src.host()[i])) - This function supports in-place operation, i.e. having is_same_object(dest, src)==true !*/ void sigmoid_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ); /*! requires - <API key>(dest,gradient_input) == true - <API key>(dest,grad) == true - is_same_object(grad,dest) == false ensures - Recalling that dest is the output of sigmoid(dest,SRC) for some SRC tensor, let f(SRC) == dot(gradient_input,dest) - Then this function computes the gradient of f() with respect to SRC and assigns it to grad. - This function supports in-place operation, i.e. having is_same_object(grad, gradient_input)==true !*/ void relu ( tensor& dest, const tensor& src ); /*! requires - <API key>(dest, src) == true ensures - for all valid i: - #dest.host()[i] == std::max(0,src.host()[i]) - This function supports in-place operation, i.e. having is_same_object(dest, src)==true !*/ void relu_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ); /*! requires - <API key>(dest,gradient_input) == true - <API key>(dest,grad) == true - is_same_object(grad,dest) == false ensures - Recalling that dest is the output of relu(dest,SRC) for some SRC tensor, let f(SRC) == dot(gradient_input,dest) - Then this function computes the gradient of f() with respect to SRC and assigns it to grad. - This function supports in-place operation, i.e. having is_same_object(grad, gradient_input)==true !*/ void tanh ( tensor& dest, const tensor& src ); /*! requires - <API key>(dest, src) == true ensures - for all valid i: - #dest.host()[i] == std::tanh(src.host()[i]) - This function supports in-place operation, i.e. having is_same_object(dest, src)==true !*/ void tanh_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ); /*! requires - <API key>(dest,gradient_input) == true - <API key>(dest,grad) == true - is_same_object(grad,dest) == false ensures - Recalling that dest is the output of tanh(dest,SRC) for some SRC tensor, let f(SRC) == dot(gradient_input,dest) - Then this function computes the gradient of f() with respect to SRC and assigns it to grad. - This function supports in-place operation, i.e. having is_same_object(grad, gradient_input)==true !*/ } } #endif // DLIB_USE_CUDA #endif // DLIB_DNN_CuDNN_H_
#pragma once #include "platform/network_policy.hpp" @class NSDate; namespace network_policy { enum Stage { Ask, Always, Never, Today, NotToday }; void SetStage(Stage state); Stage GetStage(); bool CanUseNetwork(); bool IsActivePolicyDate(); NSDate* GetPolicyDate(); } // namespace network_policy
#define <API key> #include "bgp_ip_test.cc" int main(int argc, char **argv) { const char *largv[] = { __FILE__, "--<API key>=inet6", }; return bgp_ip_test_main(sizeof(largv)/sizeof(largv[0]), largv); }
require 'spec_helper' describe 'collectd::plugin::swap', :type => :class do context ':ensure => present, default params' do let :facts do {:osfamily => 'RedHat'} end it 'Will create /etc/collectd.d/10-swap.conf' do should contain_file('swap.load').with({ :ensure => 'present', :path => '/etc/collectd.d/10-swap.conf', :content => /\#\ Generated by Puppet\nLoadPlugin swap\n\n<Plugin swap>\n ReportByDevice false\n<\/Plugin>\n/, }) end end context ':ensure => present, specific params, collectd version 5.0' do let :facts do { :osfamily => 'Redhat', :collectd_version => '5.0' } end it 'Will create /etc/collectd.d/10-swap.conf for collectd < 5.2' do should contain_file('swap.load').with({ :ensure => 'present', :path => '/etc/collectd.d/10-swap.conf', :content => "# Generated by Puppet\nLoadPlugin swap\n\n<Plugin swap>\n ReportByDevice false\n</Plugin>\n", }) end end context ':ensure => present, specific params, collectd version 5.2.0' do let :facts do { :osfamily => 'Redhat', :collectd_version => '5.2.0' } end it 'Will create /etc/collectd.d/10-swap.conf for collectd >= 5.2' do should contain_file('swap.load').with({ :ensure => 'present', :path => '/etc/collectd.d/10-swap.conf', :content => "# Generated by Puppet\nLoadPlugin swap\n\n<Plugin swap>\n ReportByDevice false\n ReportBytes true\n</Plugin>\n", }) end end context ':ensure => absent' do let :facts do {:osfamily => 'RedHat'} end let :params do {:ensure => 'absent'} end it 'Will not create /etc/collectd.d/10-swap.conf' do should contain_file('swap.load').with({ :ensure => 'absent', :path => '/etc/collectd.d/10-swap.conf', }) end end end
#pragma checksum "..\..\App.xaml" "{<API key>}" "<API key>" // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> using Calculator; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Calculator { <summary> App </summary> public partial class App : System.Windows.Application { <summary> InitializeComponent </summary> [System.Diagnostics.<API key>()] [System.CodeDom.Compiler.<API key>("<API key>", "4.0.0.0")] public void InitializeComponent() { #line 5 "..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden } <summary> Application Entry Point. </summary> [System.STAThreadAttribute()] [System.Diagnostics.<API key>()] [System.CodeDom.Compiler.<API key>("<API key>", "4.0.0.0")] public static void Main() { Calculator.App app = new Calculator.App(); app.InitializeComponent(); app.Run(); } } }
using System.ComponentModel.DataAnnotations; using FluentMigrator.Infrastructure; namespace FluentMigrator.Expressions { <summary> Expression to delete a sequence </summary> public class <API key> : <API key>, ISchemaExpression { <inheritdoc /> public virtual string SchemaName { get; set; } <summary> Gets or sets the sequence name </summary> [Required(<API key> = typeof(ErrorMessages), <API key> = nameof(ErrorMessages.<API key>))] public virtual string SequenceName { get; set; } <inheritdoc /> public override void ExecuteWith(IMigrationProcessor processor) { processor.Process(this); } <inheritdoc /> public override string ToString() { return base.ToString() + SequenceName; } } }
"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain.""" import logging from random import randint from typing import Optional from aiopvpc import PVPCData from homeassistant import config_entries from homeassistant.const import CONF_NAME, <API key> from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.aiohttp_client import <API key> from homeassistant.helpers.event import async_call_later, <API key> from homeassistant.helpers.restore_state import RestoreEntity import homeassistant.util.dt as dt_util from .const import ATTR_TARIFF _LOGGER = logging.getLogger(__name__) ATTR_PRICE = "price" ICON = "mdi:currency-eur" UNIT = f"€/{<API key>}" _DEFAULT_TIMEOUT = 10 async def async_setup_entry( hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities ): """Set up the electricity price sensor from config_entry.""" name = config_entry.data[CONF_NAME] pvpc_data_handler = PVPCData( tariff=config_entry.data[ATTR_TARIFF], local_timezone=hass.config.time_zone, websession=<API key>(hass), logger=_LOGGER, timeout=_DEFAULT_TIMEOUT, ) async_add_entities( [ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False ) class ElecPriceSensor(RestoreEntity): """Class to hold the prices of electricity as a sensor.""" unit_of_measurement = UNIT icon = ICON should_poll = False def __init__(self, name, unique_id, pvpc_data_handler): """Initialize the sensor object.""" self._name = name self._unique_id = unique_id self._pvpc_data = pvpc_data_handler self._num_retries = 0 self._hourly_tracker = None self._price_tracker = None async def <API key>(self) -> None: """Cancel listeners for sensor updates.""" self._hourly_tracker() self._price_tracker() async def async_added_to_hass(self): """Handle entity which will be added.""" await super().async_added_to_hass() state = await self.<API key>() if state: self._pvpc_data.state = state.state # Update 'state' value in hour changes self._hourly_tracker = <API key>( self.hass, self.<API key>, second=[0], minute=[0] ) # Update prices at random time, 2 times/hour (don't want to upset API) random_minute = randint(1, 29) mins_update = [random_minute, random_minute + 30] self._price_tracker = <API key>( self.hass, self.async_update_prices, second=[0], minute=mins_update ) _LOGGER.debug( "Setup of price sensor %s (%s) with tariff '%s', " "updating prices each hour at %s min", self.name, self.entity_id, self._pvpc_data.tariff, mins_update, ) await self.async_update_prices(dt_util.utcnow()) self.<API key>(dt_util.utcnow()) @property def unique_id(self) -> Optional[str]: """Return a unique ID.""" return self._unique_id @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._pvpc_data.state @property def available(self) -> bool: """Return True if entity is available.""" return self._pvpc_data.state_available @property def <API key>(self): """Return the state attributes.""" return self._pvpc_data.attributes @callback def <API key>(self, now): """Update the sensor state, by selecting the current price for this hour.""" self._pvpc_data.<API key>(now) self.<API key>() async def async_update_prices(self, now): """Update electricity prices from the ESIOS API.""" prices = await self._pvpc_data.async_update_prices(now) if not prices and self._pvpc_data.source_available: self._num_retries += 1 if self._num_retries > 2: _LOGGER.warning( "%s: repeated bad data update, mark component as unavailable source", self.entity_id, ) self._pvpc_data.source_available = False return retry_delay = 2 * self._num_retries * self._pvpc_data.timeout _LOGGER.debug( "%s: Bad update[retry:%d], will try again in %d s", self.entity_id, self._num_retries, retry_delay, ) async_call_later(self.hass, retry_delay, self.async_update_prices) return if not prices: _LOGGER.debug("%s: data source is not yet available", self.entity_id) return self._num_retries = 0 if not self._pvpc_data.source_available: self._pvpc_data.source_available = True _LOGGER.warning("%s: component has recovered data access", self.entity_id) self.<API key>(now)
package com.opengamma.financial.analytics.model.sabrcube; import static com.opengamma.engine.value.<API key>.SABR_SURFACES; import com.opengamma.<API key>; import com.opengamma.analytics.financial.interestrate.<API key>; import com.opengamma.analytics.financial.interestrate.<API key>; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.model.option.definition.<API key>; import com.opengamma.analytics.financial.model.option.definition.<API key>; import com.opengamma.analytics.math.function.DoubleFunction1D; import com.opengamma.analytics.math.surface.<API key>; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.<API key>; import com.opengamma.engine.value.<API key>; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.financial.analytics.model.sabr.<API key>; import com.opengamma.financial.analytics.model.volatility.<API key>; import com.opengamma.financial.analytics.volatility.fittedresults.SABRFittedSurfaces; import com.opengamma.financial.security.<API key>; import com.opengamma.financial.security.<API key>; import com.opengamma.util.money.Currency; /** * @deprecated Use descendants of {@link <API key>} */ @Deprecated public class <API key> extends SABRYCNSFunction { private static final <API key> NSC = <API key>.using(<API key>.getInstance()); @Override public <API key> getTargetType() { return <API key>.<API key>; } @Override protected <API key> getModelParameters(final ComputationTarget target, final FunctionInputs inputs, final Currency currency, final YieldCurveBundle yieldCurves, final ValueRequirement desiredValue) { final Object surfacesObject = inputs.getValue(SABR_SURFACES); if (surfacesObject == null) { throw new <API key>("Could not get SABR parameter surfaces"); } final SABRFittedSurfaces surfaces = (SABRFittedSurfaces) surfacesObject; final <API key> alphaSurface = surfaces.getAlphaSurface(); final <API key> betaSurface = surfaces.getBetaSurface(); final <API key> nuSurface = surfaces.getNuSurface(); final <API key> rhoSurface = surfaces.getRhoSurface(); final DoubleFunction1D correlationFunction = <API key>(); final <API key> modelParameters = new <API key>(alphaSurface, betaSurface, rhoSurface, nuSurface, correlationFunction); return new <API key>(modelParameters, yieldCurves); } @Override protected ValueProperties.Builder <API key>(final Currency currency) { return <API key>() .with(ValuePropertyNames.CURRENCY, currency.getCode()) .with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode()) .withAny(ValuePropertyNames.<API key>) .withAny(ValuePropertyNames.CURVE) .withAny(<API key>.<API key>) .withAny(<API key>.<API key>) .withAny(<API key>.<API key>) .withAny(<API key>.<API key>) .withAny(<API key>.<API key>) .with(<API key>.<API key>, <API key>.SABR) .with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.<API key>); } @Override protected ValueProperties.Builder <API key>(final ComputationTarget target, final ValueRequirement desiredValue) { final String cubeDefinitionName = desiredValue.getConstraint(<API key>.<API key>); final String <API key> = desiredValue.getConstraint(<API key>.<API key>); final String <API key> = desiredValue.getConstraint(<API key>.<API key>); final String <API key> = desiredValue.getConstraint(<API key>.<API key>); final String currency = <API key>.getCurrency(target.getSecurity()).getCode(); final String <API key> = desiredValue.getConstraint(ValuePropertyNames.<API key>); final String fittingMethod = desiredValue.getConstraint(<API key>.<API key>); final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE); return <API key>() .with(ValuePropertyNames.CURRENCY, currency) .with(ValuePropertyNames.CURVE_CURRENCY, currency) .with(ValuePropertyNames.<API key>, <API key>) .with(ValuePropertyNames.CURVE, curveName) .with(<API key>.<API key>, cubeDefinitionName) .with(<API key>.<API key>, <API key>) .with(<API key>.<API key>, <API key>) .with(<API key>.<API key>, <API key>) .with(<API key>.<API key>, fittingMethod) .with(<API key>.<API key>, <API key>.SABR) .with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.<API key>); } @Override protected <API key> <API key>(final ValueRequirement desiredValue) { return NSC; } private static DoubleFunction1D <API key>() { return new DoubleFunction1D() { @Override public Double evaluate(final Double x) { return 0.8; } }; } }
// This may look like C code, but it's really -*- C++ -*- #ifndef <API key> #define <API key> #include <Wt/Dbo/Session> #include <Wt/Dbo/Exception> #include <Wt/Dbo/SqlStatement> #include <Wt/Dbo/SqlTraits> #include <Wt/Dbo/DbAction> namespace Wt { namespace Dbo { template <typename V> FieldRef<V>::FieldRef(V& value, const std::string& name, int size) : value_(value), name_(name), size_(size) { } template <typename V> const std::string& FieldRef<V>::name() const { return name_; } template <typename V> int FieldRef<V>::size() const { return size_; } template <typename V> std::string FieldRef<V>::sqlType(Session& session) const { return sql_value_traits<V>::type(session.connection(false), size_); } template <typename V> const std::type_info *FieldRef<V>::type() const { return &typeid(V); } template <typename V> void FieldRef<V>::bindValue(SqlStatement *statement, int column) const { sql_value_traits<V>::bind(value_, statement, column, size_); } template <typename V> void FieldRef<V>::setValue(Session& session, SqlStatement *statement, int column) const { sql_value_traits<V>::read(value_, statement, column, size_); } template <class C> CollectionRef<C>::CollectionRef(collection< ptr<C> >& value, RelationType type, const std::string& joinName, const std::string& joinId, int fkConstraints) : value_(value), joinName_(joinName), joinId_(joinId), type_(type), fkConstraints_(fkConstraints) { } template <class C> PtrRef<C>::PtrRef(ptr<C>& value, const std::string& name, int size, int fkConstraints) : value_(value), name_(name), size_(size), fkConstraints_(fkConstraints) { } template <class C, class A, class Enable = void> struct LoadLazyHelper { static void loadLazy(ptr<C>& p, typename dbo_traits<C>::IdType id, Session *session) { } }; template <class C, class A> struct LoadLazyHelper<C, A, typename boost::enable_if<action_sets_value<A> >::type> { static void loadLazy(ptr<C>& p, typename dbo_traits<C>::IdType id, Session *session) { if (!(id == dbo_traits<C>::invalidId())) { if (session) p = session->loadLazy<C>(id); else throw Exception("Could not load referenced Dbo::ptr, no session?"); } } }; template <class C> template <class A> void PtrRef<C>::visit(A& action, Session *session) const { typename dbo_traits<C>::IdType id; if (action.setsValue()) id = dbo_traits<C>::invalidId(); else id = value_.id(); std::string idFieldName = "stub"; int size = size_; if (session) { Impl::MappingInfo *mapping = session->getMapping<C>(); action.actMapping(mapping); idFieldName = mapping->naturalIdFieldName; size = mapping->naturalIdFieldSize; if (idFieldName.empty()) idFieldName = mapping-><API key>; } field(action, id, name_ + "_" + idFieldName, size); LoadLazyHelper<C, A>::loadLazy(value_, id, session); } template <class C> WeakPtrRef<C>::WeakPtrRef(weak_ptr<C>& value, const std::string& joinName) : value_(value), joinName_(joinName) { } template <class C> const std::type_info *PtrRef<C>::type() const { return &typeid(typename dbo_traits<C>::IdType); } template <class A, typename V> void id(A& action, V& value, const std::string& name, int size) { action.actId(value, name, size); } template <class A, class C> void id(A& action, ptr<C>& value, const std::string& name, <API key> constraint, int size) { action.actId(value, name, size, constraint.value()); } template <class A, typename V> void field(A& action, V& value, const std::string& name, int size) { action.act(FieldRef<V>(value, name, size)); } template <class A, class C> void field(A& action, ptr<C>& value, const std::string& name, int size) { action.actPtr(PtrRef<C>(value, name, size, 0)); } template <class A, class C> void belongsToImpl(A& action, ptr<C>& value, const std::string& name, int fkConstraints, int size) { if (name.empty() && action.session()) action.actPtr(PtrRef<C>(value, action.session()->template tableName<C>(), size, fkConstraints)); else action.actPtr(PtrRef<C>(value, name, size, fkConstraints)); } template <class A, class C> void belongsTo(A& action, ptr<C>& value, const std::string& name, int size) { belongsToImpl(action, value, name, 0, size); } template <class A, class C> void belongsTo(A& action, ptr<C>& value, const std::string& name, <API key> constraint, int size) { belongsToImpl(action, value, name, constraint.value(), size); } template <class A, class C> void belongsTo(A& action, ptr<C>& value, <API key> constraint, int size) { belongsToImpl(action, value, std::string(), constraint.value(), size); } template <class A, class C> void hasOne(A& action, weak_ptr<C>& value, const std::string& joinName) { action.actWeakPtr(WeakPtrRef<C>(value, joinName)); } template <class A, class C> void hasMany(A& action, collection< ptr<C> >& value, RelationType type, const std::string& joinName) { action.actCollection(CollectionRef<C>(value, type, joinName, std::string(), Impl::FKNotNull | Impl::FKOnDeleteCascade)); } template <class A, class C> void hasMany(A& action, collection< ptr<C> >& value, RelationType type, const std::string& joinName, const std::string& joinId, <API key> constraint) { if (type != ManyToMany) throw Exception("hasMany() with named joinId only for a ManyToMany relation"); action.actCollection(CollectionRef<C>(value, type, joinName, joinId, constraint.value())); } } } #endif // <API key>
<reference path='fourslash.ts' /> // @allowjs: true // @checkJs: true // @noEmit: true // @filename: a.js /// @ts-check /let x = ""; /[|x|] = 1; // verify.codeFixAvailable([ // { description: ts.Diagnostics.<API key>.message }, // { description: ts.Diagnostics.<API key>.message } verify.codeFix({ description: ts.Diagnostics.<API key>.message, index: 1, newFileContent: `// @ts-nocheck let x = ""; x = 1;`, });
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class SourceSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public SourceSpec(ITestOutputHelper helper) : base(helper) { Materializer = ActorMaterializer.Create(Sys); } [Fact] public void <API key>() { var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer); var c = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c); var sub = c.ExpectSubscription(); sub.Request(1); c.ExpectNext(1); c.ExpectComplete(); } [Fact] public void <API key>() { var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer); var c1 = TestSubscriber.CreateManualProbe<int>(this); var c2 = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c1); var sub1 = c1.ExpectSubscription(); sub1.Request(1); c1.ExpectNext(1); c1.ExpectComplete(); p.Subscribe(c2); c2.<API key>(); } [Fact] public void <API key>() { var p = Source.Empty<int>().RunWith(Sink.AsPublisher<int>(false), Materializer); var c = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c); c.<API key>(); //reject additional subscriber var c2 = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c2); c2.<API key>(); } [Fact] public void <API key>() { var ex = new SystemException(); var p = Source.Failed<int>(ex).RunWith(Sink.AsPublisher<int>(false), Materializer); var c = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c); c.<API key>(); //reject additional subscriber var c2 = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c2); c2.<API key>(); } [Fact] public void <API key>() { this.<API key>(() => { var neverSource = Source.Maybe<object>(); var pubSink = Sink.AsPublisher<object>(false); var t = neverSource.ToMaterialized(pubSink, Keep.Both).Run(Materializer); var f = t.Item1; var neverPub = t.Item2; var c = TestSubscriber.CreateManualProbe<object>(this); neverPub.Subscribe(c); var subs = c.ExpectSubscription(); subs.Request(1000); c.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); subs.Cancel(); f.Task.Wait(500).Should().BeTrue(); f.Task.Result.Should().Be(null); }, Materializer); } [Fact] public void <API key>() { this.<API key>(() => { var neverSource = Source.Maybe<int>().Where(_ => false); var counterSink = Sink.Aggregate<int, int>(0, (acc, _) => acc + 1); var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer); var neverPromise = t.Item1; var counterFuture = t.Item2; //external cancellation neverPromise.TrySetResult(0).Should().BeTrue(); counterFuture.Wait(500).Should().BeTrue(); counterFuture.Result.Should().Be(0); }, Materializer); } [Fact] public void <API key>() { this.<API key>(() => { var neverSource = Source.Maybe<int>(); var counterSink = Sink.First<int>(); var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer); var neverPromise = t.Item1; var counterFuture = t.Item2; //external cancellation neverPromise.TrySetResult(6).Should().BeTrue(); counterFuture.Wait(500).Should().BeTrue(); counterFuture.Result.Should().Be(6); }, Materializer); } [Fact] public void <API key>() { this.<API key>(() => { var neverSource = Source.Maybe<int>(); var counterSink = Sink.First<int>(); var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer); var neverPromise = t.Item1; var counterFuture = t.Item2; //external cancellation neverPromise.SetException(new Exception("Boom")); counterFuture.Invoking(f => f.Wait(500)).ShouldThrow<Exception>() .WithMessage("Boom"); }, Materializer); } [Fact] public void <API key>() { var probes = Enumerable.Range(1, 5).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList(); var source = Source.AsSubscriber<int>(); var outProbe = TestSubscriber.CreateManualProbe<int>(this); var s = Source.FromGraph(GraphDsl.Create(source, source, source, source, source, (a, b, c, d, e) => new[] {a, b, c, d, e}, (b, i0, i1, i2, i3, i4) => { var m = b.Add(new Merge<int>(5)); b.From(i0.Outlet).To(m.In(0)); b.From(i1.Outlet).To(m.In(1)); b.From(i2.Outlet).To(m.In(2)); b.From(i3.Outlet).To(m.In(3)); b.From(i4.Outlet).To(m.In(4)); return new SourceShape<int>(m.Out); })).To(Sink.FromSubscriber(outProbe)).Run(Materializer); for (var i = 0; i < 5; i++) probes[i].Subscribe(s[i]); var sub = outProbe.ExpectSubscription(); sub.Request(10); for (var i = 0; i < 5; i++) { var subscription = probes[i].ExpectSubscription(); subscription.ExpectRequest(); subscription.SendNext(i); subscription.SendComplete(); } var gotten = new List<int>(); for (var i = 0; i < 5; i++) gotten.Add(outProbe.ExpectNext()); gotten.<API key>(new[] {0, 1, 2, 3, 4}); outProbe.ExpectComplete(); } [Fact] public void <API key>() { var probes = Enumerable.Range(1, 3).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList(); var source = probes.Select(Source.FromPublisher).ToList(); var outProbe = TestSubscriber.CreateManualProbe<int>(this); Source.Combine(source[0], source[1], i => new Merge<int, int>(i), source[2]) .To(Sink.FromSubscriber(outProbe)) .Run(Materializer); var sub = outProbe.ExpectSubscription(); sub.Request(3); for (var i = 0; i < 3; i++) { var s = probes[i].ExpectSubscription(); s.ExpectRequest(); s.SendNext(i); s.SendComplete(); } var gotten = new List<int>(); for (var i = 0; i < 3; i++) gotten.Add(outProbe.ExpectNext()); gotten.<API key>(new[] {0, 1, 2}); outProbe.ExpectComplete(); } [Fact] public void <API key>() { var probes = Enumerable.Range(1, 2).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList(); var source = probes.Select(Source.FromPublisher).ToList(); var outProbe = TestSubscriber.CreateManualProbe<int>(this); Source.Combine(source[0], source[1], i => new Merge<int, int>(i)) .To(Sink.FromSubscriber(outProbe)) .Run(Materializer); var sub = outProbe.ExpectSubscription(); sub.Request(3); for (var i = 0; i < 2; i++) { var s = probes[i].ExpectSubscription(); s.ExpectRequest(); s.SendNext(i); s.SendComplete(); } var gotten = new List<int>(); for (var i = 0; i < 2; i++) gotten.Add(outProbe.ExpectNext()); gotten.<API key>(new[] {0, 1}); outProbe.ExpectComplete(); } [Fact] public void <API key>() { var f = Source.Repeat(42).Grouped(1000).RunWith(Sink.First<IEnumerable<int>>(), Materializer); f.Result.Should().HaveCount(1000).And.Match(x => x.All(i => i == 42)); } private static readonly int[] Expected = { 9227465, 5702887, 3524578, 2178309, 1346269, 832040, 514229, 317811, 196418, 121393, 75025, 46368, 28657, 17711, 10946, 6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0 }; [Fact] public void <API key>() { Source.Unfold(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; if (a > 10000000) return null; return Tuple.Create(Tuple.Create(b, a + b), a); }).RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer).Result.Should().Equal(Expected); } [Fact] public void <API key>() { EventFilter.Exception<SystemException>(message: "expected").ExpectOne(() => { var task = Source.Unfold(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; if (a > 10000000) throw new SystemException("expected"); return Tuple.Create(Tuple.Create(b, a + b), a); }).RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<SystemException>() .WithMessage("expected"); }); } [Fact] public void <API key>() { Source.UnfoldAsync(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; if (a > 10000000) return Task.FromResult<Tuple<Tuple<int, int>, int>>(null); return Task.FromResult(Tuple.Create(Tuple.Create(b, a + b), a)); }).RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer).Result.Should().Equal(Expected); } [Fact] public void <API key>() { Source.Unfold(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; return Tuple.Create(Tuple.Create(b, a + b), a); }) .Take(36) .RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer).Result.Should().Equal(Expected); } [Fact] public void <API key>() { var expected = new[] {false, true, false, true, false, true, false, true, false, true }.ToList(); Source.FromEnumerator(() => expected.GetEnumerator()) .Grouped(10) .RunWith(Sink.First<IEnumerable<bool>>(), Materializer) .Result.Should() .Equal(expected); } [Fact] public void <API key>() { Source.Single(42).Async().AddAttributes(Attributes.None).Named(""); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Protos.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Messages { <summary>Holder for reflection information generated from Protos.proto</summary> public static partial class ProtosReflection { #region Descriptor <summary>File descriptor for Protos.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ProtosReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "<API key>", "<API key>", "<API key>=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::<API key>(null, new pbr::<API key>[] { new pbr::<API key>(typeof(global::Messages.RenameCommand), global::Messages.RenameCommand.Parser, new[]{ "Name" }, null, null, null), new pbr::<API key>(typeof(global::Messages.RenameEvent), global::Messages.RenameEvent.Parser, new[]{ "Name" }, null, null, null), new pbr::<API key>(typeof(global::Messages.State), global::Messages.State.Parser, new[]{ "Name" }, null, null, null) })); } #endregion } #region Messages public sealed partial class RenameCommand : pb::IMessage<RenameCommand> { private static readonly pb::MessageParser<RenameCommand> _parser = new pb::MessageParser<RenameCommand>(() => new RenameCommand()); [global::System.Diagnostics.<API key>] public static pb::MessageParser<RenameCommand> Parser { get { return _parser; } } [global::System.Diagnostics.<API key>] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.<API key>] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.<API key>] public RenameCommand() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.<API key>] public RenameCommand(RenameCommand other) : this() { name_ = other.name_; } [global::System.Diagnostics.<API key>] public RenameCommand Clone() { return new RenameCommand(this); } <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.<API key>] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.<API key>] public override bool Equals(object other) { return Equals(other as RenameCommand); } [global::System.Diagnostics.<API key>] public bool Equals(RenameCommand other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.<API key>] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.<API key>] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.<API key>] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.<API key>] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.<API key>] public void MergeFrom(RenameCommand other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.<API key>] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } public sealed partial class RenameEvent : pb::IMessage<RenameEvent> { private static readonly pb::MessageParser<RenameEvent> _parser = new pb::MessageParser<RenameEvent>(() => new RenameEvent()); [global::System.Diagnostics.<API key>] public static pb::MessageParser<RenameEvent> Parser { get { return _parser; } } [global::System.Diagnostics.<API key>] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.<API key>] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.<API key>] public RenameEvent() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.<API key>] public RenameEvent(RenameEvent other) : this() { name_ = other.name_; } [global::System.Diagnostics.<API key>] public RenameEvent Clone() { return new RenameEvent(this); } <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.<API key>] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.<API key>] public override bool Equals(object other) { return Equals(other as RenameEvent); } [global::System.Diagnostics.<API key>] public bool Equals(RenameEvent other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.<API key>] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.<API key>] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.<API key>] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.<API key>] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.<API key>] public void MergeFrom(RenameEvent other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.<API key>] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } public sealed partial class State : pb::IMessage<State> { private static readonly pb::MessageParser<State> _parser = new pb::MessageParser<State>(() => new State()); [global::System.Diagnostics.<API key>] public static pb::MessageParser<State> Parser { get { return _parser; } } [global::System.Diagnostics.<API key>] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.<API key>] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.<API key>] public State() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.<API key>] public State(State other) : this() { name_ = other.name_; } [global::System.Diagnostics.<API key>] public State Clone() { return new State(this); } <summary>Field number for the "Name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.<API key>] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.<API key>] public override bool Equals(object other) { return Equals(other as State); } [global::System.Diagnostics.<API key>] public bool Equals(State other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.<API key>] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.<API key>] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.<API key>] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.<API key>] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.<API key>] public void MergeFrom(State other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.<API key>] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
/** * @file * Point To Point Protocol Sequential API module * */ #include "lwip/opt.h" #if LWIP_PPP_API /* don't build if not configured for use in lwipopts.h */ #include "lwip/pppapi.h" #include "lwip/priv/tcpip_priv.h" #include "netif/ppp/pppoe.h" #include "netif/ppp/pppol2tp.h" #include "netif/ppp/pppos.h" /** * Call ppp_set_default() inside the tcpip_thread context. */ static err_t <API key>(struct tcpip_api_call *m) { struct pppapi_msg_msg *msg = (struct pppapi_msg_msg *)m; ppp_set_default(msg->ppp); return ERR_OK; } /** * Call ppp_set_default() in a thread-safe way by running that function inside the * tcpip_thread context. */ void pppapi_set_default(ppp_pcb *pcb) { struct pppapi_msg msg; msg.msg.ppp = pcb; tcpip_api_call(<API key>, &msg.call); } /** * Call ppp_set_auth() inside the tcpip_thread context. */ static err_t <API key>(struct tcpip_api_call *m) { struct pppapi_msg *msg = (struct pppapi_msg *)m; ppp_set_auth(msg->msg.ppp, msg->msg.msg.setauth.authtype, msg->msg.msg.setauth.user, msg->msg.msg.setauth.passwd); return ERR_OK; } /** * Call ppp_set_auth() in a thread-safe way by running that function inside the * tcpip_thread context. */ void pppapi_set_auth(ppp_pcb *pcb, u8_t authtype, const char *user, const char *passwd) { struct pppapi_msg msg; msg.msg.ppp = pcb; msg.msg.msg.setauth.authtype = authtype; msg.msg.msg.setauth.user = user; msg.msg.msg.setauth.passwd = passwd; tcpip_api_call(<API key>, &msg.call); } #if PPP_NOTIFY_PHASE /** * Call <API key>() inside the tcpip_thread context. */ static err_t <API key>(struct tcpip_api_call *m) { struct pppapi_msg_msg *msg = (struct pppapi_msg_msg *)m; <API key>(msg->ppp, msg->msg.setnotifyphasecb.notify_phase_cb); return ERR_OK; } /** * Call <API key>() in a thread-safe way by running that function inside the * tcpip_thread context. */ void <API key>(ppp_pcb *pcb, <API key> notify_phase_cb) { struct pppapi_msg msg; msg.function = <API key>; msg.msg.ppp = pcb; msg.msg.msg.setnotifyphasecb.notify_phase_cb = notify_phase_cb; tcpip_api_call(<API key>, &msg.call); } #endif /* PPP_NOTIFY_PHASE */ #if PPPOS_SUPPORT /** * Call pppos_create() inside the tcpip_thread context. */ static err_t <API key>(struct tcpip_api_call *m) { struct pppapi_msg *msg = (struct pppapi_msg *)(m); msg->msg.ppp = pppos_create(msg->msg.msg.serialcreate.pppif, msg->msg.msg.serialcreate.output_cb, msg->msg.msg.serialcreate.link_status_cb, msg->msg.msg.serialcreate.ctx_cb); return ERR_OK; } /** * Call pppos_create() in a thread-safe way by running that function inside the * tcpip_thread context. */ ppp_pcb* pppapi_pppos_create(struct netif *pppif, pppos_output_cb_fn output_cb, <API key> link_status_cb, void *ctx_cb) { struct pppapi_msg msg; msg.msg.msg.serialcreate.pppif = pppif; msg.msg.msg.serialcreate.output_cb = output_cb; msg.msg.msg.serialcreate.link_status_cb = link_status_cb; msg.msg.msg.serialcreate.ctx_cb = ctx_cb; tcpip_api_call(<API key>, &msg.call); return msg.msg.ppp; } #endif /* PPPOS_SUPPORT */ #if PPPOE_SUPPORT /** * Call pppoe_create() inside the tcpip_thread context. */ static err_t <API key>(struct tcpip_api_call *m) { struct pppapi_msg_msg *msg = (struct pppapi_msg_msg *)m; msg->ppp = pppoe_create(msg->msg.ethernetcreate.pppif, msg->msg.ethernetcreate.ethif, msg->msg.ethernetcreate.service_name, msg->msg.ethernetcreate.concentrator_name, msg->msg.ethernetcreate.link_status_cb, msg->msg.ethernetcreate.ctx_cb); return ERR_OK; } /** * Call pppoe_create() in a thread-safe way by running that function inside the * tcpip_thread context. */ ppp_pcb* pppapi_pppoe_create(struct netif *pppif, struct netif *ethif, const char *service_name, const char *concentrator_name, <API key> link_status_cb, void *ctx_cb) { struct pppapi_msg msg; msg.msg.msg.ethernetcreate.pppif = pppif; msg.msg.msg.ethernetcreate.ethif = ethif; msg.msg.msg.ethernetcreate.service_name = service_name; msg.msg.msg.ethernetcreate.concentrator_name = concentrator_name; msg.msg.msg.ethernetcreate.link_status_cb = link_status_cb; msg.msg.msg.ethernetcreate.ctx_cb = ctx_cb; tcpip_api_call(<API key>, &msg.call); return msg.msg.ppp; } #endif /* PPPOE_SUPPORT */ #if PPPOL2TP_SUPPORT /** * Call pppol2tp_create() inside the tcpip_thread context. */ static err_t <API key>(struct tcpip_api_call *m) { struct pppapi_msg_msg *msg = (struct pppapi_msg_msg *)m; msg->ppp = pppol2tp_create(msg->msg.l2tpcreate.pppif, msg->msg.l2tpcreate.netif, msg->msg.l2tpcreate.ipaddr, msg->msg.l2tpcreate.port, #if <API key> msg->msg.l2tpcreate.secret, msg->msg.l2tpcreate.secret_len, #else /* <API key> */ NULL, #endif /* <API key> */ msg->msg.l2tpcreate.link_status_cb, msg->msg.l2tpcreate.ctx_cb); return ERR_OK; } /** * Call pppol2tp_create() in a thread-safe way by running that function inside the * tcpip_thread context. */ ppp_pcb* <API key>(struct netif *pppif, struct netif *netif, ip_addr_t *ipaddr, u16_t port, const u8_t *secret, u8_t secret_len, <API key> link_status_cb, void *ctx_cb) { struct pppapi_msg msg; msg.msg.msg.l2tpcreate.pppif = pppif; msg.msg.msg.l2tpcreate.netif = netif; msg.msg.msg.l2tpcreate.ipaddr = ipaddr; msg.msg.msg.l2tpcreate.port = port; #if <API key> msg.msg.msg.l2tpcreate.secret = secret; msg.msg.msg.l2tpcreate.secret_len = secret_len; #endif /* <API key> */ msg.msg.msg.l2tpcreate.link_status_cb = link_status_cb; msg.msg.msg.l2tpcreate.ctx_cb = ctx_cb; tcpip_api_call(<API key>, &msg.call); return msg.msg.ppp; } #endif /* PPPOL2TP_SUPPORT */ /** * Call ppp_connect() inside the tcpip_thread context. */ static err_t <API key>(struct tcpip_api_call *m) { struct pppapi_msg *msg = (struct pppapi_msg *)m; return ppp_connect(msg->msg.ppp, msg->msg.msg.connect.holdoff); } /** * Call ppp_connect() in a thread-safe way by running that function inside the * tcpip_thread context. */ err_t pppapi_connect(ppp_pcb *pcb, u16_t holdoff) { struct pppapi_msg msg; msg.msg.ppp = pcb; msg.msg.msg.connect.holdoff = holdoff; return tcpip_api_call(<API key>, &msg.call); } #if PPP_SERVER /** * Call ppp_listen() inside the tcpip_thread context. */ static void <API key>(struct pppapi_msg_msg *msg) { msg->err = ppp_listen(msg->ppp, msg->msg.listen.addrs); TCPIP_PPPAPI_ACK(msg); } /** * Call ppp_listen() in a thread-safe way by running that function inside the * tcpip_thread context. */ err_t pppapi_listen(ppp_pcb *pcb, struct ppp_addrs *addrs) { struct pppapi_msg msg; msg.function = <API key>; msg.msg.ppp = pcb; msg.msg.msg.listen.addrs = addrs; TCPIP_PPPAPI(&msg); return msg.msg.err; } #endif /* PPP_SERVER */ /** * Call ppp_close() inside the tcpip_thread context. */ static err_t pppapi_do_ppp_close(struct tcpip_api_call *m) { struct pppapi_msg *msg = (struct pppapi_msg *)m; return ppp_close(msg->msg.ppp, msg->msg.msg.close.nocarrier); } /** * Call ppp_close() in a thread-safe way by running that function inside the * tcpip_thread context. */ err_t pppapi_close(ppp_pcb *pcb, u8_t nocarrier) { struct pppapi_msg msg; msg.msg.ppp = pcb; msg.msg.msg.close.nocarrier = nocarrier; return tcpip_api_call(pppapi_do_ppp_close, &msg.call); } /** * Call ppp_free() inside the tcpip_thread context. */ static err_t pppapi_do_ppp_free(struct tcpip_api_call *m) { struct pppapi_msg_msg *msg = (struct pppapi_msg_msg *)m; return ppp_free(msg->ppp); } /** * Call ppp_free() in a thread-safe way by running that function inside the * tcpip_thread context. */ err_t pppapi_free(ppp_pcb *pcb) { struct pppapi_msg msg; msg.msg.ppp = pcb; return tcpip_api_call(pppapi_do_ppp_free, &msg.call); } /** * Call ppp_ioctl() inside the tcpip_thread context. */ static err_t pppapi_do_ppp_ioctl(struct tcpip_api_call *m) { struct pppapi_msg *msg = (struct pppapi_msg *)m; return ppp_ioctl(msg->msg.ppp, msg->msg.msg.ioctl.cmd, msg->msg.msg.ioctl.arg); } /** * Call ppp_ioctl() in a thread-safe way by running that function inside the * tcpip_thread context. */ err_t pppapi_ioctl(ppp_pcb *pcb, u8_t cmd, void *arg) { struct pppapi_msg msg; msg.msg.ppp = pcb; msg.msg.msg.ioctl.cmd = cmd; msg.msg.msg.ioctl.arg = arg; return tcpip_api_call(pppapi_do_ppp_ioctl, &msg.call); } #endif /* LWIP_PPP_API */
<?php /** * ALIPAY API: alipay.eco.mycar.parking.lotbarcode.create request * * @author auto create * @since 1.0, 2016-06-14 15:08:52 */ class <API key> { private $bizContent; private $apiParas = array(); private $terminalType; private $terminalInfo; private $prodCode; private $apiVersion="1.0"; private $notifyUrl; private $returnUrl; private $needEncrypt=false; public function setBizContent($bizContent) { $this->bizContent = $bizContent; $this->apiParas["biz_content"] = $bizContent; } public function getBizContent() { return $this->bizContent; } public function getApiMethodName() { return "alipay.eco.mycar.parking.lotbarcode.create"; } public function setNotifyUrl($notifyUrl) { $this->notifyUrl=$notifyUrl; } public function getNotifyUrl() { return $this->notifyUrl; } public function setReturnUrl($returnUrl) { $this->returnUrl=$returnUrl; } public function getReturnUrl() { return $this->returnUrl; } public function getApiParas() { return $this->apiParas; } public function getTerminalType() { return $this->terminalType; } public function setTerminalType($terminalType) { $this->terminalType = $terminalType; } public function getTerminalInfo() { return $this->terminalInfo; } public function setTerminalInfo($terminalInfo) { $this->terminalInfo = $terminalInfo; } public function getProdCode() { return $this->prodCode; } public function setProdCode($prodCode) { $this->prodCode = $prodCode; } public function setApiVersion($apiVersion) { $this->apiVersion=$apiVersion; } public function getApiVersion() { return $this->apiVersion; } public function setNeedEncrypt($needEncrypt) { $this->needEncrypt=$needEncrypt; } public function getNeedEncrypt() { return $this->needEncrypt; } }
package com.github.dockerjava.core.command; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.Map; import org.apache.commons.lang.builder.<API key>; import org.apache.commons.lang.builder.ToStringStyle; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; import com.github.dockerjava.core.util.FiltersBuilder; /** * List images */ public class ListImagesCmdImpl extends AbstrDockerCmd<ListImagesCmd, List<Image>> implements ListImagesCmd { private String imageNameFilter; private Boolean showAll = false; private FiltersBuilder filters = new FiltersBuilder(); public ListImagesCmdImpl(ListImagesCmd.Exec exec) { super(exec); } @Override public Map<String, List<String>> getFilters() { return filters.build(); } @Override public Boolean hasShowAllEnabled() { return showAll; } @Override public ListImagesCmd withShowAll(Boolean showAll) { this.showAll = showAll; return this; } @Override public ListImagesCmd withDanglingFilter(Boolean dangling) { checkNotNull(dangling, "dangling have not been specified"); filters.withFilter("dangling", dangling.toString()); return this; } @Override public ListImagesCmd withLabelFilter(String... labels) { checkNotNull(labels, "labels have not been specified"); filters.withLabels(labels); return this; } @Override public ListImagesCmd withLabelFilter(Map<String, String> labels) { checkNotNull(labels, "labels have not been specified"); filters.withLabels(labels); return this; } @Override public ListImagesCmd withImageNameFilter(String imageNameFilter) { checkNotNull(imageNameFilter, "image name filter not specified"); this.imageNameFilter = imageNameFilter; return this; } @Override public String getImageNameFilter() { return this.imageNameFilter; } @Override public String toString() { return <API key>.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
#ifndef <API key> #define <API key> #include "core/workers/<API key>.h" #include "wtf/Noncopyable.h" #include "wtf/PassOwnPtr.h" #include "wtf/PassRefPtr.h" namespace blink { class <API key>; class <API key> final : public <API key> { <API key>(<API key>); public: static PassOwnPtr<<API key>> create(<API key>* client) { return adoptPtr(new <API key>(client)); } ~<API key>() override { } void connect(<API key><SharedWorker>, PassOwnPtr<<API key>>, const KURL&, const String& name, ExceptionState&) override; void documentDetached(Document*) override; private: explicit <API key>(<API key>*); <API key>* m_client; }; } // namespace blink #endif // <API key>
/** * Number.NEGATIVE_INFINITY is -Infinity * * @path ch15/15.7/15.7.3/15.7.3.5/S15.7.3.5_A1.js * @description Checking sign and finiteness of Number.NEGATIVE_INFINITY */ // CHECK if (isFinite(Number.NEGATIVE_INFINITY) !== false) { $ERROR(' } else { if ((Number.NEGATIVE_INFINITY < 0) !== true) { $ERROR(' } }
# Fur material # Using the fur material The fur material needs a high number of the triangular facets that make up a mesh to work well. The number of facets needed also depends on the size of the mesh. Example that seem to work for ground and sphere are: var ground = BABYLON.Mesh.CreateGround("ground", 8, 8, 200, scene); var sphere = BABYLON.Mesh.CreateSphere("sphere", 500, 8, scene); The fur material is created using var furMaterial = new BABYLON.FurMaterial("fur_material", scene); ground.material = furMaterial; # Customize the fur material You can customise three properties of the fur material: furMaterial.furLength = 3; // Represents the maximum length of the fur, which is then adjusted randomly. Default value is 1. furMaterial.furAngle = Math.PI/6; // Represents the angle the fur lies on the mesh from 0 to Math.PI/2. The default angle of 0 gives fur sticking straight up and PI/2 lies along the mesh. furMaterial.furColor = new BABYLON.Color3(0.44, 0.21, 0.02); // is the default color if furColor is not set. # Using textures ##heightTexture A greyscale image can be used to set the fur length. A speckled greyscale image can produce fur like results. Any greyscale image with affect the fur length producing a heightMap type effect. furMaterial.heightTexture = new BABYLON.Texture("speckles.jpg", scene); // Set the fur length with a texture. ##diffuseTexture A texture can also be used to paint the mesh. The leopard fur texture used in the test is by Martin Wegmann from [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Leopard_fur.JPG) under the [license](https: furMaterial.diffuseTexture = new BABYLON.Texture("leopard_fur.JPG, scene); // Set the fur length with a texture. # Using the High Level mode Fur materials have always been subjects of a lot of theories and conferences with multiple implementations thanks to multiple technologies. Here, with WebGL, we decided to choose one of these implementations, not hard to use and pretty smart (with performances) with simple models First, activate the high level (activated by default): furMaterial.highLevelFur = true; That's all. Now, the most difficult part should be to configure the shells and the fur texture to create the fur effect. Indeed, you'll have to draw several times the same mesh with an offset (computed in the effect) to create the illusion of fur. Hopefully, there is a function that creates and returns the shells: // Generate a fur texture (internally used), working like a noise texture, that will be shared between all the shells var furTexture = BABYLON.FurMaterial.GenerateTexture("furTexture", scene); furMaterial.furTexture = furTexture; myMesh.material = furMaterial; var quality = 30; // Average quality // Create shells var shells = BABYLON.FurMaterial.FurifyMesh(myMesh, quality); It is now working! The function "BABYLON.FurMaterial.FurifyMesh" returns an array of "BABYLON.Mesh" that you can dispose later. The first element is the mesh you used as the source mesh (myMesh here): for (var i=0; i < shells.length; i++) { shells[i].material.dispose(); shells[i].dispose(); } You can customize the high level fur rendering thanks to some properties: allFurMaterials.furSpacing = 2; // Computes the space between shells. In others words, works as the fur height allFurMaterials.furDensity = 20; // Computes the fur density. More the density is high, more you'll have to zoom on the model allFurMaterials.furSpeed = 100; // Divides the animation of fur in time according to the gravity // Compute the gravity followed by the fur allFurMaterials.furGravity = new BABYLON.Vector3(0, -1, 0); # Meshes where the number of facets is not user controlled on creation. Unlike the ground mesh where you can supply the number of subdivisions or the sphere mesh where you can supply the number of segments the majority of meshes are created using a minimum number of facets. To apply the fur material to these the number of facets per face of the mesh needs to be increased. The function increasedFacets will do this: When n is the number of points per side added to each side of a facet the number of facets is increased by the square of (n + 1). function increasedFacets(mesh, pps) { //pps points per side var gaps = pps+1; var n = gaps + 1; var fvs =[]; for(var i=0; i<n; i++) { fvs[i] = []; } var A,B; var d ={x:0,y:0,z:0}; var u ={x:0,y:0}; var indices = []; var vertexIndex = []; var side = []; var uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind); var meshIndices = mesh.getIndices(); var positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var normals =[]; for(var i = 0; i<meshIndices.length; i+=3) { vertexIndex[0] = meshIndices[i]; vertexIndex[1] = meshIndices[i + 1]; vertexIndex[2] = meshIndices[i + 2]; for(var j = 0; j<3; j++) { A = vertexIndex[j]; B = vertexIndex[(j+1)%3]; if(side[A] === undefined && side[B] === undefined) { side[A] = []; side[B] = []; } else { if(side[A] === undefined) { side[A] = []; } if(side[B] === undefined) { side[B] = []; } } if(side[A][B] === undefined && side[B][A] === undefined) { side[A][B] = []; d.x = (positions[3 * B] - positions[3 * A])/gaps; d.y = (positions[3 * B + 1] - positions[3 * A + 1])/gaps; d.z = (positions[3 * B + 2] - positions[3 * A + 2])/gaps; u.x = (uvs[2*B] - uvs[2*A])/gaps; u.y = (uvs[2*B + 1] - uvs[2*A + 1])/gaps; side[A][B].push(A); for(var k=1; k<gaps; k++) { side[A][B].push(positions.length/3); positions.push(positions[3 * A] + k*d.x, positions[3 * A + 1] + k*d.y, positions[3 * A + 2] + k*d.z); uvs.push(uvs[2*A] + k*u.x, uvs[2*A + 1] + k*u.y); } side[A][B].push(B); side[B][A]=[]; l = side[A][B].length; for(var a=0; a<l; a++) { side[B][A][a] = side[A][B][l-1-a]; } } else { if(side[A][B] === undefined) { side[A][B]=[]; l = side[B][A].length; for(var a=0; a<l; a++) { side[A][B][a] = side[B][A][l-1-a]; } } if(side[B][A] === undefined) { side[B][A]=[]; l = side[A][B].length; for(var a=0; a<l; a++) { side[B][A][a] = side[A][B][l-1-a]; } } } } fvs[0][0] = meshIndices[i]; fvs[1][0] = side[meshIndices[i]][meshIndices[i + 1]][1]; fvs[1][1] = side[meshIndices[i]][meshIndices[i + 2]][1]; for(var k = 2; k<gaps; k++) { fvs[k][0] = side[meshIndices[i]][meshIndices[i + 1]][k]; fvs[k][k] = side[meshIndices[i]][meshIndices[i + 2]][k]; d.x = (positions[3 * fvs[k][k]] - positions[3 * fvs[k][0]])/k; d.y = (positions[3 * fvs[k][k] + 1] - positions[3 * fvs[k][0] + 1])/k; d.z = (positions[3 * fvs[k][k] + 2] - positions[3 * fvs[k][0] + 2])/k; u.x = (uvs[2*fvs[k][k]] - uvs[2*fvs[k][0]])/k; u.y = (uvs[2*fvs[k][k] + 1] - uvs[2*fvs[k][0] + 1])/k; for(var j = 1; j<k; j++) { fvs[k][j] = positions.length/3; positions.push(positions[3 * fvs[k][0]] + j*d.x, positions[3 * fvs[k][0] + 1] + j*d.y, positions[3 * fvs[k][0] + 2] + j*d.z); uvs.push(uvs[2*fvs[k][0]] + j*u.x, uvs[2*fvs[k][0] + 1] + j*u.y); } } fvs[gaps] = side[meshIndices[i + 1]][meshIndices[i + 2]]; indices.push(fvs[0][0],fvs[1][0],fvs[1][1]); for(var k = 1; k<gaps; k++) { for(var j = 0; j<k; j++) { indices.push(fvs[k][j],fvs[k+1][j],fvs[k+1][j+1]); indices.push(fvs[k][j],fvs[k+1][j+1],fvs[k][j+1]); } indices.push(fvs[k][j],fvs[k+1][j],fvs[k+1][j+1]); } } var vertexData = new BABYLON.VertexData(); vertexData.positions = positions; vertexData.indices = indices; vertexData.uvs = uvs; BABYLON.VertexData.ComputeNormals(positions, indices, normals); vertexData.normals = normals; mesh.dispose(); var newmesh = new BABYLON.Mesh("newmesh", scene); vertexData.applyToMesh(newmesh); return newmesh; } For sharp edged meshes such as a box the shader can separate the faces since the faces meeting at the corners have there own vertices and normals at these vertices. These meshes are flat shaded. If this separation of the edges is a problem then the function <API key>() can be used. However this can then produce some artefacts at the edges. function <API key>(mesh) { var meshIndices = mesh.getIndices(); var meshPositions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var mesh_uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind); var setPositions = []; var indices = []; var positions = []; var uvs = []; var normals = []; var p; var indexMap = []; for(var i=0; i<meshPositions.length; i+=3) { var temp =[]; temp.push(i/3, meshPositions[i], meshPositions[i + 1], meshPositions[i + 2], mesh_uvs[2*i/3], mesh_uvs[2*i/3 + 1]); setPositions.push(temp); } var i=0; while(setPositions.length>0) { p = setPositions.shift(); positions.push(p[1],p[2],p[3]); uvs.push(p[4],p[5]); indexMap[p[0]] = i; var j = 0; while(j<setPositions.length) { if (Math.abs(p[1] - setPositions[j][1])<Math.pow(0.1, 10) && Math.abs(p[2] - setPositions[j][2])<Math.pow(0.1, 10) && Math.abs(p[3] - setPositions[j][3])<Math.pow(0.1, 10) ) { indexMap[setPositions[j][0]] = i; setPositions.splice(j,1); } else { j++; } } i++; } for(var i=0; i<meshIndices.length; i++) { indices.push(indexMap[meshIndices[i]]); } var vertexData = new BABYLON.VertexData(); vertexData.positions = positions; vertexData.indices = indices; vertexData.uvs = uvs; BABYLON.VertexData.ComputeNormals(positions, indices, normals); vertexData.normals = normals; vertexData.applyToMesh(mesh); return mesh; }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_11) on Mon Jul 12 21:36:30 CEST 2010 --> <TITLE> Uses of Class org.apache.fop.pdf.PDFTTFStream (Apache FOP 1.0 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class org.apache.fop.pdf.PDFTTFStream (Apache FOP 1.0 API)"; } </SCRIPT> </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=3 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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/pdf/PDFTTFStream.html" title="class in org.apache.fop.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</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> fop 1.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PDFTTFStream.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> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.fop.pdf.PDFTTFStream</B></H2> </CENTER> No usage of org.apache.fop.pdf.PDFTTFStream <P> <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=3 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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/pdf/PDFTTFStream.html" title="class in org.apache.fop.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</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> fop 1.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PDFTTFStream.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> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright 1999-2010 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
Base class for queue implementations. A queue is a TensorFlow data structure that stores tensors across multiple steps, and exposes operations that enqueue and dequeue tensors. Each queue element is a tuple of one or more tensors, where each tuple component has a static dtype, and may have a static shape. The queue implementations support versions of enqueue and dequeue that handle single elements, versions that support enqueuing and dequeuing a batch of elements at once. See [`tf.FIFOQueue`](#FIFOQueue) and [`tf.RandomShuffleQueue`](#RandomShuffleQueue) for concrete implementations of this class, and instructions on how to create them. - - - # `tf.QueueBase.enqueue(vals, name=None)` {#QueueBase.enqueue} Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is [closed](#QueueBase.close) before or during its execution. If the queue is closed before this operation runs, `tf.errors.AbortedError` will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with `<API key>=True`, or (ii) the session is [closed](../../api_docs/python/client.md#Session.close), `tf.errors.CancelledError` will be raised. ## Args: * <b>`vals`</b>: A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. * <b>`name`</b>: A name for the operation (optional). ## Returns: The operation that enqueues a new tuple of tensors to the queue. - - - # `tf.QueueBase.enqueue_many(vals, name=None)` {#QueueBase.enqueue_many} Enqueues zero or more elements to this queue. This operation slices each component tensor along the 0th dimension to make multiple queue elements. All of the tensors in `vals` must have the same size in the 0th dimension. If the queue is full when this operation executes, it will block until all of the elements have been enqueued. At runtime, this operation may raise an error if the queue is [closed](#QueueBase.close) before or during its execution. If the queue is closed before this operation runs, `tf.errors.AbortedError` will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with `<API key>=True`, or (ii) the session is [closed](../../api_docs/python/client.md#Session.close), `tf.errors.CancelledError` will be raised. ## Args: * <b>`vals`</b>: A tensor, a list or tuple of tensors, or a dictionary from which the queue elements are taken. * <b>`name`</b>: A name for the operation (optional). ## Returns: The operation that enqueues a batch of tuples of tensors to the queue. - - - # `tf.QueueBase.dequeue(name=None)` {#QueueBase.dequeue} Dequeues one element from this queue. If the queue is empty when this operation executes, it will block until there is an element to dequeue. At runtime, this operation may raise an error if the queue is [closed](#QueueBase.close) before or during its execution. If the queue is closed, the queue is empty, and there are no pending enqueue operations that can fulfil this request, `tf.errors.OutOfRangeError` will be raised. If the session is [closed](../../api_docs/python/client.md#Session.close), `tf.errors.CancelledError` will be raised. ## Args: * <b>`name`</b>: A name for the operation (optional). ## Returns: The tuple of tensors that was dequeued. - - - # `tf.QueueBase.dequeue_many(n, name=None)` {#QueueBase.dequeue_many} Dequeues and concatenates `n` elements from this queue. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. All of the components in the dequeued tuple will have size `n` in the 0th dimension. If the queue is closed and there are less than `n` elements left, then an `OutOfRange` exception is raised. At runtime, this operation may raise an error if the queue is [closed](#QueueBase.close) before or during its execution. If the queue is closed, the queue contains fewer than `n` elements, and there are no pending enqueue operations that can fulfil this request, `tf.errors.OutOfRangeError` will be raised. If the session is [closed](../../api_docs/python/client.md#Session.close), `tf.errors.CancelledError` will be raised. ## Args: * <b>`n`</b>: A scalar `Tensor` containing the number of elements to dequeue. * <b>`name`</b>: A name for the operation (optional). ## Returns: The tuple of concatenated tensors that was dequeued. - - - # `tf.QueueBase.size(name=None)` {#QueueBase.size} Compute the number of elements in this queue. ## Args: * <b>`name`</b>: A name for the operation (optional). ## Returns: A scalar tensor containing the number of elements in this queue. - - - # `tf.QueueBase.close(<API key>=False, name=None)` {#QueueBase.close} Closes this queue. This operation signals that no more elements will be enqueued in the given queue. Subsequent `enqueue` and `enqueue_many` operations will fail. Subsequent `dequeue` and `dequeue_many` operations will continue to succeed if sufficient elements remain in the queue. Subsequent `dequeue` and `dequeue_many` operations that would block will fail immediately. If `<API key>` is `True`, all pending requests will also be cancelled. ## Args: * <b>`<API key>`</b>: (Optional.) A boolean, defaulting to `False` (described above). * <b>`name`</b>: A name for the operation (optional). ## Returns: The operation that closes the queue. # Other Methods - - - # `tf.QueueBase.__init__(dtypes, shapes, names, queue_ref)` {#QueueBase.__init__} Constructs a queue object from a queue reference. The two optional lists, `shapes` and `names`, must be of the same length as `dtypes` if provided. The values at a given index `i` indicate the shape and name to use for the corresponding queue component in `dtypes`. ## Args: * <b>`dtypes`</b>: A list of types. The length of dtypes must equal the number of tensors in each element. * <b>`shapes`</b>: Constraints on the shapes of tensors in an element: A list of shape tuples or None. This list is the same length as dtypes. If the shape of any tensors in the element are constrained, all must be; shapes can be None if the shapes should not be constrained. * <b>`names`</b>: Optional list of names. If provided, the `enqueue()` and `dequeue()` methods will use dictionaries with these names as keys. Must be None or a list or tuple of the same length as `dtypes`. * <b>`queue_ref`</b>: The queue reference, i.e. the output of the queue op. ## Raises: * <b>`ValueError`</b>: If one of the arguments is invalid. - - - # `tf.QueueBase.dequeue_up_to(n, name=None)` {#QueueBase.dequeue_up_to} Dequeues and concatenates `n` elements from this queue. **Note** This operation is not supported by all queues. If a queue does not support DequeueUpTo, then a `tf.errors.UnimplementedError` is raised. This operation concatenates queue-element component tensors along the 0th dimension to make a single component tensor. If the queue has not been closed, all of the components in the dequeued tuple will have size `n` in the 0th dimension. If the queue is closed and there are more than `0` but fewer than `n` elements remaining, then instead of raising a `tf.errors.OutOfRangeError` like [`dequeue_many`](#QueueBase.dequeue_many), the remaining elements are returned immediately. If the queue is closed and there are `0` elements left in the queue, then a `tf.errors.OutOfRangeError` is raised just like in `dequeue_many`. Otherwise the behavior is identical to `dequeue_many`. ## Args: * <b>`n`</b>: A scalar `Tensor` containing the number of elements to dequeue. * <b>`name`</b>: A name for the operation (optional). ## Returns: The tuple of concatenated tensors that was dequeued. - - - # `tf.QueueBase.dtypes` {#QueueBase.dtypes} The list of dtypes for each component of a queue element. - - - # `tf.QueueBase.from_list(index, queues)` {#QueueBase.from_list} Create a queue using the queue reference from `queues[index]`. ## Args: * <b>`index`</b>: An integer scalar tensor that determines the input that gets selected. * <b>`queues`</b>: A list of `QueueBase` objects. ## Returns: A `QueueBase` object. ## Raises: * <b>`TypeError`</b>: When `queues` is not a list of `QueueBase` objects, or when the data types of `queues` are not all the same. - - - # `tf.QueueBase.name` {#QueueBase.name} The name of the underlying queue. - - - # `tf.QueueBase.names` {#QueueBase.names} The list of names for each component of a queue element. - - - # `tf.QueueBase.queue_ref` {#QueueBase.queue_ref} The underlying queue reference.
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.<API key>; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.<API key>; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow; /** * @generated */ public class <API key> extends EditElementCommand { /** * @generated */ public <API key>(<API key> req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * @generated */ protected EObject getElementToEdit() { EObject container = ((<API key>) getRequest()).getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { <API key> container = (<API key>) getElementToEdit(); if (container.getMediatorFlow() != null) { return false; } return true; } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { MediatorFlow newElement = EsbFactory.eINSTANCE.createMediatorFlow(); <API key> owner = (<API key>) getElementToEdit(); owner.setMediatorFlow(newElement); doConfigure(newElement, monitor, info); ((<API key>) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(MediatorFlow newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((<API key>) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((<API key>) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }
package brooklyn.location.jclouds.pool; import java.util.Map; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Processor; import org.jclouds.domain.Location; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; public class <API key> { private static final Logger log = LoggerFactory.getLogger(<API key>.class); public static Predicate<NodeMetadata> except(final MachineSet removedItems) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return !removedItems.contains(input); } }; } public static Predicate<NodeMetadata> except(final Predicate<NodeMetadata> predicateToExclude) { return Predicates.not(predicateToExclude); } public static Predicate<NodeMetadata> matching(final <API key> template) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return matches(template, input); } }; } public static Predicate<NodeMetadata> withTag(final String tag) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return input.getTags().contains(tag); } }; } public static Predicate<NodeMetadata> compose(final Predicate<NodeMetadata> ...predicates) { return Predicates.and(predicates); } public static boolean matches(<API key> template, NodeMetadata m) { try { // tags and user metadata if (! m.getTags().containsAll( template.getTags(false) )) return false; if (! isSubMapOf(template.getUserMetadata(false), m.getUserMetadata())) return false; // common hardware parameters if (template.getMinRam()!=null && m.getHardware().getRam() < template.getMinRam()) return false; if (template.getMinCores()!=null) { double numCores = 0; for (Processor p: m.getHardware().getProcessors()) numCores += p.getCores(); if (numCores+0.001 < template.getMinCores()) return false; } if (template.getIs64bit()!=null) { if (m.getOperatingSystem().is64Bit() != template.getIs64bit()) return false; } if (template.getOsFamily()!=null) { if (m.getOperatingSystem() == null || !template.getOsFamily().equals(m.getOperatingSystem().getFamily())) return false; } if (template.<API key>()!=null) { if (m.getOperatingSystem() == null || m.getOperatingSystem().getName()==null || !m.getOperatingSystem().getName().matches(template.<API key>())) return false; } if (template.getLocationId()!=null) { if (!<API key>(m.getLocation(), template.getLocationId())) return false; } // TODO other TemplateBuilder fields and TemplateOptions return true; } catch (Exception e) { log.warn("Error (rethrowing) trying to match "+m+" against "+template+": "+e, e); throw Throwables.propagate(e); } } private static boolean <API key>(Location location, String locationId) { if (location==null) return false; if (locationId.equals(location.getId())) return true; return <API key>(location.getParent(), locationId); } public static boolean isSubMapOf(Map<String, String> sub, Map<String, String> bigger) { for (Map.Entry<String, String> e: sub.entrySet()) { if (e.getValue()==null) { if (!bigger.containsKey(e.getKey())) return false; if (bigger.get(e.getKey())!=null) return false; } else { if (!e.getValue().equals(bigger.get(e.getKey()))) return false; } } return true; } }
# encoding: utf-8 module RuboCop module Cop module Lint # This cop checks for uses of the deprecated class method usages. class <API key> < Cop include AST::Sexp MSG = '`%s` is deprecated in favor of `%s`.' DEPRECATED_METHODS = [ [:File, :exists?, :exist?], [:Dir, :exists?, :exist?] ] def on_send(node) receiver, method_name, *_args = *node DEPRECATED_METHODS.each do |data| next unless class_nodes(data).include?(receiver) next unless method_name == data[1] add_offense(node, :selector, format(MSG, deprecated_method(data), replacement_method(data))) end end def autocorrect(node) lambda do |corrector| receiver, method_name, *_args = *node DEPRECATED_METHODS.each do |data| next unless class_nodes(data).include?(receiver) next unless method_name == data[1] corrector.replace(node.loc.selector, data[2].to_s) end end end private def class_nodes(data) [s(:const, nil, data[0]), s(:const, s(:cbase), data[0])] end def deprecated_method(data) format('%s.%s', data[0], data[1]) end def replacement_method(data) format('%s.%s', data[0], data[2]) end end end end end
// CAEmitterBehavior+TFEasyCoder.h // TFEasyCoder #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import "TFEasyCoderConst.h" typedef void(^<API key>) (CAEmitterBehavior * ins); @interface CAEmitterBehavior (TFEasyCoder) +( CAEmitterBehavior *)easyCoder:(<API key>)block; -(CAEmitterBehavior *)easyCoder:(<API key>)block; -(CAEmitterBehavior *(^)(NSString * name))set_name; -(CAEmitterBehavior *(^)(BOOL enabled))set_enabled; //superclass pros NSObject -(CAEmitterBehavior *(^)(NSArray * <API key>))<API key>; -(CAEmitterBehavior *(^)(NSArray * <API key>))<API key>; -(CAEmitterBehavior *(^)(BOOL <API key>))<API key>; -(CAEmitterBehavior *(^)(NSString * accessibilityLabel))<API key>; -(CAEmitterBehavior *(^)(NSString * accessibilityHint))<API key>; -(CAEmitterBehavior *(^)(NSString * accessibilityValue))<API key>; -(CAEmitterBehavior *(^)(unsigned long long accessibilityTraits))<API key>; -(CAEmitterBehavior *(^)(UIBezierPath * accessibilityPath))<API key>; -(CAEmitterBehavior *(^)(CGPoint <API key>))<API key>; -(CAEmitterBehavior *(^)(NSString * <API key>))<API key>; -(CAEmitterBehavior *(^)(BOOL <API key>))<API key>; -(CAEmitterBehavior *(^)(BOOL <API key>))<API key>; -(CAEmitterBehavior *(^)(BOOL <API key>))<API key>; -(CAEmitterBehavior *(^)(long long <API key>))<API key>; -(CAEmitterBehavior *(^)(id value,NSString *key))set_ValueKey; @end
<!DOCTYPE html> <html> <head> <title>sidebar-v2 example</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" /> <link rel="stylesheet" href="../css/leaflet-sidebar.css" /> <style> body { padding: 0; margin: 0; } html, body, #map { height: 100%; font: 10pt "Helvetica Neue", Arial, Helvetica, sans-serif; } .lorem { font-style: italic; color: #AAA; } </style> </head> <body> <div id="sidebar" class="sidebar collapsed"> <!-- Nav tabs --> <div class="sidebar-tabs"> <ul role="tablist"> <li><a href="#home" role="tab"><i class="fa fa-bars"></i></a></li> <li><a href="#profile" role="tab"><i class="fa fa-user"></i></a></li> <li class="disabled"><a href="#messages" role="tab"><i class="fa fa-envelope"></i></a></li> </ul> <ul role="tablist"> <li><a href="#settings" role="tab"><i class="fa fa-gear"></i></a></li> </ul> </div> <!-- Tab panes --> <div class="sidebar-content"> <div class="sidebar-pane" id="home"> <h1 class="sidebar-header"> sidebar-v2 <div class="sidebar-close"><i class="fa fa-caret-left"></i></div> </h1> <p>A responsive sidebar for mapping libraries like <a href="http: <p class="lorem">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <p class="lorem">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <p class="lorem">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <p class="lorem">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> </div> <div class="sidebar-pane" id="profile"> <h1 class="sidebar-header">Profile<div class="sidebar-close"><i class="fa fa-caret-left"></i></div></h1> </div> <div class="sidebar-pane" id="messages"> <h1 class="sidebar-header">Messages<div class="sidebar-close"><i class="fa fa-caret-left"></i></div></h1> </div> <div class="sidebar-pane" id="settings"> <h1 class="sidebar-header">Settings<div class="sidebar-close"><i class="fa fa-caret-left"></i></div></h1> </div> </div> </div> <div id="map" class="sidebar-map"></div> <a href="https: <script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script> <script src="../js/leaflet-sidebar.js"></script> <script> var map = L.map('map'); map.setView([51.2, 7], 9); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; OpenStreetMap contributors' }).addTo(map); var marker = L.marker([51.2, 7]).addTo(map); var sidebar = L.control.sidebar('sidebar').addTo(map); </script> </body> </html>
#!/usr/bin/env python # example checkbutton.py import pygtk pygtk.require('2.0') import gtk class CheckButton: # Our callback. # The data passed to this method is printed to stdout def callback(self, widget, data=None): print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()]) # This callback quits the program def delete_event(self, widget, event, data=None): gtk.main_quit() return False def __init__(self): # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) # Set the window title self.window.set_title("Check Button") # Set a handler for delete_event that immediately # exits GTK. self.window.connect("delete_event", self.delete_event) # Sets the border width of the window. self.window.set_border_width(20) # Create a vertical box vbox = gtk.VBox(True, 2) # Put the vbox in the main window self.window.add(vbox) # Create first button button = gtk.CheckButton("check button 1") # When the button is toggled, we call the "callback" method # with a pointer to "button" as its argument button.connect("toggled", self.callback, "check button 1") # Insert button 1 vbox.pack_start(button, True, True, 2) button.show() # Create second button button = gtk.CheckButton("check button 2") # When the button is toggled, we call the "callback" method # with a pointer to "button 2" as its argument button.connect("toggled", self.callback, "check button 2") # Insert button 2 vbox.pack_start(button, True, True, 2) button.show() # Create "Quit" button button = gtk.Button("Quit") # When the button is clicked, we call the mainquit function # and the program exits button.connect("clicked", lambda wid: gtk.main_quit()) # Insert the quit button vbox.pack_start(button, True, True, 2) button.show() vbox.show() self.window.show() def main(): gtk.main() return 0 if __name__ == "__main__": CheckButton() main()
<div data-dojo-type="dijit.layout.SplitContainer" data-dojo-props='orientation:"vertical"'> <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props='title:"split <p>Top of split container loaded via an href.</p> </div> <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props='title:"split <p>Bottom of split container loaded via an href.</p> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean semper sagittis velit. Cras in mi. Duis porta mauris ut ligula. Proin porta rutrum lacus. Etiam consequat scelerisque quam. Nulla facilisi. Maecenas luctus venenatis nulla. In sit amet dui non mi semper iaculis. Sed molestie tortor at ipsum. Morbi dictum rutrum magna. Sed vitae risus. </p> <p>Aliquam vitae enim. Duis scelerisque metus auctor est venenatis imperdiet. Fusce dignissim porta augue. Nulla vestibulum. Integer lorem nunc, ullamcorper a, commodo ac, malesuada sed, dolor. Aenean id mi in massa bibendum suscipit. Integer eros. Nullam suscipit mauris. In pellentesque. Mauris ipsum est, pharetra semper, pharetra in, viverra quis, tellus. Etiam purus. Quisque egestas, tortor ac cursus lacinia, felis leo adipiscing nisi, et rhoncus elit dolor eget eros. Fusce ut quam. Suspendisse eleifend leo vitae ligula. Nulla facilisi. Nulla rutrum, erat vitae lacinia dictum, pede purus imperdiet lacus, ut semper velit ante id metus. Praesent massa dolor, porttitor sed, pulvinar in, consequat ut, leo. Nullam nec est. Aenean id risus blandit tortor pharetra congue. Suspendisse pulvinar. </p> <p>Vestibulum convallis eros ac justo. Proin dolor. Etiam aliquam. Nam ornare elit vel augue. Suspendisse potenti. Etiam sed mauris eu neque nonummy mollis. Vestibulum vel purus ac pede semper accumsan. Vivamus lobortis, sem vitae nonummy lacinia, nisl est gravida magna, non cursus est quam sed urna. Phasellus adipiscing justo in ipsum. Duis sagittis dolor sit amet magna. Suspendisse suscipit, neque eu dictum auctor, nisi augue tincidunt arcu, non lacinia magna purus nec magna. Praesent pretium sollicitudin sapien. Suspendisse imperdiet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. </p> </div> </div>
/*! * Module dependencies. */ var Command = require('./util/command'), phonegapbuild = require('./util/phonegap-build'), util = require('util'); /*! * Command setup. */ module.exports = { create: function(phonegap) { return new RemoteLogoutCommand(phonegap); } }; function RemoteLogoutCommand(phonegap) { return Command.apply(this, arguments); } util.inherits(RemoteLogoutCommand, Command); /** * Logout. * * Logout of PhoneGap/Build. * * Options: * * - `options` {Object} is unused and should be `{}`. * - [`callback`] {Function} is a callback function. * - `e` {Error} is null unless there is an error. * * Returns: * * {PhoneGap} for chaining. */ RemoteLogoutCommand.prototype.run = function(options, callback) { var self = this; // require options if (!options) throw new Error('requires options parameter'); // optional callback callback = callback || function() {}; // logout phonegapbuild.logout(options, function(e) { callback(e); }); return self.phonegap; };
//go:build 386 || amd64p32 || arm || mipsle || mips64p32le // +build 386 amd64p32 arm mipsle mips64p32le package sys import ( "unsafe" ) // Pointer wraps an unsafe.Pointer to be 64bit to // conform to the syscall specification. type Pointer struct { ptr unsafe.Pointer pad uint32 }
cask 'multibit' do version '0.5.19' sha256 '<SHA256-like>' url "https://multibit.org/releases/multibit-classic/multibit-classic-#{version}/<API key>-#{version}.dmg" gpg "#{url}.asc", :key_id => '23f7fb7b' name 'MultiBit' homepage 'https://multibit.org/' license :mit app 'MultiBit.app' end
// This file was procedurally generated from the following sources: // - src/dstr-binding/<API key>.case // - src/dstr-binding/default/<API key>.template var initCount = 0; function counter() { initCount += 1; } var callCount = 0; class C { async *method({ w = counter(), x = counter(), y = counter(), z = counter() } = { w: null, x: 0, y: false, z: '' }) { assert.sameValue(w, null); assert.sameValue(x, 0); assert.sameValue(y, false); assert.sameValue(z, ''); assert.sameValue(initCount, 0); callCount = callCount + 1; } }; new C().method().next().then(() => { assert.sameValue(callCount, 1, 'invoked exactly once'); }).then($DONE, $DONE);
/* *@brief RDTSC implementation * *@date 22.10.2013 * * */ #include <stdint.h> #include <hal/cpu_info.h> uint64_t get_cpu_counter(void) { uint64_t hi = 0, lo = 0; asm volatile ( "rdtsc\n\t" "movl %%eax, %0\n\t" "movl %%edx, %1\n\t" : "=r"(lo), "=r"(hi) :); return (hi << 32) + lo; }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML3.2 EN"> <HTML> <HEAD> <META NAME="GENERATOR" CONTENT="DOCTEXT"> <TITLE>MPI_Ibsend</TITLE> </HEAD> <BODY BGCOLOR="FFFFFF"> <A NAME="MPI_Ibsend"><H1>MPI_Ibsend</H1></A> Starts a nonblocking buffered send <H2>Synopsis</H2> <PRE> int MPI_Ibsend(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) </PRE> <H2>Input Parameters</H2> <DL> <DT><B>buf </B><DD>initial address of send buffer (choice) <DT><B>count </B><DD>number of elements in send buffer (integer) <DT><B>datatype </B><DD>datatype of each send buffer element (handle) <DT><B>dest </B><DD>rank of destination (integer) <DT><B>tag </B><DD>message tag (integer) <DT><B>comm </B><DD>communicator (handle) </DL> <P> <H2>Output Parameter</H2> <DL><DT><B>request </B> <DD> communication request (handle) </DL> <P> <H2>Thread and Interrupt Safety</H2> <P> This routine is thread-safe. This means that this routine may be safely used by multiple threads without the need for any user-provided thread locks. However, the routine is not interrupt safe. Typically, this is due to the use of memory allocation routines such as <TT>malloc </TT>or other non-MPICH runtime routines that are themselves not interrupt-safe. <P> <H2>Notes for Fortran</H2> All MPI routines in Fortran (except for <TT>MPI_WTIME</TT> and <TT>MPI_WTICK</TT>) have an additional argument <TT>ierr</TT> at the end of the argument list. <TT>ierr </TT>is an integer and has the same meaning as the return value of the routine in C. In Fortran, MPI routines are subroutines, and are invoked with the <TT>call</TT> statement. <P> All MPI objects (e.g., <TT>MPI_Datatype</TT>, <TT>MPI_Comm</TT>) are of type <TT>INTEGER </TT>in Fortran. <P> <H2>Errors</H2> <P> All MPI routines (except <TT>MPI_Wtime</TT> and <TT>MPI_Wtick</TT>) return an error value; C routines as the value of the function and Fortran routines in the last argument. Before the value is returned, the current MPI error handler is called. By default, this error handler aborts the MPI job. The error handler may be changed with <TT><API key></TT> (for communicators), <TT><API key></TT> (for files), and <TT><API key></TT> (for RMA windows). The MPI-1 routine <TT>MPI_Errhandler_set</TT> may be used but its use is deprecated. The predefined error handler <TT>MPI_ERRORS_RETURN</TT> may be used to cause error values to be returned. Note that MPI does <EM>not</EM> guarentee that an MPI program can continue past an error; however, MPI implementations will attempt to continue whenever possible. <P> <DL><DT><B>MPI_SUCCESS </B> <DD> No error; MPI routine completed successfully. </DL> <DL><DT><B>MPI_ERR_COMM </B> <DD> Invalid communicator. A common error is to use a null communicator in a call (not even allowed in <TT>MPI_Comm_rank</TT>). </DL> <DL><DT><B>MPI_ERR_COUNT </B> <DD> Invalid count argument. Count arguments must be non-negative; a count of zero is often valid. </DL> <DL><DT><B>MPI_ERR_TYPE </B> <DD> Invalid datatype argument. May be an uncommitted MPI_Datatype (see <TT>MPI_Type_commit</TT>). </DL> <DL><DT><B>MPI_ERR_TAG </B> <DD> Invalid tag argument. Tags must be non-negative; tags in a receive (<TT>MPI_Recv</TT>, <TT>MPI_Irecv</TT>, <TT>MPI_Sendrecv</TT>, etc.) may also be <TT>MPI_ANY_TAG</TT>. The largest tag value is available through the the attribute <TT>MPI_TAG_UB</TT>. </DL> <DL><DT><B>MPI_ERR_RANK </B> <DD> Invalid source or destination rank. Ranks must be between zero and the size of the communicator minus one; ranks in a receive (<TT>MPI_Recv</TT>, <TT>MPI_Irecv</TT>, <TT>MPI_Sendrecv</TT>, etc.) may also be <TT>MPI_ANY_SOURCE</TT>. </DL> <DL><DT><B>MPI_ERR_BUFFER </B> <DD> Invalid buffer pointer. Usually a null buffer where one is not valid. </DL> <P> <P><B>Location:</B>ibsend.c<P> </BODY></HTML>
#if HAVE_CONFIG_H # include <config.h> #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <netinet/in.h> #include <string.h> #include <infiniband/opcode.h> #include "mthca.h" #include "doorbell.h" enum { MTHCA_CQ_DOORBELL = 0x20 }; enum { CQ_OK = 0, CQ_EMPTY = -1, CQ_POLL_ERR = -2 }; #define <API key> (1 << 24) #define <API key> (2 << 24) #define <API key> (3 << 24) #define <API key> (4 << 24) #define <API key> (5 << 24) #define <API key> (1 << 24) #define <API key> (2 << 24) #define <API key> (3 << 24) enum { <API key> = 0x00, <API key> = 0x80, <API key> = 0xfe }; enum { <API key> = 0x01, <API key> = 0x02, <API key> = 0x03, <API key> = 0x04, <API key> = 0x05, <API key> = 0x06, <API key> = 0x10, <API key> = 0x11, <API key> = 0x12, <API key> = 0x13, <API key> = 0x14, <API key> = 0x15, <API key> = 0x16, <API key> = 0x20, <API key> = 0x21, <API key> = 0x22, <API key> = 0x23, <API key> = 0x24 }; struct mthca_cqe { uint32_t my_qpn; uint32_t my_ee; uint32_t rqpn; uint16_t sl_g_mlpath; uint16_t rlid; uint32_t imm_etype_pkey_eec; uint32_t byte_cnt; uint32_t wqe; uint8_t opcode; uint8_t is_send; uint8_t reserved; uint8_t owner; }; struct mthca_err_cqe { uint32_t my_qpn; uint32_t reserved1[3]; uint8_t syndrome; uint8_t vendor_err; uint16_t db_cnt; uint32_t reserved2; uint32_t wqe; uint8_t opcode; uint8_t reserved3[2]; uint8_t owner; }; static inline struct mthca_cqe *get_cqe(struct mthca_cq *cq, int entry) { return cq->buf.buf + entry * MTHCA_CQ_ENTRY_SIZE; } static inline struct mthca_cqe *cqe_sw(struct mthca_cq *cq, int i) { struct mthca_cqe *cqe = get_cqe(cq, i); return <API key> & cqe->owner ? NULL : cqe; } static inline struct mthca_cqe *next_cqe_sw(struct mthca_cq *cq) { return cqe_sw(cq, cq->cons_index & cq->ibv_cq.cqe); } static inline void set_cqe_hw(struct mthca_cqe *cqe) { <API key>(cqe, sizeof *cqe); cqe->owner = <API key>; } /* * incr is ignored in native Arbel (mem-free) mode, so cq->cons_index * should be correct before calling update_cons_index(). */ static inline void update_cons_index(struct mthca_cq *cq, int incr) { uint32_t doorbell[2]; if (mthca_is_memfree(cq->ibv_cq.context)) { *cq->set_ci_db = htonl(cq->cons_index); wmb(); } else { doorbell[0] = htonl(<API key> | cq->cqn); doorbell[1] = htonl(incr - 1); mthca_write64(doorbell, to_mctx(cq->ibv_cq.context), MTHCA_CQ_DOORBELL); } } static void dump_cqe(void *cqe_ptr) { uint32_t *cqe = cqe_ptr; int i; for (i = 0; i < 8; ++i) printf(" [%2x] %08x\n", i * 4, ntohl(((uint32_t *) cqe)[i])); } static int handle_error_cqe(struct mthca_cq *cq, struct mthca_qp *qp, int wqe_index, int is_send, struct mthca_err_cqe *cqe, struct ibv_wc *wc, int *free_cqe) { int err; int dbd; uint32_t new_wqe; if (cqe->syndrome == <API key>) { printf("local QP operation err " "(QPN %06x, WQE @ %08x, CQN %06x, index %d)\n", ntohl(cqe->my_qpn), ntohl(cqe->wqe), cq->cqn, cq->cons_index); dump_cqe(cqe); } /* * For completions in error, only work request ID, status, vendor error * (and freed resource count for RD) have to be set. */ switch (cqe->syndrome) { case <API key>: wc->status = IBV_WC_LOC_LEN_ERR; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = IBV_WC_LOC_PROT_ERR; break; case <API key>: wc->status = IBV_WC_WR_FLUSH_ERR; break; case <API key>: wc->status = IBV_WC_MW_BIND_ERR; break; case <API key>: wc->status = IBV_WC_BAD_RESP_ERR; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = IBV_WC_REM_OP_ERR; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = <API key>; break; case <API key>: wc->status = IBV_WC_INV_EECN_ERR; break; case <API key>: wc->status = <API key>; break; default: wc->status = IBV_WC_GENERAL_ERR; break; } wc->vendor_err = cqe->vendor_err; /* * Mem-free HCAs always generate one CQE per WQE, even in the * error case, so we don't have to check the doorbell count, etc. */ if (mthca_is_memfree(cq->ibv_cq.context)) return 0; err = mthca_free_err_wqe(qp, is_send, wqe_index, &dbd, &new_wqe); if (err) return err; /* * If we're at the end of the WQE chain, or we've used up our * doorbell count, free the CQE. Otherwise just update it for * the next poll operation. * * This doesn't apply to mem-free HCAs, which never use the * doorbell count field. In that case we always free the CQE. */ if (mthca_is_memfree(cq->ibv_cq.context) || !(new_wqe & htonl(0x3f)) || (!cqe->db_cnt && dbd)) return 0; cqe->db_cnt = htons(ntohs(cqe->db_cnt) - dbd); cqe->wqe = new_wqe; cqe->syndrome = <API key>; *free_cqe = 0; return 0; } static inline int mthca_poll_one(struct mthca_cq *cq, struct mthca_qp **cur_qp, int *freed, struct ibv_wc *wc) { struct mthca_wq *wq; struct mthca_cqe *cqe; struct mthca_srq *srq; uint32_t qpn; uint32_t wqe; int wqe_index; int is_error; int is_send; int free_cqe = 1; int err = 0; cqe = next_cqe_sw(cq); if (!cqe) return CQ_EMPTY; <API key>(cqe, sizeof *cqe); /* * Make sure we read CQ entry contents after we've checked the * ownership bit. */ rmb(); qpn = ntohl(cqe->my_qpn); is_error = (cqe->opcode & <API key>) == <API key>; is_send = is_error ? cqe->opcode & 0x01 : cqe->is_send & 0x80; if (!*cur_qp || ntohl(cqe->my_qpn) != (*cur_qp)->ibv_qp.qp_num) { /* * We do not have to take the QP table lock here, * because CQs will be locked while QPs are removed * from the table. */ *cur_qp = mthca_find_qp(to_mctx(cq->ibv_cq.context), ntohl(cqe->my_qpn)); if (!*cur_qp) { err = CQ_POLL_ERR; goto out; } } wc->qp_num = (*cur_qp)->ibv_qp.qp_num; if (is_send) { wq = &(*cur_qp)->sq; wqe_index = ((ntohl(cqe->wqe) - (*cur_qp)->send_wqe_offset) >> wq->wqe_shift); wc->wr_id = (*cur_qp)->wrid[wqe_index + (*cur_qp)->rq.max]; } else if ((*cur_qp)->ibv_qp.srq) { srq = to_msrq((*cur_qp)->ibv_qp.srq); wqe = htonl(cqe->wqe); wq = NULL; wqe_index = wqe >> srq->wqe_shift; wc->wr_id = srq->wrid[wqe_index]; mthca_free_srq_wqe(srq, wqe_index); } else { int32_t wqe; wq = &(*cur_qp)->rq; wqe = ntohl(cqe->wqe); wqe_index = wqe >> wq->wqe_shift; /* * WQE addr == base - 1 might be reported by Sinai FW * 1.0.800 and Arbel FW 5.1.400 in receive completion * with error instead of (rq size - 1). This bug * should be fixed in later FW revisions. */ if (wqe_index < 0) wqe_index = wq->max - 1; wc->wr_id = (*cur_qp)->wrid[wqe_index]; } if (wq) { if (wq->last_comp < wqe_index) wq->tail += wqe_index - wq->last_comp; else wq->tail += wqe_index + wq->max - wq->last_comp; wq->last_comp = wqe_index; } if (is_error) { err = handle_error_cqe(cq, *cur_qp, wqe_index, is_send, (struct mthca_err_cqe *) cqe, wc, &free_cqe); goto out; } if (is_send) { wc->wc_flags = 0; switch (cqe->opcode) { case <API key>: wc->opcode = IBV_WC_RDMA_WRITE; break; case <API key>: wc->opcode = IBV_WC_RDMA_WRITE; wc->wc_flags |= IBV_WC_WITH_IMM; break; case MTHCA_OPCODE_SEND: wc->opcode = IBV_WC_SEND; break; case <API key>: wc->opcode = IBV_WC_SEND; wc->wc_flags |= IBV_WC_WITH_IMM; break; case <API key>: wc->opcode = IBV_WC_RDMA_READ; wc->byte_len = ntohl(cqe->byte_cnt); break; case <API key>: wc->opcode = IBV_WC_COMP_SWAP; wc->byte_len = ntohl(cqe->byte_cnt); break; case <API key>: wc->opcode = IBV_WC_FETCH_ADD; wc->byte_len = ntohl(cqe->byte_cnt); break; case <API key>: wc->opcode = IBV_WC_BIND_MW; break; default: /* assume it's a send completion */ wc->opcode = IBV_WC_SEND; break; } } else { wc->byte_len = ntohl(cqe->byte_cnt); switch (cqe->opcode & 0x1f) { case <API key>: case <API key>: wc->wc_flags = IBV_WC_WITH_IMM; wc->imm_data = cqe->imm_etype_pkey_eec; wc->opcode = IBV_WC_RECV; break; case <API key>: case <API key>: wc->wc_flags = IBV_WC_WITH_IMM; wc->imm_data = cqe->imm_etype_pkey_eec; wc->opcode = <API key>; break; default: wc->wc_flags = 0; wc->opcode = IBV_WC_RECV; break; } wc->slid = ntohs(cqe->rlid); wc->sl = ntohs(cqe->sl_g_mlpath) >> 12; wc->src_qp = ntohl(cqe->rqpn) & 0xffffff; wc->dlid_path_bits = ntohs(cqe->sl_g_mlpath) & 0x7f; wc->pkey_index = ntohl(cqe->imm_etype_pkey_eec) >> 16; wc->wc_flags |= ntohs(cqe->sl_g_mlpath) & 0x80 ? IBV_WC_GRH : 0; } wc->status = IBV_WC_SUCCESS; out: if (free_cqe) { set_cqe_hw(cqe); ++(*freed); ++cq->cons_index; } return err; } int mthca_poll_cq(struct ibv_cq *ibcq, int ne, struct ibv_wc *wc) { struct mthca_cq *cq = to_mcq(ibcq); struct mthca_qp *qp = NULL; int npolled; int err = CQ_OK; int freed = 0; pthread_spin_lock(&cq->lock); for (npolled = 0; npolled < ne; ++npolled) { err = mthca_poll_one(cq, &qp, &freed, wc + npolled); if (err != CQ_OK) break; } if (freed) { wmb(); update_cons_index(cq, freed); } pthread_spin_unlock(&cq->lock); return err == CQ_POLL_ERR ? err : npolled; } int mthca_tavor_arm_cq(struct ibv_cq *cq, int solicited) { uint32_t doorbell[2]; doorbell[0] = htonl((solicited ? <API key> : <API key>) | to_mcq(cq)->cqn); doorbell[1] = 0xffffffff; mthca_write64(doorbell, to_mctx(cq->context), MTHCA_CQ_DOORBELL); return 0; } int mthca_arbel_arm_cq(struct ibv_cq *ibvcq, int solicited) { struct mthca_cq *cq = to_mcq(ibvcq); uint32_t doorbell[2]; uint32_t sn; uint32_t ci; sn = cq->arm_sn & 3; ci = htonl(cq->cons_index); doorbell[0] = ci; doorbell[1] = htonl((cq->cqn << 8) | (2 << 5) | (sn << 3) | (solicited ? 1 : 2)); mthca_write_db_rec(doorbell, cq->arm_db); /* * Make sure that the doorbell record in host memory is * written before ringing the doorbell via PCI MMIO. */ wmb(); doorbell[0] = htonl((sn << 28) | (solicited ? <API key> : <API key>) | cq->cqn); doorbell[1] = ci; mthca_write64(doorbell, to_mctx(ibvcq->context), MTHCA_CQ_DOORBELL); return 0; } void <API key>(struct ibv_cq *cq) { to_mcq(cq)->arm_sn++; } static inline int is_recv_cqe(struct mthca_cqe *cqe) { if ((cqe->opcode & <API key>) == <API key>) return !(cqe->opcode & 0x01); else return !(cqe->is_send & 0x80); } void __mthca_cq_clean(struct mthca_cq *cq, uint32_t qpn, struct mthca_srq *srq) { struct mthca_cqe *cqe; uint32_t prod_index; int i, nfreed = 0; /* * First we need to find the current producer index, so we * know where to start cleaning from. It doesn't matter if HW * adds new entries after this loop -- the QP we're worried * about is already in RESET, so the new entries won't come * from our QP and therefore don't need to be checked. */ for (prod_index = cq->cons_index; cqe_sw(cq, prod_index & cq->ibv_cq.cqe); ++prod_index) if (prod_index == cq->cons_index + cq->ibv_cq.cqe) break; /* * Now sweep backwards through the CQ, removing CQ entries * that match our QP by copying older entries on top of them. */ while ((int) --prod_index - (int) cq->cons_index >= 0) { cqe = get_cqe(cq, prod_index & cq->ibv_cq.cqe); if (cqe->my_qpn == htonl(qpn)) { if (srq && is_recv_cqe(cqe)) mthca_free_srq_wqe(srq, ntohl(cqe->wqe) >> srq->wqe_shift); ++nfreed; } else if (nfreed) memcpy(get_cqe(cq, (prod_index + nfreed) & cq->ibv_cq.cqe), cqe, MTHCA_CQ_ENTRY_SIZE); } if (nfreed) { for (i = 0; i < nfreed; ++i) set_cqe_hw(get_cqe(cq, (cq->cons_index + i) & cq->ibv_cq.cqe)); wmb(); cq->cons_index += nfreed; update_cons_index(cq, nfreed); } } void mthca_cq_clean(struct mthca_cq *cq, uint32_t qpn, struct mthca_srq *srq) { pthread_spin_lock(&cq->lock); __mthca_cq_clean(cq, qpn, srq); pthread_spin_unlock(&cq->lock); } void <API key>(struct mthca_cq *cq, void *buf, int old_cqe) { int i; /* * In Tavor mode, the hardware keeps the consumer and producer * indices mod the CQ size. Since we might be making the CQ * bigger, we need to deal with the case where the producer * index wrapped around before the CQ was resized. */ if (!mthca_is_memfree(cq->ibv_cq.context) && old_cqe < cq->ibv_cq.cqe) { cq->cons_index &= old_cqe; if (cqe_sw(cq, old_cqe)) cq->cons_index -= old_cqe + 1; } for (i = cq->cons_index; cqe_sw(cq, i & old_cqe); ++i) memcpy(buf + (i & cq->ibv_cq.cqe) * MTHCA_CQ_ENTRY_SIZE, get_cqe(cq, i & old_cqe), MTHCA_CQ_ENTRY_SIZE); } int mthca_alloc_cq_buf(struct mthca_device *dev, struct mthca_buf *buf, int nent) { int i; if (mthca_alloc_buf(buf, align(nent * MTHCA_CQ_ENTRY_SIZE, dev->page_size), dev->page_size)) return -1; for (i = 0; i < nent; ++i) ((struct mthca_cqe *) buf->buf)[i].owner = <API key>; return 0; }
{-# LANGUAGE OverloadedStrings, TupleSections #-} -- | Parser components for the ROS message description language (@msg@ -- files). See http://wiki.ros.org/msg for reference. module Parse (parseMsg, parseSrv, simpleFieldAssoc) where import Prelude hiding (takeWhile) import Control.Applicative import Control.Arrow ((&&&)) import Data.Attoparsec.ByteString.Char8 import Data.ByteString (ByteString) import Data.ByteString.Char8 (pack, unpack) import qualified Data.ByteString.Char8 as B import Data.Char (toLower, digitToInt) import Data.Either (partitionEithers) import Data.List (foldl') import System.FilePath (dropExtension, takeFileName, splitDirectories) import Types simpleFieldTypes :: [MsgType] simpleFieldTypes = [ RBool, RInt8, RUInt8, RInt16, RUInt16, RInt32, RUInt32, RInt64, RUInt64, RFloat32, RFloat64, RString, RTime, RDuration, RByte, RChar ] simpleFieldAssoc :: [(MsgType, ByteString)] simpleFieldAssoc = map (id &&& B.pack . map toLower . tail . show) simpleFieldTypes eatLine :: Parser () eatLine = manyTill anyChar (eitherP endOfLine endOfInput) *> skipSpace parseName :: Parser ByteString parseName = skipSpace *> identifier <* eatLine <* try comment identifier :: Parser ByteString identifier = B.cons <$> letter_ascii <*> takeWhile validChar where validChar c = any ($ c) [isDigit, isAlpha_ascii, (== '_'), (== '/')] parseInt :: Parser Int parseInt = foldl' (\s x -> s*10 + digitToInt x) 0 <$> many1 digit comment :: Parser [()] comment = many $ skipSpace *> try (char '#' *> eatLine) simpleParser :: (MsgType, ByteString) -> Parser (ByteString, MsgType) simpleParser (t,b) = (, t) <$> (string b *> space *> parseName) fixedArrayParser :: (MsgType, ByteString) -> Parser (ByteString, MsgType) fixedArrayParser (t,b) = (\len name -> (name, RFixedArray len t)) <$> (string b *> char '[' *> parseInt <* char ']') <*> (space *> parseName) varArrayParser :: (MsgType, ByteString) -> Parser (ByteString, MsgType) varArrayParser (t,b) = (, RVarArray t) <$> (string b *> string "[]" *> space *> parseName) userTypeParser :: Parser (ByteString, MsgType) userTypeParser = choice [userSimple, userVarArray, userFixedArray] userSimple :: Parser (ByteString, MsgType) userSimple = (\t name -> (name, RUserType t)) <$> identifier <*> (space *> parseName) userVarArray :: Parser (ByteString, MsgType) userVarArray = (\t name -> (name, RVarArray (RUserType t))) <$> identifier <*> (string "[]" *> space *> parseName) userFixedArray :: Parser (ByteString, MsgType) userFixedArray = (\t n name -> (name, RFixedArray n (RUserType t))) <$> identifier <*> (char '[' *> parseInt <* char ']') <*> (space *> parseName) -- Parse constants defined in the message constParser :: ByteString -> MsgType -> Parser (ByteString, MsgType, ByteString) constParser s x = (,x,) <$> (string s *> space *> identifier) <*> (skipSpace *> char '=' *> skipSpace *> restOfLine <* skipSpace) where restOfLine :: Parser ByteString restOfLine = pack <$> manyTill anyChar (eitherP endOfLine endOfInput) constParsers :: [Parser (ByteString, MsgType, ByteString)] constParsers = map (uncurry constParser . swap) simpleFieldAssoc where swap (x,y) = (y,x) -- String constants are parsed somewhat differently from numeric -- constants. For numerical constants, we drop comments and trailing -- spaces. For strings, we take the whole line (so comments aren't -- stripped). sanitizeConstants :: (a, MsgType, ByteString) -> (a, MsgType, ByteString) sanitizeConstants c@(_, RString, _) = c sanitizeConstants (name, t, val) = (name, t, B.takeWhile (\c -> c /= '#' && not (isSpace c)) val) -- Parsers fields and constants. fieldParsers :: [Parser (Either (ByteString, MsgType) (ByteString, MsgType, ByteString))] fieldParsers = map (comment *>) $ map (Right . sanitizeConstants <$>) constParsers ++ map (Left <$>) (builtIns ++ [userTypeParser]) where builtIns = concatMap (`map` simpleFieldAssoc) [simpleParser, fixedArrayParser, varArrayParser] mkParser :: MsgName -> String -> ByteString -> Parser Msg mkParser sname lname txt = aux . partitionEithers <$> many (choice fieldParsers) where aux (fs, cs) = Msg sname lname txt (map buildField fs) (map buildConst cs) buildField :: (ByteString, MsgType) -> MsgField buildField (name,typ) = MsgField fname typ name where fname = B.append "_" $ sanitize name buildConst :: (ByteString, MsgType, ByteString) -> MsgConst buildConst (name,typ,val) = MsgConst fname typ val name where fname = B.map toLower $ sanitize name {- testMsg :: ByteString testMsg = "# Foo bar\n\n# \nHeader header # a header\nuint32 aNum # a number \n # It's not important\ngeometry_msgs/PoseStamped[] poses\nbyte DEBUG=1 #debug level\n" test :: Result Msg test = feed (parse (comment *> (mkParser "" "" testMsg)) testMsg) "" -} -- Ensure that field and constant names are valid Haskell identifiers -- and do not coincide with Haskell reserved words. sanitize :: ByteString -> ByteString sanitize "data" = "_data" sanitize "type" = "_type" sanitize "class" = "_class" sanitize "module" = "_module" sanitize x = B.cons (toLower (B.head x)) (B.tail x) pkgName :: FilePath -> String pkgName f = let parts = splitDirectories f [pkg,_,_msgFile] = drop (length parts - 3) parts in pkg parseMsg :: FilePath -> IO (Either String Msg) parseMsg fname = do msgFile <- B.readFile fname let tName = msgName . dropExtension . takeFileName $ fname packageName = pkgName fname return $ parseMsgWithName tName packageName msgFile parseMsgWithName :: MsgName -> String -> ByteString -> Either String Msg parseMsgWithName name packageName msgFile = case feed (parse parser msgFile) "" of Done leftOver msg | B.null leftOver -> Right msg | otherwise -> Left $ "Couldn't parse " ++ unpack leftOver Fail _ _ctxt err -> Left err Partial _ -> Left "Incomplete msg definition" where parser = comment *> mkParser name packageName msgFile -- | Parse a service file by splitting the file into a request and a response -- | and parsing each part separately. parseSrv :: FilePath -> IO (Either String Srv) parseSrv fname = do srvFile <- B.readFile fname let (request, response) = splitService srvFile packageName = pkgName fname rawServiceName = dropExtension . takeFileName $ fname return $ do rqst <- parseMsgWithName (requestMsgName rawServiceName) packageName request resp <- parseMsgWithName (responseMsgName rawServiceName) packageName response return Srv{srvRequest = rqst , srvResponse = resp , srvName = msgName rawServiceName , srvPackage = packageName , srvSource = srvFile} splitService :: ByteString -> (ByteString, ByteString) splitService service = (request, response) where -- divider does not include newlines to allow it match even -- if there is no request or response message divider = " (request, dividerAndResponse) = B.breakSubstring divider service --Add 1 to the length of the divider to remove newline response = B.drop (1 + B.length divider) dividerAndResponse
"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:])
<?php $this->breadcrumbs = [ Yii::t('StoreModule.category', 'Categories') => ['index'], $model->name, ]; $this->pageTitle = Yii::t('StoreModule.category', 'Categories - view'); $this->menu = [ ['icon' => 'fa fa-fw fa-list-alt', 'label' => Yii::t('StoreModule.category', 'Manage categories'), 'url' => ['/store/categoryBackend/index']], ['icon' => 'fa fa-fw fa-plus-square', 'label' => Yii::t('StoreModule.category', 'Create category'), 'url' => ['/store/categoryBackend/create']], ['label' => Yii::t('StoreModule.category', 'Category') . ' «' . mb_substr($model->name, 0, 32) . '»'], [ 'icon' => 'fa fa-fw fa-pencil', 'label' => Yii::t('StoreModule.category', 'Update category'), 'url' => [ '/store/categoryBackend/update', 'id' => $model->id ] ], [ 'icon' => 'fa fa-fw fa-eye', 'label' => Yii::t('StoreModule.category', 'View category'), 'url' => [ '/store/categoryBackend/view', 'id' => $model->id ] ], [ 'icon' => 'fa fa-fw fa-trash-o', 'label' => Yii::t('StoreModule.category', 'Delete category'), 'url' => ' 'linkOptions' => [ 'submit' => ['/store/categoryBackend/delete', 'id' => $model->id], 'params' => [Yii::app()->getRequest()->csrfTokenName => Yii::app()->getRequest()->csrfToken], 'confirm' => Yii::t('StoreModule.category', 'Do you really want to remove category?'), 'csrf' => true, ] ], ]; ?> <div class="page-header"> <h1> <?php echo Yii::t('StoreModule.category', 'Viewing category'); ?><br/> <small>&laquo;<?php echo $model->name; ?>&raquo;</small> </h1> </div> <?php $this->widget( 'bootstrap.widgets.TbDetailView', [ 'data' => $model, 'attributes' => [ 'id', [ 'name' => 'parent_id', 'value' => $model->getParentName(), ], 'name', 'slug', [ 'name' => 'image', 'type' => 'raw', 'value' => $model->image ? CHtml::image($model->getImageUrl(200, 200), $model->name) : ' ], [ 'name' => 'description', 'type' => 'raw' ], [ 'name' => 'short_description', 'type' => 'raw' ], [ 'name' => 'status', 'value' => $model->getStatus(), ], ], ] ); ?>
'use strict'; const EventEmitter = require('../../vendor/emitter/EventEmitter'); const <API key> = require('../<API key>'); /** * Mock the NativeEventEmitter as a normal JS EventEmitter. */ class NativeEventEmitter extends EventEmitter { constructor() { super(<API key>.sharedSubscriber); } } module.exports = NativeEventEmitter;
#ifndef STATS_H #define STATS_H #include "GetTime.h" #include "BeginPrivate.h" #if defined(mingw32_HOST_OS) /* On Win64, if we say "printf" then gcc thinks we are going to use MS format specifiers like %I64d rather than %llu */ #define PRINTF gnu_printf #else /* However, on OS X, "gnu_printf" isn't recognised */ #define PRINTF printf #endif struct gc_thread_; void stat_startInit(void); void stat_endInit(void); void stat_startGCSync(struct gc_thread_ *_gct); void stat_startGC(Capability *cap, struct gc_thread_ *_gct); void stat_endGC (Capability *cap, struct gc_thread_ *_gct, W_ live, W_ copied, W_ slop, uint32_t gen, uint32_t n_gc_threads, W_ par_max_copied, W_ par_tot_copied); #ifdef PROFILING void stat_startRP(void); void stat_endRP(uint32_t, #ifdef DEBUG_RETAINER uint32_t, int, #endif double); #endif /* PROFILING */ #if defined(PROFILING) || defined(DEBUG) void <API key>(void); void stat_endHeapCensus(void); #endif void stat_startExit(void); void stat_endExit(void); void stat_exit(void); void stat_workerStop(void); void initStats0(void); void initStats1(void); double mut_user_time_until(Time t); double mut_user_time(void); void statDescribeGens( void ); Time <API key>(void); Time stat_getElapsedTime(void); #include "EndPrivate.h" #endif /* STATS_H */
# Generated by Django 2.2.6 on 2019-10-23 09:06 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import olympia.amo.models class Migration(migrations.Migration): dependencies = [ ('scanners', '<API key>'), ] operations = [ migrations.CreateModel( name='ScannerMatch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False)), ('modified', models.DateTimeField(auto_now=True)), ('result', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scanners.ScannerResult')), ('rule', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scanners.ScannerRule')), ], options={ 'get_latest_by': 'created', 'abstract': False, 'base_manager_name': 'objects', }, bases=(olympia.amo.models.SearchMixin, olympia.amo.models.SaveUpdateMixin, models.Model), ), migrations.AddField( model_name='scannerresult', name='matched_rules', field=models.ManyToManyField(through='scanners.ScannerMatch', to='scanners.ScannerRule'), ), ]
# modification, are permitted provided that the following conditions are met: # documentation and/or other materials provided with the distribution. # * Neither the name of NuoDB, Inc. nor the names of its contributors may # be used to endorse or promote products derived from this software # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NUODB, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require 'active_record/connection_adapters/nuodb_adapter'
#include "chrome/browser/sync_file_system/local/<API key>.h" #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "chrome/browser/sync_file_system/local/<API key>.h" #include "chrome/browser/sync_file_system/local/<API key>.h" #include "chrome/browser/sync_file_system/local/<API key>.h" #include "chrome/browser/sync_file_system/sync_file_metadata.h" #include "chrome/browser/sync_file_system/sync_status_code.h" #include "chrome/browser/sync_file_system/<API key>.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/<API key>.h" #include "content/public/test/<API key>.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/src/helpers/memenv/memenv.h" #include "third_party/leveldatabase/src/include/leveldb/env.h" #include "webkit/browser/fileapi/file_system_context.h" #include "webkit/browser/fileapi/<API key>.h" #include "webkit/browser/fileapi/isolated_context.h" #include "webkit/common/blob/scoped_file.h" #define FPL FILE_PATH_LITERAL using content::BrowserThread; using fileapi::FileSystemContext; using fileapi::FileSystemURL; using fileapi::FileSystemURLSet; // This tests <API key> behavior in multi-thread / // <API key> environment. // Basic combined tests (single-thread / <API key>) // that involve <API key> are also in // <API key>.cc. namespace sync_file_system { namespace { const char kOrigin1[] = "http://example.com"; const char kOrigin2[] = "http://chromium.org"; } class <API key> : public testing::Test { protected: <API key>() : thread_bundle_( content::<API key>::REAL_FILE_THREAD | content::<API key>::REAL_IO_THREAD), status_(<API key>), file_error_(base::File::FILE_ERROR_FAILED), <API key>(false), <API key>(false) {} virtual void SetUp() OVERRIDE { <API key>(); ASSERT_TRUE(dir_.CreateUniqueTempDir()); in_memory_env_.reset(leveldb::NewMemEnv(leveldb::Env::Default())); ui_task_runner_ = base::MessageLoop::current()->message_loop_proxy(); io_task_runner_ = BrowserThread::<API key>( BrowserThread::IO); file_task_runner_ = BrowserThread::<API key>( BrowserThread::IO); } virtual void TearDown() OVERRIDE { <API key>(); } void StartPrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, <API key>::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, webkit_blob::ScopedFile* snapshot) { ASSERT_TRUE(changes != NULL); ASSERT_FALSE(<API key>); status_ = SYNC_STATUS_UNKNOWN; <API key> = true; sync_context_->PrepareForSync( file_system_context, url, sync_mode, base::Bind(&<API key>::DidPrepareForSync, base::Unretained(this), metadata, changes, snapshot)); } SyncStatusCode PrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, <API key>::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, webkit_blob::ScopedFile* snapshot) { StartPrepareForSync(file_system_context, url, sync_mode, metadata, changes, snapshot); base::MessageLoop::current()->Run(); return status_; } base::Closure <API key>( FileSystemContext* file_system_context, const FileSystemURL& url, <API key>::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, webkit_blob::ScopedFile* snapshot) { return base::Bind(&<API key>::StartPrepareForSync, base::Unretained(this), base::Unretained(file_system_context), url, sync_mode, metadata, changes, snapshot); } void DidPrepareForSync(SyncFileMetadata* metadata_out, FileChangeList* changes_out, webkit_blob::ScopedFile* snapshot_out, SyncStatusCode status, const LocalFileSyncInfo& sync_file_info, webkit_blob::ScopedFile snapshot) { ASSERT_TRUE(ui_task_runner_-><API key>()); <API key> = false; status_ = status; *metadata_out = sync_file_info.metadata; *changes_out = sync_file_info.changes; if (snapshot_out) *snapshot_out = snapshot.Pass(); base::MessageLoop::current()->Quit(); } SyncStatusCode ApplyRemoteChange(FileSystemContext* file_system_context, const FileChange& change, const base::FilePath& local_path, const FileSystemURL& url, SyncFileType expected_file_type) { SCOPED_TRACE(testing::Message() << "ApplyChange for " << url.DebugString()); // First we should call PrepareForSync to disable writing. SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system_context, url, <API key>::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(expected_file_type, metadata.file_type); status_ = SYNC_STATUS_UNKNOWN; sync_context_->ApplyRemoteChange( file_system_context, change, local_path, url, base::Bind(&<API key>::<API key>, base::Unretained(this), make_scoped_refptr(file_system_context), url)); base::MessageLoop::current()->Run(); return status_; } void <API key>(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status) { status_ = status; sync_context_-><API key>( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::MessageLoop::QuitClosure()); } void <API key>(<API key>* file_system, const FileSystemURL& url) { ASSERT_TRUE(file_system != NULL); if (!io_task_runner_-><API key>()) { <API key> = false; ASSERT_TRUE(ui_task_runner_-><API key>()); io_task_runner_->PostTask( FROM_HERE, base::Bind(&<API key>::<API key>, base::Unretained(this), file_system, url)); return; } ASSERT_TRUE(io_task_runner_-><API key>()); file_error_ = base::File::FILE_ERROR_FAILED; file_system->operation_runner()->Truncate( url, 1, base::Bind(&<API key>::DidModifyFile, base::Unretained(this))); } base::File::Error <API key>() { while (!<API key>) base::MessageLoop::current()->RunUntilIdle(); return file_error_; } void DidModifyFile(base::File::Error error) { if (!ui_task_runner_-><API key>()) { ASSERT_TRUE(io_task_runner_-><API key>()); ui_task_runner_->PostTask( FROM_HERE, base::Bind(&<API key>::DidModifyFile, base::Unretained(this), error)); return; } ASSERT_TRUE(ui_task_runner_-><API key>()); file_error_ = error; <API key> = true; } void SimulateFinishSync(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status, <API key>::SyncMode sync_mode) { if (sync_mode == <API key>::SYNC_SNAPSHOT) { sync_context_-><API key>( file_system_context, url, status, base::Bind(&base::DoNothing)); } else { sync_context_-><API key>( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::Bind(&base::DoNothing)); } } void <API key>(<API key>::SyncMode sync_mode, SyncStatusCode <API key>) { <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.<API key>( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, NULL)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); // We should see the same set of changes. file_system.<API key>(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); SimulateFinishSync(file_system.file_system_context(), kFile, <API key>, sync_mode); file_system.<API key>(kFile, &changes); if (<API key> == SYNC_STATUS_OK) { // The change's cleared. EXPECT_TRUE(changes.empty()); } else { EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); } sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } void <API key>( <API key>::SyncMode sync_mode) { <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.<API key>( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; webkit_blob::ScopedFile snapshot; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, &snapshot)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(sync_mode == <API key>::SYNC_SNAPSHOT, !snapshot.path().empty()); // Tracker keeps same set of changes. file_system.<API key>(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); <API key>(&file_system, kFile); if (sync_mode == <API key>::SYNC_SNAPSHOT) { // Write should succeed. EXPECT_EQ(base::File::FILE_OK, <API key>()); } else { base::MessageLoop::current()->RunUntilIdle(); EXPECT_FALSE(<API key>); } SimulateFinishSync(file_system.file_system_context(), kFile, SYNC_STATUS_OK, sync_mode); EXPECT_EQ(base::File::FILE_OK, <API key>()); // Sync succeeded, but the other change that was made during or // after sync is recorded. file_system.<API key>(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } base::ScopedTempDir dir_; scoped_ptr<leveldb::Env> in_memory_env_; // These need to remain until the very end. content::<API key> thread_bundle_; scoped_refptr<base::<API key>> io_task_runner_; scoped_refptr<base::<API key>> ui_task_runner_; scoped_refptr<base::<API key>> file_task_runner_; scoped_refptr<<API key>> sync_context_; SyncStatusCode status_; base::File::Error file_error_; bool <API key>; bool <API key>; }; TEST_F(<API key>, <API key>) { sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); sync_context_->ShutdownOnUIThread(); } TEST_F(<API key>, <API key>) { <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system using |sync_context_|. EXPECT_EQ(SYNC_STATUS_OK, file_system.<API key>(sync_context_.get())); // Make sure everything's set up for file_system to be able to handle // syncable file system operations. EXPECT_TRUE(file_system.backend()->sync_context() != NULL); EXPECT_TRUE(file_system.backend()->change_tracker() != NULL); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Calling MaybeInitialize for the same context multiple times must be ok. EXPECT_EQ(SYNC_STATUS_OK, file_system.<API key>(sync_context_.get())); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Opens the file_system, perform some operation and see if the change tracker // correctly captures the change. EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL(file_system.URL("foo")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL)); FileSystemURLSet urls; file_system.<API key>(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL)); // Finishing the test. sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(<API key>, <API key>) { <API key> file_system1(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); <API key> file_system2(GURL(kOrigin2), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system1.SetUp(<API key>::QUOTA_ENABLED); file_system2.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system1 and file_system2. EXPECT_EQ(SYNC_STATUS_OK, file_system1.<API key>(sync_context_.get())); EXPECT_EQ(SYNC_STATUS_OK, file_system2.<API key>(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system1.OpenFileSystem()); EXPECT_EQ(base::File::FILE_OK, file_system2.OpenFileSystem()); const FileSystemURL kURL1(file_system1.URL("foo")); const FileSystemURL kURL2(file_system2.URL("bar")); // Creates a file in file_system1. EXPECT_EQ(base::File::FILE_OK, file_system1.CreateFile(kURL1)); // file_system1's tracker must have recorded the change. FileSystemURLSet urls; file_system1.<API key>(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL1)); // file_system1's tracker must have no change. urls.clear(); file_system2.<API key>(&urls); ASSERT_TRUE(urls.empty()); // Creates a directory in file_system2. EXPECT_EQ(base::File::FILE_OK, file_system2.CreateDirectory(kURL2)); // file_system1's tracker must have the change for kURL1 as before. urls.clear(); file_system1.<API key>(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL1)); // file_system2's tracker now must have the change for kURL2. urls.clear(); file_system2.<API key>(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL2)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system1.file_system_context(), kURL1, <API key>::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(0, metadata.size); changes.clear(); EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system2.file_system_context(), kURL2, <API key>::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(1U, changes.size()); EXPECT_FALSE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(<API key>, metadata.file_type); EXPECT_EQ(0, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system1.TearDown(); file_system2.TearDown(); } TEST_F(<API key>, <API key>) { <API key>(<API key>::SYNC_EXCLUSIVE, SYNC_STATUS_OK); } TEST_F(<API key>, <API key>) { <API key>(<API key>::SYNC_SNAPSHOT, SYNC_STATUS_OK); } TEST_F(<API key>, <API key>) { <API key>(<API key>::SYNC_EXCLUSIVE, SYNC_STATUS_FAILED); } TEST_F(<API key>, <API key>) { <API key>(<API key>::SYNC_SNAPSHOT, SYNC_STATUS_FAILED); } TEST_F(<API key>, <API key>) { <API key>(<API key>::SYNC_EXCLUSIVE); } TEST_F(<API key>, <API key>) { <API key>(<API key>::SYNC_SNAPSHOT); } // <API key>.<API key> is flaky on android. // It is also flaky on the TSAN v2 bots, and hangs other bots. TEST_F(<API key>, <API key>) { <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); EXPECT_EQ(SYNC_STATUS_OK, file_system.<API key>(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL1(file_system.URL("foo")); // Creates a file in file_system. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL1)); // Kick file write on IO thread. <API key>(&file_system, kURL1); // Until the operation finishes PrepareForSync should return BUSY error. SyncFileMetadata metadata; metadata.file_type = <API key>; FileChangeList changes; EXPECT_EQ(<API key>, PrepareForSync(file_system.file_system_context(), kURL1, <API key>::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); // Register PrepareForSync method to be invoked when kURL1 becomes // syncable. (Actually this may be done after all operations are done // on IO thread in this test.) metadata.file_type = <API key>; changes.clear(); sync_context_-><API key>( kURL1, <API key>(file_system.file_system_context(), kURL1, <API key>::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); // Wait for the completion. EXPECT_EQ(base::File::FILE_OK, <API key>()); // The PrepareForSync must have been started; wait until DidPrepareForSync // is done. base::MessageLoop::current()->Run(); ASSERT_FALSE(<API key>); // Now PrepareForSync should have run and returned OK. EXPECT_EQ(SYNC_STATUS_OK, status_); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(1, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } TEST_F(<API key>, <API key>) { <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.<API key>(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64 initial_usage = -1; int64 quota = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.<API key>(&urls); ASSERT_EQ(3U, urls.size()); ASSERT_TRUE(ContainsKey(urls, kFile)); ASSERT_TRUE(ContainsKey(urls, kDir)); ASSERT_TRUE(ContainsKey(urls, kChild)); for (FileSystemURLSet::iterator iter = urls.begin(); iter != urls.end(); ++iter) { file_system.<API key>(*iter); } // At this point the usage must be greater than the initial usage. int64 new_usage = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); // Now let's apply remote deletion changes. FileChange change(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kFile, SYNC_FILE_TYPE_FILE)); // The implementation doesn't check file type for deletion, and it must be ok // even if we don't know if the deletion change was for a file or a directory. change = FileChange(FileChange::FILE_CHANGE_DELETE, <API key>); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, <API key>)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::<API key>, file_system.FileExists(kFile)); EXPECT_EQ(base::File::<API key>, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::<API key>, file_system.FileExists(kChild)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.<API key>(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } TEST_F(<API key>, <API key>) { <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.<API key>(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64 initial_usage = -1; int64 quota = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // At this point the usage must be greater than the initial usage. int64 new_usage = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); const FileSystemURL kRoot(file_system.URL("")); // Now let's apply remote deletion changes for the root. FileChange change(FileChange::FILE_CHANGE_DELETE, <API key>); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kRoot, <API key>)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::<API key>, file_system.FileExists(kFile)); EXPECT_EQ(base::File::<API key>, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::<API key>, file_system.FileExists(kChild)); // All changes made for the previous creation must have been also reset. FileSystemURLSet urls; file_system.<API key>(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } TEST_F(<API key>, <API key>) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.<API key>(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile1(file_system.URL("file1")); const FileSystemURL kFile2(file_system.URL("file2")); const FileSystemURL kDir(file_system.URL("dir")); const char kTestFileData0[] = "0123456789"; const char kTestFileData1[] = "Lorem ipsum!"; const char kTestFileData2[] = "This is sample test data."; // Create kFile1 and populate it with kTestFileData0. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile1)); EXPECT_EQ(static_cast<int64>(arraysize(kTestFileData0) - 1), file_system.WriteString(kFile1, kTestFileData0)); // kFile2 and kDir are not there yet. EXPECT_EQ(base::File::<API key>, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::<API key>, file_system.DirectoryExists(kDir)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.<API key>(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kFile1)); file_system.<API key>(*urls.begin()); // Prepare temporary files which represent the remote file data. const base::FilePath kFilePath1(temp_dir.path().Append(FPL("file1"))); const base::FilePath kFilePath2(temp_dir.path().Append(FPL("file2"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData1) - 1), base::WriteFile(kFilePath1, kTestFileData1, arraysize(kTestFileData1) - 1)); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData2) - 1), base::WriteFile(kFilePath2, kTestFileData2, arraysize(kTestFileData2) - 1)); // Record the usage. int64 usage = -1, new_usage = -1; int64 quota = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&usage, &quota)); // Here in the local filesystem we have: // * kFile1 with kTestFileData0 // In the remote side let's assume we have: // * kFile1 with kTestFileData1 // * kFile2 with kTestFileData2 // * kDir // By calling ApplyChange's: // * kFile1 will be updated to have kTestFileData1 // * kFile2 will be created // * kDir will be created // Apply the remote change to kFile1 (which will update the file). FileChange change(FileChange::<API key>, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kFile1, SYNC_FILE_TYPE_FILE)); // Check if the usage has been increased by (kTestFileData1 - kTestFileData0). const int updated_size = arraysize(kTestFileData1) - arraysize(kTestFileData0); EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(updated_size, new_usage - usage); // Apply remote changes to kFile2 and kDir (should create a file and // directory respectively). // They are non-existent yet so their expected file type (the last // parameter of ApplyRemoteChange) are // <API key>. change = FileChange(FileChange::<API key>, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath2, kFile2, <API key>)); change = FileChange(FileChange::<API key>, <API key>); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, <API key>)); // Calling ApplyRemoteChange with different file type should be handled as // overwrite. change = FileChange(FileChange::<API key>, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, <API key>)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kDir)); change = FileChange(FileChange::<API key>, <API key>); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, SYNC_FILE_TYPE_FILE)); // Creating a file/directory must have increased the usage more than // the size of kTestFileData2. new_usage = usage; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, static_cast<int64>(usage + arraysize(kTestFileData2) - 1)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.<API key>(&urls); EXPECT_TRUE(urls.empty()); // Make sure all three files/directory exist. EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile1)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(<API key>, <API key>) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); <API key> file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(<API key>::QUOTA_ENABLED); sync_context_ = new <API key>( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.<API key>(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const char kTestFileData[] = "Lorem ipsum!"; const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kFile(file_system.URL("dir/file")); // Either kDir or kFile not exist yet. EXPECT_EQ(base::File::<API key>, file_system.FileExists(kDir)); EXPECT_EQ(base::File::<API key>, file_system.FileExists(kFile)); // Prepare a temporary file which represents remote file data. const base::FilePath kFilePath(temp_dir.path().Append(FPL("file"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData) - 1), base::WriteFile(kFilePath, kTestFileData, arraysize(kTestFileData) - 1)); // Calling ApplyChange's with kFilePath should create // kFile along with kDir. FileChange change(FileChange::<API key>, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath, kFile, <API key>)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. FileSystemURLSet urls; urls.clear(); file_system.<API key>(&urls); EXPECT_TRUE(urls.empty()); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } } // namespace sync_file_system
; (function ($) { var <API key> = function (element, options) { var element = $(element); var obj = this; // Merge options with defaults //var $settings = $.extend($.fn.bootstrapWizard.defaults, options || {}); var $settings = $.extend({}, $.fn.bootstrapWizard.defaults, options); var $activeTab = null; var $navigation = null; this.<API key> = function () { // Get the current active tab if (!$activeTab.length) { // Select first one $navigation.find('a:first').tab('show'); $activeTab = $navigation.find('li:first'); } // See if we currently in the first then disable the previous and last buttons if (obj.firstIndex() >= obj.currentIndex()) { $('li.previous', element).addClass('disabled'); } else { $('li.previous', element).removeClass('disabled'); } if (obj.currentIndex() >= obj.navigationLength()) { $('li.next', element).addClass('disabled'); } else { $('li.next', element).removeClass('disabled'); } if ($settings.onTabShow && typeof $settings.onTabShow === 'function' && $settings.onTabShow($activeTab, $navigation, obj.currentIndex()) === false) { return false; } }; this.next = function (e) { // If we clicked the last then dont activate this if (element.hasClass('last')) { return false; } if ($settings.onNext && typeof $settings.onNext === 'function' && $settings.onNext($activeTab, $navigation, obj.nextIndex()) === false) { return false; } // Did we click the last button $index = obj.nextIndex(); if ($index > obj.navigationLength()) { } else { $navigation.find('li:eq(' + $index + ') a').tab('show'); } }; this.previous = function (e) { // If we clicked the first then dont activate this if (element.hasClass('first')) { return false; } if ($settings.onPrevious && typeof $settings.onPrevious === 'function' && $settings.onPrevious($activeTab, $navigation, obj.previousIndex()) === false) { return false; } $index = obj.previousIndex(); if ($index < 0) { } else { $navigation.find('li:eq(' + $index + ') a').tab('show'); } }; this.first = function (e) { if ($settings.onFirst && typeof $settings.onFirst === 'function' && $settings.onFirst($activeTab, $navigation, obj.firstIndex()) === false) { return false; } // If the element is disabled then we won't do anything if (element.hasClass('disabled')) { return false; } $navigation.find('li:eq(0) a').tab('show'); }; this.last = function (e) { if ($settings.onLast && typeof $settings.onLast === 'function' && $settings.onLast($activeTab, $navigation, obj.lastIndex()) === false) { return false; } // If the element is disabled then we won't do anything if (element.hasClass('disabled')) { return false; } $navigation.find('li:eq(' + obj.navigationLength() + ') a').tab('show'); }; this.currentIndex = function () { return $navigation.find('li').index($activeTab); }; this.firstIndex = function () { return 0; }; this.lastIndex = function () { return obj.navigationLength(); }; this.getIndex = function (elem) { return $navigation.find('li').index(elem); }; this.nextIndex = function () { return $navigation.find('li').index($activeTab) + 1; }; this.previousIndex = function () { return $navigation.find('li').index($activeTab) - 1; }; this.navigationLength = function () { return $navigation.find('li').length - 1; }; this.activeTab = function () { return $activeTab; }; this.nextTab = function () { return $navigation.find('li:eq(' + (obj.currentIndex() + 1) + ')').length ? $navigation.find('li:eq(' + (obj.currentIndex() + 1) + ')') : null; }; this.previousTab = function () { if (obj.currentIndex() <= 0) { return null; } return $navigation.find('li:eq(' + parseInt(obj.currentIndex() - 1) + ')'); }; $navigation = element.find('ul:first', element); $activeTab = $navigation.find('li.active', element); if (!$navigation.hasClass($settings.class)) { $navigation.addClass($settings.class); } // Load onShow if ($settings.onInit && typeof $settings.onInit === 'function') { $settings.onInit($activeTab, $navigation, 0); } // Next/Previous events $($settings.nextSelector, element).bind('click', obj.next); $($settings.previousSelector, element).bind('click', obj.previous); $($settings.lastSelector, element).bind('click', obj.last); $($settings.firstSelector, element).bind('click', obj.first); // Load onShow if ($settings.onShow && typeof $settings.onShow === 'function') { $settings.onShow($activeTab, $navigation, obj.nextIndex()); } // Work the next/previous buttons obj.<API key>(); $('a[data-toggle="tab"]', element).on('click', function (e) { if ($settings.onTabClick && typeof $settings.onTabClick === 'function' && $settings.onTabClick($activeTab, $navigation, obj.currentIndex()) === false) { return false; } }); $('a[data-toggle="tab"]', element).on('show', function (e) { $element = $(e.target).parent(); // If it's disabled then do not change if ($element.hasClass('disabled')) { return false; } $activeTab = $element; // activated tab obj.<API key>(); }); }; $.fn.bootstrapWizard = function (options) { return this.each(function (index) { var element = $(this); // Return early if this element already has a plugin instance if (element.data('bootstrapWizard')) return; // pass options to plugin constructor var wizard = new <API key>(element, options); // Store plugin object in this element's data element.data('bootstrapWizard', wizard); }); }; // expose options $.fn.bootstrapWizard.defaults = { 'class':'nav nav-pills', 'nextSelector':'.wizard li.next', 'previousSelector':'.wizard li.previous', 'firstSelector':'.wizard li.first', 'lastSelector':'.wizard li.last', 'onShow':null, 'onInit':null, 'onNext':null, 'onPrevious':null, 'onLast':null, 'onFirst':null, 'onTabClick':null, 'onTabShow':null }; })(jQuery);
<!DOCTYPE html> <! Copyright (c) 2013 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. <link rel="import" href="/tracing/core/test_utils.html"> <link rel="import" href="/tracing/extras/importer/linux_perf/ftrace_importer.html"> <script> 'use strict'; tr.b.unittest.testSuite(function() { test('drmImport', function() { const lines = [ ' chrome-2465 [000] 71.653157: drm_vblank_event: crtc=0, seq=4233', ' <idle>-0 [000] 71.669851: drm_vblank_event: crtc=0, seq=4234' ]; const m = tr.c.TestUtils.newModelWithEvents([lines.join('\n')], { shiftWorldToZero: false }); assert.isFalse(m.hasImportWarnings); const threads = m.getAllThreads(); assert.strictEqual(threads.length, 1); const vblankThread = threads[0]; assert.strictEqual(vblankThread.name, 'drm_vblank'); assert.strictEqual(vblankThread.sliceGroup.length, 2); }); }); </script>
package jline.internal; import java.util.ArrayList; import java.util.List; import static jline.internal.Preconditions.checkNotNull; /** * Manages the JLine shutdown-hook thread and tasks to execute on shutdown. * * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> * @since 2.7 */ public class ShutdownHooks { public static final String JLINE_SHUTDOWNHOOK = "jline.shutdownhook"; private static final boolean enabled = Configuration.getBoolean(JLINE_SHUTDOWNHOOK, true); private static final List<Task> tasks = new ArrayList<Task>(); private static Thread hook; public static synchronized <T extends Task> T add(final T task) { checkNotNull(task); // If not enabled ignore if (!enabled) { Log.debug("Shutdown-hook is disabled; not installing: ", task); return task; } // Install the hook thread if needed if (hook == null) { hook = addHook(new Thread("JLine Shutdown Hook") { @Override public void run() { runTasks(); } }); } // Track the task Log.debug("Adding shutdown-hook task: ", task); tasks.add(task); return task; } private static synchronized void runTasks() { Log.debug("Running all shutdown-hook tasks"); // Iterate through copy of tasks list for (Task task : tasks.toArray(new Task[tasks.size()])) { Log.debug("Running task: ", task); try { task.run(); } catch (Throwable e) { Log.warn("Task failed", e); } } tasks.clear(); } private static Thread addHook(final Thread thread) { Log.debug("Registering shutdown-hook: ", thread); try { Runtime.getRuntime().addShutdownHook(thread); } catch (AbstractMethodError e) { // JDK 1.3+ only method. Bummer. Log.debug("Failed to register shutdown-hook", e); } return thread; } public static synchronized void remove(final Task task) { checkNotNull(task); // ignore if not enabled or hook never installed if (!enabled || hook == null) { return; } // Drop the task tasks.remove(task); // If there are no more tasks, then remove the hook thread if (tasks.isEmpty()) { removeHook(hook); hook = null; } } private static void removeHook(final Thread thread) { Log.debug("Removing shutdown-hook: ", thread); try { Runtime.getRuntime().removeShutdownHook(thread); } catch (AbstractMethodError e) { // JDK 1.3+ only method. Bummer. Log.debug("Failed to remove shutdown-hook", e); } catch (<API key> e) { // The VM is shutting down, not a big deal; ignore } } /** * Essentially a {@link Runnable} which allows running to throw an exception. */ public static interface Task { void run() throws Exception; } }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http: <head> <title>killerbee.openear.gps.gps'</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="killerbee-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="killerbee-module.html">Package&nbsp;killerbee</a> :: <a href="killerbee.openear-module.html">Package&nbsp;openear</a> :: <a href="killerbee.openear.gps-module.html">Package&nbsp;gps</a> :: Module&nbsp;gps' </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="killerbee.openear.gps.gps%27-module.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <h1 class="epydoc">Module gps'</h1><p class="nomargin-top"><span class="codelink"><a href="killerbee.openear.gps.gps%27-pysrc.html">source&nbsp;code</a></span></p> <a name="section-Classes"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Classes</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Classes" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="killerbee.openear.gps.gps%27.gps-class.html" class="summary-name">gps</a><br /> Client interface to a running gpsd instance. </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="killerbee.openear.gps.gps%27.gpsdata-class.html" class="summary-name">gpsdata</a><br /> Position, track, velocity and status information returned by a GPS. </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="killerbee.openear.gps.gps%27.gpsfix-class.html" class="summary-name">gpsfix</a> </td> </tr> </table> <a name="section-Functions"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Functions</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Functions" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="isnan"></a><span class="summary-sig-name">isnan</span>(<span class="summary-sig-arg">x</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="killerbee.openear.gps.gps%27-pysrc.html#isnan">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> </table> <a name="section-Variables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Variables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="AIS_SET"></a><span class="summary-name">AIS_SET</span> = <code title="268435456">268435456</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ALTITUDE_SET"></a><span class="summary-name">ALTITUDE_SET</span> = <code title="16">16</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ATTITUDE_SET"></a><span class="summary-name">ATTITUDE_SET</span> = <code title="16384">16384</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="AUXDATA_SET"></a><span class="summary-name">AUXDATA_SET</span> = <code title="2147483648">2147483648</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CLIMBERR_SET"></a><span class="summary-name">CLIMBERR_SET</span> = <code title="2097152">2097152</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CLIMB_SET"></a><span class="summary-name">CLIMB_SET</span> = <code title="128">128</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DEVICEID_SET"></a><span class="summary-name">DEVICEID_SET</span> = <code title="16777216">16777216</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DEVICELIST_SET"></a><span class="summary-name">DEVICELIST_SET</span> = <code title="8388608">8388608</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DEVICE_SET"></a><span class="summary-name">DEVICE_SET</span> = <code title="4194304">4194304</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DOP_SET"></a><span class="summary-name">DOP_SET</span> = <code title="1024">1024</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ERROR_SET"></a><span class="summary-name">ERROR_SET</span> = <code title="33554432">33554432</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="GPSD_PORT"></a><span class="summary-name">GPSD_PORT</span> = <code title="'2947'"><code class="variable-quote">'</code><code class="variable-string">2947</code><code class="variable-quote">'</code></code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="HERR_SET"></a><span class="summary-name">HERR_SET</span> = <code title="4096">4096</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="LATLON_SET"></a><span class="summary-name">LATLON_SET</span> = <code title="8">8</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MAXCHANNELS"></a><span class="summary-name">MAXCHANNELS</span> = <code title="20">20</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_2D"></a><span class="summary-name">MODE_2D</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_3D"></a><span class="summary-name">MODE_3D</span> = <code title="3">3</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_NO_FIX"></a><span class="summary-name">MODE_NO_FIX</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_SET"></a><span class="summary-name">MODE_SET</span> = <code title="512">512</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="NaN"></a><span class="summary-name">NaN</span> = <code title="nan">nan</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ONLINE_SET"></a><span class="summary-name">ONLINE_SET</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="PACKET_SET"></a><span class="summary-name">PACKET_SET</span> = <code title="536870912">536870912</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="POLICY_SET"></a><span class="summary-name">POLICY_SET</span> = <code title="32768">32768</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="RAW_SET"></a><span class="summary-name">RAW_SET</span> = <code title="131072">131072</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="RTCM2_SET"></a><span class="summary-name">RTCM2_SET</span> = <code title="67108864">67108864</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="RTCM3_SET"></a><span class="summary-name">RTCM3_SET</span> = <code title="134217728">134217728</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SATELLITE_SET"></a><span class="summary-name">SATELLITE_SET</span> = <code title="65536">65536</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="<API key>"></a><span class="summary-name"><API key></span> = <code title="nan">nan</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SPEEDERR_SET"></a><span class="summary-name">SPEEDERR_SET</span> = <code title="524288">524288</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SPEED_SET"></a><span class="summary-name">SPEED_SET</span> = <code title="32">32</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_DGPS_FIX"></a><span class="summary-name">STATUS_DGPS_FIX</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_FIX"></a><span class="summary-name">STATUS_FIX</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_NO_FIX"></a><span class="summary-name">STATUS_NO_FIX</span> = <code title="0">0</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_SET"></a><span class="summary-name">STATUS_SET</span> = <code title="256">256</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TIMERR_SET"></a><span class="summary-name">TIMERR_SET</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TIME_SET"></a><span class="summary-name">TIME_SET</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TRACKERR_SET"></a><span class="summary-name">TRACKERR_SET</span> = <code title="1048576">1048576</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TRACK_SET"></a><span class="summary-name">TRACK_SET</span> = <code title="64">64</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="UNION_SET"></a><span class="summary-name">UNION_SET</span> = <code title="511707136">511707136</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="USED_SET"></a><span class="summary-name">USED_SET</span> = <code title="262144">262144</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="VERR_SET"></a><span class="summary-name">VERR_SET</span> = <code title="8192">8192</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="VERSION_SET"></a><span class="summary-name">VERSION_SET</span> = <code title="2048">2048</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_DEVICE"></a><span class="summary-name">WATCH_DEVICE</span> = <code title="64">64</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_DISABLE"></a><span class="summary-name">WATCH_DISABLE</span> = <code title="0">0</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_ENABLE"></a><span class="summary-name">WATCH_ENABLE</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_JSON"></a><span class="summary-name">WATCH_JSON</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_NEWSTYLE"></a><span class="summary-name">WATCH_NEWSTYLE</span> = <code title="128">128</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_NMEA"></a><span class="summary-name">WATCH_NMEA</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_OLDSTYLE"></a><span class="summary-name">WATCH_OLDSTYLE</span> = <code title="65536">65536</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_RARE"></a><span class="summary-name">WATCH_RARE</span> = <code title="8">8</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_RAW"></a><span class="summary-name">WATCH_RAW</span> = <code title="16">16</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_SCALED"></a><span class="summary-name">WATCH_SCALED</span> = <code title="32">32</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="__package__"></a><span class="summary-name">__package__</span> = <code title="'killerbee.openear.gps'"><code class="variable-quote">'</code><code class="variable-string">killerbee.openear.gps</code><code class="variable-quote">'</code></code> </td> </tr> </table> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="killerbee-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Mon Dec 30 17:49:12 2013 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <! // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); </script> </body> </html>
#ifndef <API key> #define <API key> #include <string> #include "base/basictypes.h" #include "base/containers/hash_tables.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "gpu/gpu_export.h" #if defined(ANGLE_DX11) #include "third_party/angle_dx11/include/GLSLANG/ShaderLang.h" #else #include "third_party/angle/include/GLSLANG/ShaderLang.h" #endif namespace gpu { namespace gles2 { // Translates a GLSL ES 2.0 shader to desktop GLSL shader, or just // validates GLSL ES 2.0 shaders on a true GLSL ES implementation. class <API key> { public: enum <API key> { kGlsl, kGlslES }; enum <API key> { <API key>, <API key> }; struct VariableInfo { VariableInfo() : type(0), size(0) { } VariableInfo(int _type, int _size, std::string _name) : type(_type), size(_size), name(_name) { } bool operator==( const <API key>::VariableInfo& other) const { return type == other.type && size == other.size && strcmp(name.c_str(), other.name.c_str()) == 0; } int type; int size; std::string name; // name in the original shader source. }; // Mapping between variable name and info. typedef base::hash_map<std::string, VariableInfo> VariableMap; // Mapping between hashed name and original name. typedef base::hash_map<std::string, std::string> NameMap; // Initializes the translator. // Must be called once before using the translator object. virtual bool Init( ShShaderType shader_type, ShShaderSpec shader_spec, const ShBuiltInResources* resources, <API key> <API key>, <API key> <API key>) = 0; // Translates the given shader source. // Returns true if translation is successful, false otherwise. virtual bool Translate(const char* shader) = 0; // The following functions return results from the last translation. // The results are NULL/empty if the translation was unsuccessful. // A valid info-log is always returned irrespective of whether translation // was successful or not. virtual const char* translated_shader() const = 0; virtual const char* info_log() const = 0; virtual const VariableMap& attrib_map() const = 0; virtual const VariableMap& uniform_map() const = 0; virtual const NameMap& name_map() const = 0; // Return a string that is unique for a specfic set of options that would // possibly effect compilation. virtual std::string <API key>() const = 0; protected: virtual ~<API key>() {} }; // Implementation of <API key> class GPU_EXPORT ShaderTranslator : public base::RefCounted<ShaderTranslator>, NON_EXPORTED_BASE(public <API key>) { public: class DestructionObserver { public: DestructionObserver(); virtual ~DestructionObserver(); virtual void OnDestruct(ShaderTranslator* translator) = 0; private: <API key>(DestructionObserver); }; ShaderTranslator(); // Overridden from <API key>. virtual bool Init( ShShaderType shader_type, ShShaderSpec shader_spec, const ShBuiltInResources* resources, <API key> <API key>, <API key> <API key>) OVERRIDE; // Overridden from <API key>. virtual bool Translate(const char* shader) OVERRIDE; // Overridden from <API key>. virtual const char* translated_shader() const OVERRIDE; virtual const char* info_log() const OVERRIDE; // Overridden from <API key>. virtual const VariableMap& attrib_map() const OVERRIDE; virtual const VariableMap& uniform_map() const OVERRIDE; virtual const NameMap& name_map() const OVERRIDE; virtual std::string <API key>() const OVERRIDE; void <API key>(DestructionObserver* observer); void <API key>(DestructionObserver* observer); private: friend class base::RefCounted<ShaderTranslator>; virtual ~ShaderTranslator(); void ClearResults(); int GetCompileOptions() const; ShHandle compiler_; ShBuiltInResources compiler_options_; scoped_ptr<char[]> translated_shader_; scoped_ptr<char[]> info_log_; VariableMap attrib_map_; VariableMap uniform_map_; NameMap name_map_; bool <API key>; bool <API key>; ObserverList<DestructionObserver> <API key>; <API key>(ShaderTranslator); }; } // namespace gles2 } // namespace gpu #endif // <API key>
module FunIn3 where --The application of a function is replaced by the right-hand side of the definition, --with actual parameters replacing formals. --In this example, unfold 'addthree'. --This example aims to test the elimination of extra parentheses when unfolding --a function defintion. main :: Int -> Int main = \x -> case x of 1 -> 1 + main 0 0 ->((1 + 2) + 3) addthree :: Int -> Int -> Int -> Int addthree a b c = a + b + c
package scala.lms package internal import util.GraphUtil import scala.collection.mutable import java.util.IdentityHashMap import scala.collection.JavaConversions._ trait Scheduling { val IR: Expressions import IR._ def getUnsortedSchedule(scope: List[Stm])(result: Any): List[Stm] = { getSchedule(scope)(result, false) } // checks if a and b share at least one element. O(N^2), but with no allocation and possible early exit. def containsAny(a: List[Sym[Any]], b: List[Sym[Any]]): Boolean = { var aIter = a while (aIter.nonEmpty) { val aElem = aIter.head aIter = aIter.tail var bIter = b while (bIter.nonEmpty) { if (bIter.head eq aElem) return true bIter = bIter.tail } } false } //TBD: not used? def <API key>(scope: List[Stm])(result: Any): List[Stm] = { def deps(st: List[Sym[Any]]): List[Stm] = scope.filter(d => containsAny(st, d.lhs)) // scope.filter(d => (st intersect d.lhs).nonEmpty) def allSyms(r: Any) = syms(r) ++ softSyms(r) val xx = GraphUtil.<API key>[Stm](deps(allSyms(result)), t => deps(allSyms(t.rhs))) xx.foreach { x => if (x.length > 1) { printerr("warning: recursive schedule for result " + result + ": " + x) (new Exception) printStackTrace } } xx.flatten.reverse } //performance hotspot! //should be O(1) wrt 'scope' (nodes in graph), try to keep this as efficient as possible protected def <API key>(syms: List[Sym[Any]], cache: IdentityHashMap[Sym[Any], (Stm,Int)]): List[Stm] = { //syms.map(cache.get(_)).filter(_ ne null).distinct.sortBy(_._2).map(_._1) val sortedSet = new java.util.TreeSet[(Stm,Int)]( new java.util.Comparator[(Stm,Int)] { def compare(a:(Stm,Int), b:(Stm,Int)) = if (b._2 < a._2) -1 else if (b._2 == a._2) 0 else 1 } ) for (sym <- syms) { val stm = cache.get(sym) if (stm ne null) sortedSet.add(stm) } var res: List[Stm] = Nil val iter = sortedSet.iterator //return stms in the original order given by 'scope' while (iter.hasNext) { res ::= iter.next._1 } res } protected def buildScopeIndex(scope: List[Stm]): IdentityHashMap[Sym[Any], (Stm,Int)] = { val cache = new IdentityHashMap[Sym[Any], (Stm,Int)] var idx = 0 for (stm <- scope) { for (s <- stm.lhs) cache.put(s, (stm,idx)) //remember the original order of the stms idx += 1 } cache } def getSchedule(scope: List[Stm])(result: Any, sort: Boolean = true): List[Stm] = { val scopeIndex = buildScopeIndex(scope) val xx = GraphUtil.<API key>[Stm](<API key>(syms(result), scopeIndex), t => <API key>(syms(t.rhs), scopeIndex)) if (sort) xx.foreach { x => if (x.length > 1) { printerr("warning: recursive schedule for result " + result + ": " + x) (new Exception) printStackTrace } } xx.flatten.reverse } def getScheduleM(scope: List[Stm])(result: Any, cold: Boolean, hot: Boolean): List[Stm] = { def mysyms(st: Any) = { val db = symsFreq(st).groupBy(_._1).mapValues(_.map(_._2).sum).toList assert(syms(st).toSet == db.map(_._1).toSet, "different list of syms: "+syms(st)+"!="+db+" for "+st) if (cold && hot) db.map(_._1) else if (cold && !hot) db.withFilter(_._2 < 100.0).map(_._1) else if (!cold && hot) db.withFilter(_._2 > 0.75).map(_._1) else db.withFilter(p=>p._2 > 0.75 && p._2 < 100.0).map(_._1) } val scopeIndex = buildScopeIndex(scope) GraphUtil.<API key>[Stm](<API key>(mysyms(result), scopeIndex), t => <API key>(mysyms(t.rhs), scopeIndex)).flatten.reverse } /** begin performance hotspot **/ /* for each symbol s in sts, find all statements that depend on it. we need to stop when we reach the statement where s is bound. it would be tempting to do only one scc call but then we mix up the locations where different symbols are bound. */ def <API key>(scope: List[Stm])(sts: List[Sym[Any]]): List[Stm] = { if (sts.isEmpty) return Nil /* precompute: s => all d in scope such that: d.lhs contains s || syms(d.rhs).contains(s) st => all d in scope such that: boundSyms(d.rhs) contains st */ //type IdentityHashMap[K,V] = HashMap[K,V] // IdentityHashMap appears faster than scala.collection.mutable.HashMap here (based on perf. testing) // possible improvement: use an integer hashmap that works directly with sym ids val lhsCache = new IdentityHashMap[Sym[Any], List[Stm]]() val symsCache = new IdentityHashMap[Sym[Any], List[Stm]]() val boundSymsCache = new IdentityHashMap[Sym[Any], List[Stm]]() //val boundSymsCache = new IdentityHashMap[Sym[Any], Set[Stm]]() def infix_getOrElse[K,V](map: IdentityHashMap[K, V], s: K, f: => V) = { var res = map.get(s) //map(s) if (res == null) res = f res } def putDef(map: IdentityHashMap[Sym[Any], List[Stm]], s: Sym[Any], d: Stm): Unit = { var res = map.get(s) //map(s) if (res == null) res = Nil //map.getOrElse(s, Nil) match { res match { case `d`::ds => case ds => map.update(s,d::ds) //map.put(s,d::ds) } } def putDefSet(map: IdentityHashMap[Sym[Any], Set[Stm]], s: Sym[Any], d: Stm): Unit = { var res = map(s) //map.get(s) if (res == null) { res = Set[Stm]() map.update(s,res) //map.put(s,res) } res += d } for (d <- scope) { d.lhs.foreach(s => putDef(lhsCache, s, d)) syms(d.rhs).foreach(s => putDef(symsCache, s, d)) boundSyms(d.rhs).foreach(st => putDef(boundSymsCache, st, d)) tunnelSyms(d.rhs).foreach(st => putDef(boundSymsCache, st, d)) // treat tunnel like bound } val A = loop { s1 => ... val B = sum { s2 => ... val y = s2 + s1; .../* use y */ ... } } /* optimization: traverse syms by ascending id. if sym s1 is used by s2, do not evaluate further uses of s2 because they are already there. CAVEAT: TRANSFORMERS !!! assumption: if s2 uses s1, the scope of s2 is completely included in s1's scope: once we reach y the second time (from s2) we can stop, because the uses of y have been tracked up to A, which includes all of B */ val seen = new mutable.HashSet[Sym[Any]] def getDepStuff(st: Sym[Any]) = { // could also precalculate uses, but computing all combinations eagerly is also expensive def uses(s: Sym[Any]): List[Stm] = if (seen(s)) Nil else { //seen += s lhsCache.getOrElse(s,Nil) ::: symsCache.getOrElse(s,Nil) filterNot (boundSymsCache.getOrElse(st, Nil) contains _) } GraphUtil.<API key>[Stm]( uses(st), t => t.lhs flatMap uses ).flatten } /* reference impl:*/ val res = sts.flatMap(getDepStuff).distinct /*if (sts.contains(Sym(1064))) { println("dep on x1064:") res.foreach { r => println(" " + r) } }*/ res // CAVEAT: TRANSFORMERS !!! see CloseWorldRestage app in Delite //sts.sortBy(_.id).flatMap(getDepStuff) } /** end performance hotspot **/ }
// t0288.cc // "ambiguous function template instantiation" // 2005-08-03: This appears to be fixed by the switch to // the new mtype module. namespace std { template < class _CharT > struct char_traits; } typedef int ptrdiff_t; extern "C" { typedef struct __locale_struct { } *__locale_t; }; typedef struct __pthread_attr_s { } <API key>; namespace std { typedef ptrdiff_t streamsize; template < typename _CharT, typename _Traits = char_traits < _CharT > >class basic_ios; template < typename _CharT, typename _Traits = char_traits < _CharT > >class basic_streambuf; } extern "C++" { namespace std { class exception { }; } } namespace std { template < typename _CharT, typename _Traits > class basic_streambuf { public:typedef _CharT char_type; typedef _Traits traits_type; typedef basic_streambuf < char_type, traits_type > __streambuf_type; friend streamsize __copy_streambufs <> (basic_ios < char_type, traits_type > &__ios, __streambuf_type * __sbin, __streambuf_type * __sbout); }; template < typename _CharT, typename _Traits > streamsize __copy_streambufs (basic_ios < _CharT, _Traits > &__ios, basic_streambuf < _CharT, _Traits > *__sbin, basic_streambuf < _CharT, _Traits > *__sbout) { try { } catch (exception & __fail) { } } extern template streamsize __copy_streambufs (basic_ios < wchar_t > &, basic_streambuf < wchar_t > *, basic_streambuf < wchar_t > *); }
#include "device/common/nn_workload_data.h" #include "device/cpu/api_internal/<API key>.h" #include "<API key>.h" #include <immintrin.h> #include <string.h> #include <thread> #include <vector> #include "device/cpu/api_internal/data_helper.h" // NN_CODE_UNREACHABLE signal to supporting compiler that specific location in code cannot be reached #if defined _MSC_VER # define NN_UNREACHABLE_CODE __assume(0) #endif #if defined __GNUC__ # if (__GNUC__ * 100 + __GNUC_MINOR__) >= 405 # define NN_UNREACHABLE_CODE <API key>() # else # define NN_UNREACHABLE_CODE # endif #endif #if defined __clang__ # if __has_builtin(<API key>) # define NN_UNREACHABLE_CODE <API key>() # else # define NN_UNREACHABLE_CODE # endif #endif // SIMD width for this implementation const auto C_simd_width = sizeof(__m256) / sizeof(float); static const auto C_max_acc = 12u; static const auto C_batch_size = C_simd_width; static const auto C_data_stride = C_batch_size * C_max_acc; namespace layer { // forward implementation template<uint32_t T_SIZE> void <API key>( float* &input_ptr, float* &output_ptr, const __m256 coeff_a, const __m256 coeff_b) { // We are not using table of registers and unroll pragmas // due to compiler which have issues with register allocation // and needs special, obvious treatment. Template immediate // arguments matching will remove all conditions in this code. __m256 acc0, acc1, acc2, acc3, acc4, acc5, acc6, acc7, acc8, acc9, acc10, acc11, acc12, acc13, acc14, acc15; // Load inputs. if (T_SIZE >= 1) acc0 = _mm256_loadu_ps(input_ptr + 0 * C_batch_size); if (T_SIZE >= 2) acc1 = _mm256_loadu_ps(input_ptr + 1 * C_batch_size); if (T_SIZE >= 3) acc2 = _mm256_loadu_ps(input_ptr + 2 * C_batch_size); if (T_SIZE >= 4) acc3 = _mm256_loadu_ps(input_ptr + 3 * C_batch_size); if (T_SIZE >= 5) acc4 = _mm256_loadu_ps(input_ptr + 4 * C_batch_size); if (T_SIZE >= 6) acc5 = _mm256_loadu_ps(input_ptr + 5 * C_batch_size); if (T_SIZE >= 7) acc6 = _mm256_loadu_ps(input_ptr + 6 * C_batch_size); if (T_SIZE >= 8) acc7 = _mm256_loadu_ps(input_ptr + 7 * C_batch_size); if (T_SIZE >= 9) acc8 = _mm256_loadu_ps(input_ptr + 8 * C_batch_size); if (T_SIZE >= 10) acc9 = _mm256_loadu_ps(input_ptr + 9 * C_batch_size); if (T_SIZE >= 11) acc10 = _mm256_loadu_ps(input_ptr + 10 * C_batch_size); if (T_SIZE >= 12) acc11 = _mm256_loadu_ps(input_ptr + 11 * C_batch_size); if (T_SIZE >= 13) acc12 = _mm256_loadu_ps(input_ptr + 12 * C_batch_size); if (T_SIZE >= 14) acc13 = _mm256_loadu_ps(input_ptr + 13 * C_batch_size); if (T_SIZE >= 15) acc14 = _mm256_loadu_ps(input_ptr + 14 * C_batch_size); // Perform a*x + b if (T_SIZE >= 1) acc0 = _mm256_fmadd_ps(coeff_a, acc0, coeff_b); if (T_SIZE >= 2) acc1 = _mm256_fmadd_ps(coeff_a, acc1, coeff_b); if (T_SIZE >= 3) acc2 = _mm256_fmadd_ps(coeff_a, acc2, coeff_b); if (T_SIZE >= 4) acc3 = _mm256_fmadd_ps(coeff_a, acc3, coeff_b); if (T_SIZE >= 5) acc4 = _mm256_fmadd_ps(coeff_a, acc4, coeff_b); if (T_SIZE >= 6) acc5 = _mm256_fmadd_ps(coeff_a, acc5, coeff_b); if (T_SIZE >= 7) acc6 = _mm256_fmadd_ps(coeff_a, acc6, coeff_b); if (T_SIZE >= 8) acc7 = _mm256_fmadd_ps(coeff_a, acc7, coeff_b); if (T_SIZE >= 9) acc8 = _mm256_fmadd_ps(coeff_a, acc8, coeff_b); if (T_SIZE >= 10) acc9 = _mm256_fmadd_ps(coeff_a, acc9, coeff_b); if (T_SIZE >= 11) acc10 = _mm256_fmadd_ps(coeff_a, acc10, coeff_b); if (T_SIZE >= 12) acc11 = _mm256_fmadd_ps(coeff_a, acc11, coeff_b); if (T_SIZE >= 13) acc12 = _mm256_fmadd_ps(coeff_a, acc12, coeff_b); if (T_SIZE >= 14) acc13 = _mm256_fmadd_ps(coeff_a, acc13, coeff_b); if (T_SIZE >= 15) acc14 = _mm256_fmadd_ps(coeff_a, acc14, coeff_b); // Store results. if (T_SIZE >= 1) _mm256_storeu_ps(output_ptr + 0 * C_batch_size, acc0); if (T_SIZE >= 2) _mm256_storeu_ps(output_ptr + 1 * C_batch_size, acc1); if (T_SIZE >= 3) _mm256_storeu_ps(output_ptr + 2 * C_batch_size, acc2); if (T_SIZE >= 4) _mm256_storeu_ps(output_ptr + 3 * C_batch_size, acc3); if (T_SIZE >= 5) _mm256_storeu_ps(output_ptr + 4 * C_batch_size, acc4); if (T_SIZE >= 6) _mm256_storeu_ps(output_ptr + 5 * C_batch_size, acc5); if (T_SIZE >= 7) _mm256_storeu_ps(output_ptr + 6 * C_batch_size, acc6); if (T_SIZE >= 8) _mm256_storeu_ps(output_ptr + 7 * C_batch_size, acc7); if (T_SIZE >= 9) _mm256_storeu_ps(output_ptr + 8 * C_batch_size, acc8); if (T_SIZE >= 10) _mm256_storeu_ps(output_ptr + 9 * C_batch_size, acc9); if (T_SIZE >= 11) _mm256_storeu_ps(output_ptr + 10 * C_batch_size, acc10); if (T_SIZE >= 12) _mm256_storeu_ps(output_ptr + 11 * C_batch_size, acc11); if (T_SIZE >= 13) _mm256_storeu_ps(output_ptr + 12 * C_batch_size, acc12); if (T_SIZE >= 14) _mm256_storeu_ps(output_ptr + 13 * C_batch_size, acc13); if (T_SIZE >= 15) _mm256_storeu_ps(output_ptr + 14 * C_batch_size, acc14); input_ptr += T_SIZE*C_batch_size; output_ptr += T_SIZE*C_batch_size; } void <API key>::<API key>( const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) { const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x]; const auto output_width = output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1; const auto num_full_blocks = output_width / C_max_acc; const auto partial_block_size = output_width % C_max_acc; const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x] * C_batch_size; const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x] * C_batch_size; auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset]; auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset]; const __m256 coeff_a = _mm256_set1_ps(alpha); const __m256 coeff_b = _mm256_set1_ps(beta); { for (auto block = 0u; block < num_full_blocks; ++block) { // Run computation. <API key><C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b); } switch (partial_block_size) { case 0: break; case 1: <API key>< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 2: <API key>< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 3: <API key>< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 4: <API key>< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 5: <API key>< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 6: <API key>< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 7: <API key>< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 8: <API key>< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 9: <API key>< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 10: <API key><10>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 11: <API key><11>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 12: <API key><12>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 13: <API key><13>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 14: <API key><14>(input_buffer, output_buffer, coeff_a, coeff_b); break; default: NN_UNREACHABLE_CODE; } } } void <API key>::<API key>( const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) { const auto BatchSize = output_view->parent->lengths.t[NN_DATA_COORD_n]; const auto NoBatches = BatchSize / C_batch_size; const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x] * BatchSize; const auto output_width = (output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1) * BatchSize; const auto num_full_blocks = (output_width / C_simd_width) / C_max_acc; const auto partial_block_size = (output_width / C_simd_width ) % C_max_acc; const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x] * BatchSize; const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x] * BatchSize; //for (auto itrB = 0; itrB < BatchSize / C_batch_size; ++itrB) { auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset]; auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset]; const __m256 coeff_a = _mm256_set1_ps(alpha); const __m256 coeff_b = _mm256_set1_ps(beta); for (auto block = 0u; block < num_full_blocks; ++block) { // Run computation. <API key><C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b); } switch (partial_block_size) { case 0: break; case 1: <API key>< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 2: <API key>< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 3: <API key>< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 4: <API key>< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 5: <API key>< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 6: <API key>< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 7: <API key>< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 8: <API key>< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 9: <API key>< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 10: <API key><10>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 11: <API key><11>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 12: <API key><12>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 13: <API key><13>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 14: <API key><14>(input_buffer, output_buffer, coeff_a, coeff_b); break; default: NN_UNREACHABLE_CODE; } } } template<uint32_t T_NUM_ITERATIONS> void <API key>( float* &input_ptr, float* &output_ptr, const float coeff_a, const float coeff_b) { for (auto iteration = 0u; iteration < T_NUM_ITERATIONS; ++iteration) { *output_ptr = (*input_ptr) * coeff_a + coeff_b; ++input_ptr; ++output_ptr; } } void <API key>::<API key>( const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) { const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x]; const auto output_width = output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1; const auto num_full_blocks = output_width / C_data_stride; const auto partial_block_size = (output_width / C_simd_width) % C_max_acc; const auto subsimd_block_size = output_width % C_simd_width; const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x]; const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x]; auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset]; auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset]; const __m256 coeff_a = _mm256_set1_ps(alpha); const __m256 coeff_b = _mm256_set1_ps(beta); for (auto block = 0u; block < num_full_blocks; ++block) { // Run computation. <API key><C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b); } switch (partial_block_size) { case 0: break; case 1: <API key>< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 2: <API key>< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 3: <API key>< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 4: <API key>< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 5: <API key>< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 6: <API key>< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 7: <API key>< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 8: <API key>< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 9: <API key>< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 10: <API key><10>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 11: <API key><11>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 12: <API key><12>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 13: <API key><13>(input_buffer, output_buffer, coeff_a, coeff_b); break; case 14: <API key><14>(input_buffer, output_buffer, coeff_a, coeff_b); break; default: NN_UNREACHABLE_CODE; } switch (subsimd_block_size) { case 0: break; case 1: <API key><1>(input_buffer, output_buffer, alpha, beta); break; case 2: <API key><2>(input_buffer, output_buffer, alpha, beta); break; case 3: <API key><3>(input_buffer, output_buffer, alpha, beta); break; case 4: <API key><4>(input_buffer, output_buffer, alpha, beta); break; case 5: <API key><5>(input_buffer, output_buffer, alpha, beta); break; case 6: <API key><6>(input_buffer, output_buffer, alpha, beta); break; case 7: <API key><7>(input_buffer, output_buffer, alpha, beta); break; default: NN_UNREACHABLE_CODE; } } void <API key>::<API key>( const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) { auto batch_size = input_view->parent->lengths.t[NN_DATA_COORD_n]; switch (batch_size) { case 1: <API key>(input_view, output_view); break; case 8: <API key>(input_view, output_view); break; case 16: case 24: case 32: case 48: <API key>(input_view, output_view); break; default: break; } } struct <API key> { <API key> *primitive; const nn::workload_data<float> *input_view; nn::workload_data<float> *output_view; }; void <API key>( void* void_handle) { auto handle = reinterpret_cast<<API key> *>(void_handle); handle->primitive-><API key>(handle->input_view, handle->output_view); } void <API key>::<API key>( const nn::workload_data<float> *input, nn::workload_data<float> *output) { auto <API key> = std::min(static_cast<decltype(device->thread_pool.get_num_threads())>(18), device->thread_pool.get_num_threads()); const auto item_view_length = output->view_end.t[NN_DATA_COORD_x] - output->view_begin.t[NN_DATA_COORD_x] + 1; const auto items_per_thread = item_view_length / <API key>; const auto items_modulo = item_view_length % <API key>; // Check if we have enough data to cover all threads. if (items_per_thread == 0 && items_modulo < 2) { // Its tiny data - just do it single threaded way. <API key>(input, output); } else { // Not all threads will be used. if (items_per_thread == 0) <API key> = items_modulo; // Full cores utilization version. std::vector<<API key>> request_handles(<API key>); std::vector<const nn::workload_data<float> *> input_views(<API key>); std::vector<nn::workload_data<float> *> output_views(<API key>); uint32_t* thread_items_sums = static_cast<uint32_t*>(alloca(<API key> * sizeof(uint32_t))); if (thread_items_sums == nullptr) throw std::bad_alloc(); // Distribute elements more evenly. auto elements_left = items_modulo; for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { thread_items_sums[thread_id] = items_per_thread; if (elements_left) { ++thread_items_sums[thread_id]; --elements_left; } } // Now create table of thread sums. auto thread_sum = 0u; for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { thread_sum += thread_items_sums[thread_id]; thread_items_sums[thread_id] = thread_sum; } // Fill slave work items. for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { auto work_begin = 0u; if (thread_id > 0u) work_begin = thread_items_sums[thread_id - 1]; auto work_end = thread_items_sums[thread_id] - 1; // Replace nn_workload_datas pointers with views. <API key> nn_view_begin = { 0, work_begin, 0, 0, 0, 0 }; <API key> nn_view_end = { input->get_length(NN_DATA_COORD_n) - 1, work_end, input->get_length(NN_DATA_COORD_y) - 1, input->get_length(NN_DATA_COORD_z) - 1, input->get_length(NN_DATA_COORD_p) - 1, input->get_length(NN_DATA_COORD_q) - 1 }; input_views[thread_id] = new nn::workload_data<float>(*input, nn_view_begin, nn_view_end); output_views[thread_id] = new nn::workload_data<float>(*output, nn_view_begin, nn_view_end); } // Run threads. std::vector<<API key>> job(<API key>); for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { request_handles[thread_id].primitive = this; request_handles[thread_id].input_view = input_views[thread_id]; request_handles[thread_id].output_view = output_views[thread_id]; job[thread_id].callback = <API key>; job[thread_id].request_handle = &request_handles[thread_id]; } // Wait for all sub threads. device->thread_pool.push_job(job); // Cleanup dynamic memory. for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { delete input_views[thread_id]; delete output_views[thread_id]; } } } void <API key>::forward(const nn::workload_data<float> *input, nn::workload_data<float> *output) { <API key> in_out_view_coords = { input->parent->lengths.t[NN_DATA_COORD_n], input->parent->buffer_size / static_cast<uint32_t>(sizeof(float)) / input->parent->lengths.t[NN_DATA_COORD_n], 1, 1, 1, 1 }; <API key> in_out_view_layout = nn::workload_data<float>::layout.nxyzpq; nn::workload_data<float>* input_view = new nn::workload_data<float>(<API key>, input->parent->data_buffer, in_out_view_coords, in_out_view_layout); nn::workload_data<float>* output_view = new nn::workload_data<float>(<API key>, output->parent->data_buffer, in_out_view_coords, in_out_view_layout); if (device->thread_pool.get_num_threads() > 1) { <API key>(input_view, output_view); } else { <API key>(input_view, output_view); } delete output_view; delete input_view; } void <API key>::forward(const std::vector<const nn_workload_data_t *> &inputs, const std::vector<const nn_workload_data_t *> &parameters, const std::vector<nn_workload_data_t *> &outputs) { assert(inputs.size() == 1); assert(parameters.size() == 0); assert(outputs.size() == 1); forward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]), reinterpret_cast<nn::workload_data<float> *>(outputs[0])); } __m256 <API key>(__m256 arg) { __m256i e = _mm256_slli_epi32( _mm256_sub_epi32( _mm256_and_si256( _mm256_castps_si256(arg), _mm256_set1_epi32(0x7f800000)), _mm256_set1_epi32(0x3f800000)), 1); __m256 p0 = _mm256_castsi256_ps( _mm256_srli_epi32( _mm256_add_epi32( _mm256_mullo_epi32( _mm256_srai_epi32( _mm256_and_si256( e, _mm256_set1_epi32(0xfc000000)), 2), _mm256_set1_epi32(-3)), _mm256_set1_epi32(0x7f000000)), 1)); __m256 p1 = _mm256_blendv_ps( _mm256_set1_ps(0.<API key>), _mm256_set1_ps(1.0f), _mm256_castsi256_ps( _mm256_cmpeq_epi32( _mm256_and_si256( e, _mm256_set1_epi32(1<<24)), _mm256_set1_epi32(0)))); __m256 p2 = _mm256_blendv_ps( _mm256_set1_ps(0.<API key>), _mm256_set1_ps(1.0f), _mm256_castsi256_ps( _mm256_cmpeq_epi32( _mm256_and_si256( e, _mm256_set1_epi32(2<<24)), _mm256_set1_epi32(0)))); arg = _mm256_castsi256_ps( _mm256_or_si256( _mm256_and_si256( _mm256_castps_si256(arg), _mm256_set1_epi32(0x007fffff)), _mm256_set1_epi32(0x3f800000))); __m256 intermediate_result; intermediate_result = _mm256_fmadd_ps(arg, _mm256_set1_ps(-0.06251362156237f), _mm256_set1_ps(0.56657226995864f)); intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(-2.12314847503624f)); intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(4.22879355263332f)); intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(-4.79039952143706f)); intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(3.18069569544757f)); intermediate_result = _mm256_mul_ps( _mm256_mul_ps( p0, p1), _mm256_mul_ps( p2, intermediate_result)); return intermediate_result; } void <API key>::<API key>(const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) { const auto input_column_size = input_view->parent->lengths.t[NN_DATA_COORD_z]; const auto input_row_size = input_view->parent->lengths.t[NN_DATA_COORD_x] * input_column_size; const auto input_batch_size = input_view->parent->lengths.t[NN_DATA_COORD_y] * input_row_size; const auto output_column_size = output_view->parent->lengths.t[NN_DATA_COORD_z]; const auto output_row_size = output_view->parent->lengths.t[NN_DATA_COORD_x] * output_column_size; const auto output_batch_size = output_view->parent->lengths.t[NN_DATA_COORD_y] * output_row_size; auto input_buffer = static_cast<float*>(input_view->parent->data_buffer); auto output_buffer = static_cast<float*>(output_view->parent->data_buffer); // Const data. const uint32_t permutation_mask[8] = { 1, 2, 3, 4, 5, 6, 7, 0 }; uint32_t first_load_mask[8] = { 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000 }; uint32_t last_load_mask[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; const auto neighbourhood = n / 2; for (uint32_t neighbour = 0; neighbour < neighbourhood; ++neighbour) { first_load_mask[neighbour] ^= 0x80000000; last_load_mask[neighbour] ^= 0x80000000; } // Permuters and masks. const __m256i forward_permuter = _mm256_loadu_si256((__m256i*)permutation_mask); const __m256i first_masker = _mm256_loadu_si256((__m256i*)first_load_mask); const __m256i last_masker = _mm256_loadu_si256((__m256i*)last_load_mask); for (uint32_t batch = input_view->view_begin.t[NN_DATA_COORD_n]; batch <= input_view->view_end.t[NN_DATA_COORD_n]; ++batch) { for (uint32_t row = input_view->view_begin.t[NN_DATA_COORD_y], out_row = output_view->view_begin.t[NN_DATA_COORD_y]; row <= input_view->view_end.t[NN_DATA_COORD_y]; ++row, ++out_row) { for (uint32_t column = input_view->view_begin.t[NN_DATA_COORD_x], out_column = output_view->view_begin.t[NN_DATA_COORD_x]; column <= input_view->view_end.t[NN_DATA_COORD_x]; ++column, ++out_column) { const auto input_address = &input_buffer[batch*input_batch_size + row*input_row_size + column*input_column_size]; const auto output_address = &output_buffer[batch*output_batch_size + out_row*output_row_size + out_column*output_column_size]; // Prepare first data chunk. __m256 source_tmp = _mm256_maskload_ps(input_address - neighbourhood, first_masker); source_tmp = _mm256_mul_ps(source_tmp, source_tmp); for (uint32_t feature_map = input_view->view_begin.t[NN_DATA_COORD_z], out_feature_map = output_view->view_begin.t[NN_DATA_COORD_z]; feature_map <= input_view->view_end.t[NN_DATA_COORD_z]; feature_map += C_simd_width, out_feature_map += C_simd_width) { // Initialize accumulator. __m256 acc = _mm256_setzero_ps(); // Move previous saved chunk to first and load new one as a next. __m256 source_first = source_tmp; __m256 source_second = (feature_map + C_simd_width <= input_view->view_end.t[NN_DATA_COORD_z]) ? _mm256_loadu_ps(input_address + feature_map - neighbourhood + C_simd_width) : _mm256_maskload_ps(input_address + feature_map - neighbourhood + C_simd_width, last_masker); // Square of new chunk and save for next iteration. source_tmp = source_second = _mm256_mul_ps(source_second, source_second); // Required for final computation. __m256 source_raw = _mm256_loadu_ps(input_address + feature_map); // Forward permute - five times. for (int i = 0; i < n; ++i) { acc = _mm256_add_ps(source_first, acc); source_first = <API key>(source_first, forward_permuter); source_second = <API key>(source_second, forward_permuter); source_first = _mm256_blend_ps(source_first, source_second, 0x80); } // Do k + alpha * acc. acc = _mm256_fmadd_ps(acc, _mm256_set1_ps(alpha), _mm256_set1_ps(k)); // Magic happens here. (acc^-0.75) acc = <API key>(acc); // Multiply with input data. acc = _mm256_mul_ps(acc, source_raw); // Save data. _mm256_storeu_ps(output_address + out_feature_map, acc); } } } } } struct <API key> { <API key> *primitive; const nn::workload_data<float> *input_view; nn::workload_data<float> *output_view; }; struct <API key> { <API key> *primitive; const nn::workload_data<float> *forward_input; const nn::workload_data<float> *forward_output; const nn::workload_data<float> *backward_input; nn::workload_data<float> *backward_output; }; void <API key>( void* void_handle) { auto handle = reinterpret_cast<<API key> *>(void_handle); handle->primitive-><API key>(handle->input_view, handle->output_view); } void <API key>( void* void_handle) { auto handle = reinterpret_cast<<API key> *>(void_handle); handle->primitive->backward(handle->forward_input, handle->forward_output, handle->backward_input, handle->backward_output); } void <API key>::dispatch_backward( const nn::workload_data<float> *forward_input, const nn::workload_data<float> *forward_output, const nn::workload_data<float> *backward_input, nn::workload_data<float> *backward_output) { const auto num_batch_items = (backward_output->view_end.t[NN_DATA_COORD_n] - backward_output->view_begin.t[NN_DATA_COORD_n] + 1); const auto total_workers = num_batch_items; if (device->thread_pool.get_num_threads() < 2 || total_workers < 2) { // Its tiny data or there is only one thread available - just do it singlethreaded way. backward(forward_input, forward_output, backward_input, backward_output); } else { // Full cores utilization version. std::vector<nn::workload_data<float> *> <API key>(total_workers); // Fill slave work items. for (auto batch_item = 0u; batch_item < num_batch_items; ++batch_item) { auto item_in_pool = batch_item; // Replace nn_workload_datas pointers with views. <API key> output_view_begin = { batch_item, 0, 0, 0, 0, 0 }; <API key> output_view_end = { batch_item, backward_output->get_length(NN_DATA_COORD_x) - 1, backward_output->get_length(NN_DATA_COORD_y) - 1, backward_output->get_length(NN_DATA_COORD_z) - 1, backward_output->get_length(NN_DATA_COORD_p) - 1, backward_output->get_length(NN_DATA_COORD_q) - 1 }; <API key>[item_in_pool] = new nn::workload_data<float>(*backward_output, output_view_begin, output_view_end); } // Run threads. std::vector<<API key>> job(total_workers); std::vector<<API key>> request_handles(total_workers); for (auto item_in_pool = 0u; item_in_pool < total_workers; ++item_in_pool) { request_handles[item_in_pool].primitive = this; request_handles[item_in_pool].forward_input = forward_input; request_handles[item_in_pool].forward_output = forward_output; request_handles[item_in_pool].backward_input = backward_input; request_handles[item_in_pool].backward_output = <API key>[item_in_pool]; job[item_in_pool].callback = <API key>; job[item_in_pool].request_handle = &request_handles[item_in_pool]; } // Wait for all sub threads. device->thread_pool.push_job(job); // Cleanup dynamic memory. for (auto item_in_pool = 0u; item_in_pool < total_workers; ++item_in_pool) { delete <API key>[item_in_pool]; } } } void <API key>::<API key>( const nn::workload_data<float> *input, nn::workload_data<float> *output) { auto <API key> = std::min(device->thread_pool.get_num_threads(), max_threads); const auto item_view_length = output->view_end.t[NN_DATA_COORD_y] - output->view_begin.t[NN_DATA_COORD_y] + 1; const auto items_per_thread = item_view_length / <API key>; const auto items_modulo = item_view_length % <API key>; // Check if we have enough data to cover all threads. if (items_per_thread == 0 && items_modulo < 2) { // Its tiny data - just do it singlethreaded way. <API key>(input, output); } else { // Full cores utilization version. // Not all threads will be used. if (items_per_thread == 0) <API key> = items_modulo; std::vector<<API key>> request_handles(<API key>); std::vector<const nn::workload_data<float> *> input_views(<API key>); std::vector<nn::workload_data<float> *> output_views(<API key>); uint32_t* thread_items_sums = static_cast<uint32_t*>(alloca(<API key> * sizeof(uint32_t))); if (thread_items_sums == nullptr) throw std::bad_alloc(); // Distribute elements more evenly. auto elements_left = items_modulo; for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { thread_items_sums[thread_id] = items_per_thread; if (elements_left) { ++thread_items_sums[thread_id]; --elements_left; } } // Now create table of thread sums. auto thread_sum = 0u; for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { thread_sum += thread_items_sums[thread_id]; thread_items_sums[thread_id] = thread_sum; } // Fill slave work items. for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { auto work_begin = 0u; if (thread_id > 0u) work_begin = thread_items_sums[thread_id - 1]; auto work_end = thread_items_sums[thread_id] - 1; // Replace nn_workload_datas pointers with views. <API key> nn_view_begin = { 0, 0, work_begin, 0, 0, 0 }; <API key> nn_view_end = { input->get_length(NN_DATA_COORD_n) - 1, input->get_length(NN_DATA_COORD_x) - 1, work_end, input->get_length(NN_DATA_COORD_z) - 1, input->get_length(NN_DATA_COORD_p) - 1, input->get_length(NN_DATA_COORD_q) - 1 }; input_views[thread_id] = new nn::workload_data<float>(*input, nn_view_begin, nn_view_end); output_views[thread_id] = new nn::workload_data<float>(*output, nn_view_begin, nn_view_end); } // Run threads. std::vector<<API key>> job(<API key>); for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { request_handles[thread_id].primitive = this; request_handles[thread_id].input_view = input_views[thread_id]; request_handles[thread_id].output_view = output_views[thread_id]; job[thread_id].callback = <API key>; job[thread_id].request_handle = &request_handles[thread_id]; } // Wait for all sub threads. device->thread_pool.push_job(job); // Cleanup dynamic memory. for (auto thread_id = 0u; thread_id < <API key>; ++thread_id) { delete input_views[thread_id]; delete output_views[thread_id]; } } } void <API key>::forward(const nn::workload_data<float> *input, nn::workload_data<float> *output) { if (device->thread_pool.get_num_threads() > 1) { <API key>(input, output); } else { <API key>(input, output); } } void <API key>::forward(const std::vector<const nn_workload_data_t *> &inputs, const std::vector<const nn_workload_data_t *> &parameters, const std::vector<nn_workload_data_t *> &outputs) { assert(inputs.size() == 1); assert(parameters.size() == 0); assert(outputs.size() == 1); forward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]), reinterpret_cast<nn::workload_data<float> *>(outputs[0])); } __m256 <API key>(__m256 arg) { __m256i e = _mm256_sub_epi32(_mm256_cvttps_epi32(arg), _mm256_and_si256(_mm256_castps_si256(_mm256_cmp_ps(arg, _mm256_setzero_ps(), _CMP_LT_OQ)), _mm256_set1_epi32(1))); arg = _mm256_sub_ps(arg, _mm256_cvtepi32_ps(e)); arg = _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( arg , _mm256_set1_ps(0.00021871895714413f) , _mm256_set1_ps(0.00123905464987147f)) , arg , _mm256_set1_ps(0.00968412797528994f)) , arg , _mm256_set1_ps(0.0554807914042966f)) , arg , _mm256_set1_ps(0.240230343637606f)) , arg , _mm256_set1_ps(0.693146963375785f)) , arg , _mm256_set1_ps(0.999999999869321f)); __m256 res = _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_add_epi32(e, _mm256_set1_epi32(127)), 23)); res = _mm256_mul_ps(res, arg); return res; } __m256 <API key>(__m256 input) { __m256i tmp = _mm256_castps_si256(input); __m256i e = _mm256_and_si256(tmp, _mm256_set1_epi32(0xff800000)); input = _mm256_castsi256_ps(_mm256_or_si256(_mm256_xor_si256(tmp, e), _mm256_set1_epi32(0x40000000))); e = _mm256_srai_epi32(_mm256_sub_epi32(e, _mm256_set1_epi32(0x3f900000)), 23); input = _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( input , _mm256_set1_ps(-3.92272173215165e-4f) , _mm256_set1_ps(8.44188448699613e-3f)) , input , _mm256_set1_ps(-7.80873452751869e-2f)) , input , _mm256_set1_ps(4.06812574432218e-1f)) , input , _mm256_set1_ps(-1.32744857721956f)) , input , _mm256_set1_ps(3.04806680788937f)) , input , _mm256_set1_ps(-2.03647726245336f)); return _mm256_add_ps(input, _mm256_cvtepi32_ps(e)); } __m256 <API key>(__m256 base, __m256 exponent) { return <API key>(_mm256_mul_ps(<API key>(base), exponent)); } __m256 <API key>(__m256 base) { auto x = _mm256_castsi256_ps(_mm256_or_si256(_mm256_and_si256(_mm256_castps_si256(base), _mm256_set1_epi32(0x007fffff)), _mm256_set1_epi32(0x3f800000))); auto e4 = _mm256_sub_epi32(_mm256_srai_epi32(_mm256_and_si256(_mm256_castps_si256(base), _mm256_set1_epi32(0x7f800000)), 21), _mm256_set1_epi32(508)); auto e4_3i = _mm256_srai_epi32(_mm256_add_epi32(_mm256_mullo_epi32(e4, _mm256_set1_epi32(0x5555)), _mm256_set1_epi32(0x1000)), 16); auto e4_3f = _mm256_sub_epi32(e4, _mm256_mullo_epi32(e4_3i, _mm256_set1_epi32(3))); auto e0 = _mm256_add_ps(_mm256_set1_ps(1.0f), _mm256_castsi256_ps(_mm256_and_si256(_mm256_cmpgt_epi32(e4_3f, _mm256_set1_epi32(0)), _mm256_castps_si256(_mm256_set1_ps(0.<API key>))))); auto e1 = _mm256_add_ps(_mm256_set1_ps(1.0f), _mm256_castsi256_ps(_mm256_and_si256(_mm256_cmpgt_epi32(e4_3f, _mm256_set1_epi32(1)), _mm256_castps_si256(_mm256_set1_ps(0.<API key>))))); auto e = _mm256_mul_ps(_mm256_mul_ps(_mm256_castsi256_ps(_mm256_slli_epi32(_mm256_add_epi32(e4_3i, _mm256_set1_epi32(127)), 23)), e0), e1); x = _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( _mm256_fmadd_ps( x , _mm256_set1_ps(-6.13621063256050e-4f) , _mm256_set1_ps(2.81846524230542e-3f)) , x , _mm256_set1_ps(7.23755774062622e-3f)) , x , _mm256_set1_ps(-9.05150071637931e-2f)) , x , _mm256_set1_ps(4.30600295045482e-1f)) , x , _mm256_set1_ps(7.04368603164122e-1f)) , x , _mm256_set1_ps(-5.38962929654863e-2f)); return _mm256_mul_ps(_mm256_mul_ps(x, e), base); } enum EXP_APPROX { APPROX_GENERIC, APPROX_2_33 }; template<EXP_APPROX T_approx> __m256 <API key> (__m256 base, __m256 exponent); template<> __m256 <API key><APPROX_GENERIC>(__m256 base, __m256 exponent) {return <API key>(base, exponent);} template<> __m256 <API key><APPROX_2_33> (__m256 base, __m256 exponent) {return <API key>(base);} template<EXP_APPROX T_approx> void <API key>( const nn::workload_data<float> *forward_input, const nn::workload_data<float> *forward_output, const nn::workload_data<float> *backward_input, nn::workload_data<float> *backward_output, const uint32_t n, const float alpha, const float beta) { const uint32_t range = (n - 1) / 2; const auto <API key> = reinterpret_cast<float*>(forward_input->parent->data_buffer); const auto <API key> = reinterpret_cast<float*>(forward_output->parent->data_buffer); const auto <API key> = reinterpret_cast<float*>(backward_input->parent->data_buffer); const auto <API key> = reinterpret_cast<float*>(backward_output->parent->data_buffer); const auto input_depth = forward_input->parent->lengths.t[NN_DATA_COORD_z]; const auto input_width = forward_input->parent->lengths.t[NN_DATA_COORD_x]; const auto input_height = forward_input->parent->lengths.t[NN_DATA_COORD_y]; const auto output_depth = forward_output->parent->lengths.t[NN_DATA_COORD_z]; const auto output_width = forward_output->parent->lengths.t[NN_DATA_COORD_x]; const auto output_height = forward_output->parent->lengths.t[NN_DATA_COORD_y]; assert(input_depth == output_depth); __m256i mask; const __m256 alpha_vec = _mm256_set1_ps(alpha); const __m256 beta_vec = _mm256_set1_ps(beta); const __m256 const_vec = _mm256_set1_ps(-2.0f); const __m256 pow_vec = _mm256_set1_ps(1.0f + 1.0f / beta); uint32_t* initial_load_mask = reinterpret_cast<uint32_t*>(alloca((output_depth + n - 1) * sizeof(float))); uint32_t load_mask[C_simd_width]; uint32_t load_mask_id = 0; for(uint32_t i = 0; i < range; ++i, ++load_mask_id) initial_load_mask[load_mask_id] = 0; for(uint32_t i = 0; i < input_depth; ++i, ++load_mask_id) initial_load_mask[load_mask_id] = 0xFFFFFFFF; for(uint32_t i = 0; i < range; ++i, ++load_mask_id) initial_load_mask[load_mask_id] = 0; for (uint32_t batch = backward_output->view_begin.t[NN_DATA_COORD_n]; batch <= backward_output->view_end.t[NN_DATA_COORD_n]; ++batch) { for (uint32_t row = backward_output->view_begin.t[NN_DATA_COORD_y]; row <= backward_output->view_end.t[NN_DATA_COORD_y]; ++row) { for (uint32_t column = backward_output->view_begin.t[NN_DATA_COORD_x]; column <= backward_output->view_end.t[NN_DATA_COORD_x]; ++column) { const auto forward_input_ptr = <API key> + column * input_depth + row * input_depth * input_width + batch * input_depth * input_width * input_height; const auto forward_output_ptr = <API key> + column * output_depth + row * output_depth * output_width + batch * output_depth * output_width * output_height; const auto backward_input_ptr = <API key> + column * output_depth + row * output_depth * output_width + batch * output_depth * output_width * output_height; #pragma forceinline recursive for (uint32_t in_feature_map = backward_output->view_begin.t[NN_DATA_COORD_z]; in_feature_map <= backward_output->view_end.t[NN_DATA_COORD_z]; in_feature_map += C_simd_width) { __m256 <API key> = _mm256_setzero_ps(); for (int32_t out_feature_map = (int32_t)in_feature_map - (int32_t)range; out_feature_map <= (int32_t)in_feature_map + (int32_t)range; ++out_feature_map) { const __m256i mask = _mm256_loadu_si256((__m256i*)(initial_load_mask + out_feature_map + range)); const __m256 n_out = _mm256_maskload_ps(forward_input_ptr + out_feature_map, mask); const __m256 a_out = _mm256_maskload_ps(forward_output_ptr + out_feature_map, mask); const __m256 n_in = _mm256_load_ps(forward_input_ptr + in_feature_map); const __m256 error_in = _mm256_maskload_ps(backward_input_ptr + out_feature_map, mask); // This code corresponds to: // acc = -2.0f * alpha * beta * n_out * n_in * std::pow(a_out / n_out, 1.0f + 1.0f / beta); __m256 acc = _mm256_mul_ps( _mm256_mul_ps( <API key><T_approx>( _mm256_div_ps(a_out, n_out), pow_vec), n_in), _mm256_mul_ps( _mm256_mul_ps(const_vec, alpha_vec), _mm256_mul_ps(beta_vec, n_out))); acc = _mm256_and_ps(acc, _mm256_castsi256_ps(mask)); <API key> = _mm256_fmadd_ps(acc, error_in, <API key>); } { const __m256i mask = _mm256_loadu_si256((__m256i*)(initial_load_mask + in_feature_map + range)); const __m256 n_out = _mm256_maskload_ps(forward_input_ptr + in_feature_map, mask); const __m256 a_out = _mm256_maskload_ps(forward_output_ptr + in_feature_map, mask); const __m256 error_in = _mm256_maskload_ps(backward_input_ptr + in_feature_map, mask); __m256 acc = _mm256_and_ps(_mm256_div_ps(a_out, n_out), _mm256_castsi256_ps(mask)); <API key> = _mm256_fmadd_ps(acc, error_in, <API key>); } _mm256_store_ps( <API key> + in_feature_map + column * input_depth + row * input_depth * input_width + batch * input_depth * input_width * input_height , <API key>); } } } } } void <API key>::backward( const nn::workload_data<float> *forward_input, const nn::workload_data<float> *forward_output, const nn::workload_data<float> *backward_input, nn::workload_data<float> *backward_output) { if(beta == 0.75f) { // Fast approximated exponent = 2.333f. <API key><APPROX_2_33>( forward_input, forward_output, backward_input, backward_output, n, alpha, beta); } else { // Generic case. <API key><APPROX_GENERIC>( forward_input, forward_output, backward_input, backward_output, n, alpha, beta); } } void <API key>::backward(const std::vector<nn_workload_data_t *> &inputs, const std::vector<const nn_workload_data_t *> &parameters, const std::vector<const nn_workload_data_t *> &outputs) { assert(inputs.size() == 1); assert(outputs.size() == 1); const nn::workload_data<float> backward_input(outputs[0]->parent->delta_buffer, outputs[0]->parent->lengths, outputs[0]->parent->layout); nn::workload_data<float> backward_output(inputs[0]->parent->delta_buffer, inputs[0]->parent->lengths, inputs[0]->parent->layout); dispatch_backward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]), reinterpret_cast<const nn::workload_data<float> *>(outputs[0]), &backward_input, &backward_output); } void <API key>(nn_workload_item *const work_item) { switch (work_item->forward_item->arguments.<API key>.normalization.mode) { case <API key>: { assert(0); // Not yet implemented. break; } case <API key>: { auto primitive = static_cast<<API key> *>(work_item->forward_item->primitive); primitive->dispatch_backward( reinterpret_cast<nn::workload_data<float> *>(work_item->forward_item->input[0].get_data_view()), reinterpret_cast<nn::workload_data<float> *>(work_item->forward_item->output[0]), reinterpret_cast<nn::workload_data<float> *>(work_item->input[0].get_data_view()), reinterpret_cast<nn::workload_data<float> *>(work_item->output[0])); break; } default: { assert(0); break; } } } <API key>::<API key>(float alpha, float beta, size_t image_size_x, size_t image_size_y, size_t image_size_z, size_t batch_size, nn_device_internal *device) : <API key>(batch_size, image_size_z, image_size_x, image_size_y, image_size_z, 0, 0, 0, 0, device), normalization_mode(<API key>), alpha(alpha), beta(beta) {} size_t <API key>::<API key>() { return output_size_x; } size_t <API key>::<API key>() { return output_size_y; } bool <API key>::validate_input(size_t index, nn_workload_data_t *data) { switch (index) { case 0: return nn::data_helper<<API key>, float>::validate<false>( data, <API key>(), <API key>(), input_size_z, batch_size, 0, 0, 0, 0); } throw std::invalid_argument("index out of range"); } <API key>::<API key>(float alpha, float beta, uint32_t k, uint32_t n, size_t image_size_x, size_t image_size_y, size_t image_size_z, size_t batch_size, size_t output_padding_left, size_t <API key>, size_t output_padding_top, size_t <API key>, nn_device_internal *device) : <API key>(batch_size, image_size_z, image_size_x, image_size_y, image_size_z, output_padding_left, <API key>, output_padding_top, <API key>, device), normalization_mode(<API key>), alpha(alpha), beta(beta), k(k), n(n) {} size_t <API key>::<API key>() { return output_size_x; } size_t <API key>::<API key>() { return output_size_y; } bool <API key>::validate_input(size_t index, nn_workload_data_t *data) { switch (index) { case 0: return nn::data_helper<<API key>, float>::validate<true>( data, <API key>(), <API key>(), input_size_z, batch_size, 0, 0, 0, 0); } throw std::invalid_argument("index out of range"); } } // namespace layer <API key> <API key> <API key>(nn_device_t *device, /* IDLF device handle */ float alpha, /* multiplier */ float beta, /* offset */ size_t image_size_x, /* image width */ size_t image_size_y, /* image height */ size_t image_size_z, /* number of feature maps */ size_t batch_size, /* size of input batch */ NN_API_STATUS *status /* NN_API_STATUS_OK on success */) { SET_STATUS(NN_API_STATUS_OK); return new layer::<API key>(alpha, beta, image_size_x, image_size_y, image_size_z, batch_size, reinterpret_cast<nn_device_internal *>(device)); } <API key> <API key> <API key>( nn_device_t *device, /* IDLF device handle */ float alpha, /* sum scale */ float beta, /* sum power */ uint32_t k, /* square sum weight */ uint32_t n, /* size of moving window on the feature maps */ size_t image_size_x, /* image width */ size_t image_size_y, /* image height */ size_t image_size_z, /* number of feature maps */ size_t batch_size, /* size of input batch */ const <API key> *hints, NN_API_STATUS *status /* NN_API_STATUS_OK on success */) { SET_STATUS(NN_API_STATUS_OK); std::remove_const<std::remove_pointer<decltype(hints)>::type>::type hints_ = {}; if (hints != nullptr) hints_ = *hints; return new layer::<API key>(alpha, beta, k, n, image_size_x, image_size_y, image_size_z, batch_size, hints_.output_padding.left, hints_.output_padding.right, hints_.output_padding.top, hints_.output_padding.bottom, reinterpret_cast<nn_device_internal *>(device)); }
<?php /* Prototype : string vsprintf(string format, array args) * Description: Return a formatted string * Source code: ext/standard/formatted_print.c */ /* * Test vsprintf() when different hexa formats and hexa values are passed to * the '$format' and '$args' arguments of the function */ echo "*** Testing vsprintf() : hexa formats with hexa values ***\n"; // defining array of different hexa formats $formats = array( "%x", "%+x %-x %X", "%lx %Lx, %4x %-4x", "%10.4x %-10.4x %04x %04.4x", "%'#2x %'2x %'$2x %'_2x", "%x %x %x %x", "% %%x x%", '%3$x %4$x %1$x %2$x' ); // Arrays of hexa values for the format defined in $format. // Each sub array contains hexa values which correspond to each format string in $format $args_array = array( array(0x0), array(-0x1, 0x1, +0x22), array(0x7FFFFFFF, -0x7fffffff, +0x7000000, -0x80000000), array(123456, 12345678, -1234567, 1234567), array(1, 0x2222, 0333333, -0x44444444), array(0x123b, 0xfAb, "0xaxz", 012), array(0x1234, 0x34, 0x2ff), array(0x3, 0x4, 0x1, 0x2) ); // looping to test vsprintf() with different char octal from the above $format array // and with octal values from the above $args_array array $counter = 1; foreach($formats as $format) { echo "\n-- Iteration $counter --\n"; var_dump( vsprintf($format, $args_array[$counter-1]) ); $counter++; } echo "Done"; ?>
# TODO list - [ ] Update rustup - [ ] Update dependency `cargo upgrade` - [ ] Run `cargo clippy` - [ ] Run all test - [ ] Stable: `RSTEST_TEST_CHANNEL=stable; cargo +${RSTEST_TEST_CHANNEL} test` - [ ] Beta: `RSTEST_TEST_CHANNEL=beta; cargo +${RSTEST_TEST_CHANNEL} test` - [ ] Nightly: `RSTEST_TEST_CHANNEL=nightly; cargo +${RSTEST_TEST_CHANNEL} test` - [ ] Check Cargo.toml version - [ ] Create docs and checks links - [ ] Check CHANGELOG: **RELEASE DATE** and remove empty blocks - [ ] Check README - [ ] Create tag (Use github release) - [ ] prepare deploy `cargo publish --dry-run` - [ ] deploy `cargo publish` - [ ] Change next version - [ ] `Cargo.toml` - [ ] `README.md` - [ ] `CHANGELOG.md` - [ ] Change dependency (inner `rstest` and `rstest_ruse`) - [ ] Prepare next changelog
#ifndef <API key> #define <API key> #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "blimp/net/blimp_net_export.h" #include "net/base/completion_callback.h" namespace blink { class WebInputEvent; } namespace blimp { class BlimpMessage; class <API key>; // Handles creating serialized InputMessage protos from a stream of // WebInputEvents. This class may be stateful to optimize the size of the // serialized transmission data. See <API key> for the deserialize // code. class BLIMP_NET_EXPORT <API key> { public: <API key>(); ~<API key>(); // Builds a BlimpMessage from |event| that has the basic input event fields // populated. This might make use of state sent from previous // BlimpMessage::INPUT messages. It is up to the caller to populate the // non-input fields and to send the BlimpMessage. scoped_ptr<BlimpMessage> GenerateMessage(const blink::WebInputEvent& event); private: <API key>(<API key>); }; } // namespace blimp #endif // <API key>
#ifndef EventHandler_h #define EventHandler_h #include "core/CoreExport.h" #include "core/events/PointerEventFactory.h" #include "core/events/TextEventInputType.h" #include "core/layout/HitTestRequest.h" #include "core/page/DragActions.h" #include "core/page/<API key>.h" #include "core/style/<API key>.h" #include "platform/Cursor.h" #include "platform/PlatformMouseEvent.h" #include "platform/PlatformTouchPoint.h" #include "platform/Timer.h" #include "platform/<API key>.h" #include "platform/geometry/LayoutPoint.h" #include "platform/heap/Handle.h" #include "platform/scroll/ScrollTypes.h" #include "public/platform/WebFocusType.h" #include "public/platform/WebInputEventResult.h" #include "wtf/Forward.h" #include "wtf/HashMap.h" #include "wtf/HashTraits.h" #include "wtf/RefPtr.h" #include <deque> namespace blink { class <API key>; class DataTransfer; class PaintLayer; class <API key>; class Document; class DragState; class Element; class Event; class EventTarget; template <typename EventType> class <API key>; class FloatPoint; class FloatQuad; class HTMLFrameSetElement; class HitTestRequest; class HitTestResult; class KeyboardEvent; class LayoutObject; class LocalFrame; class Node; class OptionalCursor; class <API key>; class <API key>; class PlatformTouchEvent; class PlatformWheelEvent; class ScrollableArea; class Scrollbar; class ScrollState; class SelectionController; class TextEvent; class WheelEvent; class Widget; enum class DragInitiator; class CORE_EXPORT EventHandler final : public <API key><EventHandler> { <API key>(EventHandler); <API key>(EventHandler); public: explicit EventHandler(LocalFrame*); ~EventHandler(); DECLARE_TRACE(); void clear(); void nodeWillBeRemoved(Node&); void <API key>(); #if OS(WIN) void startPanScrolling(LayoutObject*); #endif void stopAutoscroll(); void <API key>(); void <API key>(const FloatQuad&); HitTestResult <API key>(const LayoutPoint&, HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active, const LayoutSize& padding = LayoutSize()); bool mousePressed() const { return m_mousePressed; } void <API key>(<API key><Node>); // A caller is responsible for resetting capturing node to 0. WebInputEventResult updateDragAndDrop(const PlatformMouseEvent&, DataTransfer*); void cancelDragAndDrop(const PlatformMouseEvent&, DataTransfer*); WebInputEventResult performDragAndDrop(const PlatformMouseEvent&, DataTransfer*); void <API key>(Element* rootEditableElement); void <API key>(); void <API key>(); // Return whether a mouse cursor update is currently pending. Used for testing. bool cursorUpdatePending(); void setResizingFrameSet(HTMLFrameSetElement*); void <API key>(); IntPoint <API key>() const; // Attempts to scroll the DOM tree. If that fails, scrolls the view. // If the view can't be scrolled either, recursively bubble to the parent frame. bool bubblingScroll(ScrollDirection, ScrollGranularity, Node* startingNode = nullptr); WebInputEventResult <API key>(const PlatformMouseEvent&); void <API key>(const PlatformMouseEvent&); WebInputEventResult <API key>(const PlatformMouseEvent&); WebInputEventResult <API key>(const PlatformMouseEvent&); WebInputEventResult handleWheelEvent(const PlatformWheelEvent&); void <API key>(Node*, WheelEvent*); // Called on the local root frame exactly once per gesture event. WebInputEventResult handleGestureEvent(const <API key>&); WebInputEventResult handleGestureEvent(const <API key>&); // Clear the old hover/active state within frames before moving the hover state to the another frame void <API key>(const HitTestRequest&, Element*); // Hit-test the provided (non-scroll) gesture event, applying touch-adjustment and updating // hover/active state across all frames if necessary. This should be called at most once // per gesture event, and called on the local root frame. // Note: This is similar to (the less clearly named) prepareMouseEvent. // FIXME: Remove readOnly param when there is only ever a single call to this. <API key> targetGestureEvent(const <API key>&, bool readOnly = false); <API key> <API key>(const <API key>&, HitTestRequest::HitTestRequestType); // Handle the provided non-scroll gesture event. Should be called only on the inner frame. WebInputEventResult <API key>(const <API key>&); // Handle the provided scroll gesture event, propagating down to child frames as necessary. WebInputEventResult <API key>(const <API key>&); WebInputEventResult <API key>(const <API key>&); bool <API key>() const; bool <API key>(const HitTestResult&, IntPoint& targetPoint, Node*& targetNode); bool <API key>(const HitTestResult&, IntPoint& targetPoint, Node*& targetNode); // FIXME: This doesn't appear to be used outside tests anymore, what path are we using now and is it tested? bool <API key>(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode); WebInputEventResult <API key>(const PlatformMouseEvent&, Node* overrideTargetNode = nullptr); WebInputEventResult <API key>(Element* <API key> = nullptr); WebInputEventResult <API key>(const <API key>&); void <API key>() { <API key> = true; } static PlatformEvent::Modifiers accessKeyModifiers(); bool handleAccessKey(const <API key>&); WebInputEventResult keyEvent(const <API key>&); void <API key>(KeyboardEvent*); bool <API key>(const String& text, Event* underlyingEvent = nullptr, TextEventInputType = <API key>); void <API key>(TextEvent*); void dragSourceEndedAt(const PlatformMouseEvent&, DragOperation); void focusDocumentView(); void <API key>(); // Only called by FrameSelection WebInputEventResult handleTouchEvent(const PlatformTouchEvent&); bool useHandCursor(Node*, bool isOverLink); void <API key>(); PassRefPtr<UserGestureToken> <API key>() { return <API key>.release(); } int clickCount() { return m_clickCount; } SelectionController& selectionController() const { return *<API key>; } class TouchInfo { <API key>(); public: DEFINE_INLINE_TRACE() { visitor->trace(touchTarget); visitor->trace(targetFrame); } PlatformTouchPoint point; RefPtrWillBeMember<EventTarget> touchTarget; RefPtrWillBeMember<LocalFrame> targetFrame; FloatPoint adjustedPagePoint; FloatSize adjustedRadius; bool knownTarget; bool consumed; }; private: static DragState& dragState(); DataTransfer* <API key>() const; WebInputEventResult <API key>(const PlatformMouseEvent&, HitTestResult* hoveredNode = nullptr, bool <API key> = false, bool forceLeave = false); WebInputEventResult <API key>(const <API key>&); WebInputEventResult handleMouseFocus(const <API key>&, <API key>* sourceCapabilities); WebInputEventResult <API key>(const <API key>&); WebInputEventResult <API key>(const <API key>&); HitTestRequest::HitTestRequestType <API key>(PlatformEvent::Type); void <API key>(<API key>*, HitTestResult*); WebInputEventResult handleGestureTap(const <API key>&); WebInputEventResult <API key>(const <API key>&); WebInputEventResult <API key>(const <API key>&); WebInputEventResult <API key>(const <API key>&); WebInputEventResult <API key>(const <API key>&); void <API key>(); void <API key>(const <API key>&); bool <API key>(const <API key>&) const; OptionalCursor selectCursor(const HitTestResult&); OptionalCursor selectAutoCursor(const HitTestResult&, Node*, const Cursor& iBeam); void hoverTimerFired(Timer<EventHandler>*); void <API key>(Timer<EventHandler>*); void <API key>(Timer<EventHandler>*); void <API key>(Timer<EventHandler>*); void <API key>(); bool isCursorVisible() const; void updateCursor(); ScrollableArea* <API key>(const PaintLayer*) const; // Scrolls the elements of the DOM tree. Returns true if a node was scrolled. // False if we reached the root and couldn't scroll anything. // direction - The direction to scroll in. If this is a logical direction, it will be // converted to the physical direction based on a node's writing mode. // granularity - The units that the scroll delta parameter is in. // startNode - The node to start bubbling the scroll from. If a node can't scroll, // the scroll bubbles up to the containing block. // stopNode - On input, if provided and non-null, the node at which we should stop bubbling on input. // On output, if provided and a node was scrolled stopNode will point to that node. // delta - The delta to scroll by, in the units of the granularity parameter. (e.g. pixels, lines, pages, etc.) // absolutePoint - For wheel scrolls - the location, in absolute coordinates, where the event occured. <API key> scroll(ScrollDirection, ScrollGranularity, Node* startNode = nullptr, Node** stopNode = nullptr, float delta = 1.0f, IntPoint absolutePoint = IntPoint()); void resetOverscroll(bool didScrollX, bool didScrollY); void handleOverscroll(const ScrollResult&, const FloatPoint& position = FloatPoint(), const FloatSize& velocity = FloatSize()); void customizedScroll(const Node& startNode, ScrollState&); HitTestResult <API key>(LocalFrame*, const LayoutPoint&, HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active); void invalidateClick(); void <API key>(Node*, const PlatformMouseEvent&); // Returns true when the sent PE has defaultPrevented or defaultHandled set. WebInputEventResult <API key>(Node* target, const AtomicString& eventType, const PlatformMouseEvent&, Node* relatedTarget = nullptr); // Dispatches mouseover, mouseout, mouseenter and mouseleave events to appropriate nodes when the mouse pointer moves from one node to another. void <API key>(Node*, Node*, const PlatformMouseEvent&); <API key> prepareMouseEvent(const HitTestRequest&, const PlatformMouseEvent&); WebInputEventResult dispatchMouseEvent(const AtomicString& eventType, Node* target, int clickCount, const PlatformMouseEvent&); // Dispatches ME after corresponding PE provided the PE has not been canceled. The eventType arg // must be a mouse event that can be gated though a preventDefaulted pointerdown (i.e., one of // {mousedown, mousemove, mouseup}). // TODO(mustaq): Can we avoid the clickCount param, instead use PlatformMouseEvent's count? // Same applied to dispatchMouseEvent() above. WebInputEventResult <API key>(const AtomicString& mouseEventType, Node* target, int clickCount, const PlatformMouseEvent&); WebInputEventResult dispatchDragEvent(const AtomicString& eventType, Node* target, const PlatformMouseEvent&, DataTransfer*); void <API key>(); bool handleDrag(const <API key>&, DragInitiator); bool tryStartDrag(const <API key>&); void clearDragState(); WebInputEventResult <API key>(const AtomicString& eventType, const PlatformMouseEvent&); bool <API key>(const IntPoint&) const; WebInputEventResult <API key>(<API key>&, LocalFrame* subframe); WebInputEventResult <API key>(<API key>&, LocalFrame* subframe, HitTestResult* hoveredNode = nullptr); WebInputEventResult <API key>(<API key>&, LocalFrame* subframe); bool <API key>(<API key>&); WebInputEventResult <API key>(const PlatformWheelEvent&, Widget&); void <API key>(KeyboardEvent*); void <API key>(KeyboardEvent*); void <API key>(KeyboardEvent*); void <API key>(KeyboardEvent*); void <API key>(WebFocusType, KeyboardEvent*); void <API key>(Scrollbar*, bool); void <API key>(); bool capturesDragging() const { return m_capturesDragging; } WebInputEventResult <API key>(); bool <API key>(Node*, const <API key>&); WebInputEventResult <API key>(const <API key>&, LayoutObject*); <API key>* <API key>() const; bool panScrollInProgress() const; void <API key>(const PlatformMouseEvent&); void <API key>(const PlatformMouseEvent&); bool <API key>(FloatSize) const; // If the given element is a shadow host and its root has delegatesFocus=false flag, // slide focus to its inner element. Returns true if the resulting focus is different from // the given element. bool <API key>(const Element&); void <API key>(const PlatformTouchEvent&, WillBeHeapVector<TouchInfo>&); void sendPointerCancels(WillBeHeapVector<TouchInfo>&); WebInputEventResult dispatchTouchEvents(const PlatformTouchEvent&, WillBeHeapVector<TouchInfo>&, bool, bool); // NOTE: If adding a new field to this class please ensure that it is // cleared in |EventHandler::clear()|. const RawPtrWillBeMember<LocalFrame> m_frame; // Current button-press state for mouse/mouse-like-stylus. // TODO(crbug.com/563676): Buggy for chorded buttons. bool m_mousePressed; bool m_capturesDragging; RefPtrWillBeMember<Node> m_mousePressNode; bool <API key>; const OwnPtrWillBeMember<SelectionController> <API key>; LayoutPoint m_dragStartPos; Timer<EventHandler> m_hoverTimer; // TODO(rbyers): Mouse cursor update is page-wide, not per-frame. Page-wide state // should move out of EventHandler to a new PageEventHandler class. crbug.com/449649 Timer<EventHandler> m_cursorUpdateTimer; bool <API key>; Timer<EventHandler> <API key>; bool m_svgPan; RawPtrWillBeMember<<API key>> <API key>; RefPtrWillBeMember<Node> <API key>; bool <API key>; RefPtrWillBeMember<Node> m_nodeUnderMouse; RefPtrWillBeMember<LocalFrame> <API key>; RefPtrWillBeMember<Scrollbar> <API key>; int m_clickCount; RefPtrWillBeMember<Node> m_clickNode; RefPtrWillBeMember<Node> m_dragTarget; bool <API key>; RefPtrWillBeMember<HTMLFrameSetElement> <API key>; LayoutSize <API key>; // In the coords of <API key>. FloatSize <API key>; bool <API key>; // The last mouse movement position this frame has seen in root frame coordinates. IntPoint <API key>; IntPoint <API key>; IntPoint m_mouseDownPos; // In our view's coords. double <API key>; PlatformMouseEvent m_mouseDown; RefPtr<UserGestureToken> <API key>; RefPtrWillBeMember<Node> <API key>; // The target of each active touch point indexed by the touch ID. using TouchTargetMap = WillBeHeapHashMap<unsigned, RefPtrWillBeMember<EventTarget>, DefaultHash<unsigned>::Hash, WTF::<API key><unsigned>>; TouchTargetMap m_targetForTouchID; // If set, the document of the active touch sequence. Unset if no touch sequence active. RefPtrWillBeMember<Document> <API key>; RefPtr<UserGestureToken> <API key>; bool m_touchPressed; PointerEventFactory <API key>; // Prevents firing mousedown, mousemove & mouseup in-between a canceled pointerdown and next pointerup/pointercancel. // See "PREVENT MOUSE EVENT flag" in the spec: // https://w3c.github.io/pointerevents/#<API key> bool <API key>; // This is set upon sending a pointercancel for touch, prevents PE dispatches for touches until // all touch-points become inactive. // TODO(mustaq): Consider a state per pointerType, as in PointerIdManager? Exclude mouse? bool <API key>; RefPtrWillBeMember<Node> <API key>; bool <API key>; // The most recent element to scroll natively during this scroll // sequence. Null if no native element has scrolled this scroll // sequence, or if the most recent element to scroll used scroll // customization. RefPtrWillBeMember<Node> <API key>; RefPtrWillBeMember<Scrollbar> <API key>; double <API key>; bool <API key>; Timer<EventHandler> <API key>; double <API key>; RefPtrWillBeMember<Element> <API key>; // Only used with the ScrollCustomization runtime enabled feature. std::deque<int> <API key>; // True iff some of the delta has been consumed for the current // scroll sequence in this frame, or any child frames. Only used // with ScrollCustomization. If some delta has been consumed, a // scroll which shouldn't propagate can't cause any element to // scroll other than the |<API key>|. bool <API key>; }; } // namespace blink <API key>(blink::EventHandler::TouchInfo); #endif // EventHandler_h
__ace_shadowed__.define('ace/mode/ruby', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/<API key>', 'ace/mode/<API key>', 'ace/range', 'ace/mode/folding/coffee'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var RubyHighlightRules = require("./<API key>").RubyHighlightRules; var <API key> = require("./<API key>").<API key>; var Range = require("../range").Range; var FoldMode = require("./folding/coffee").FoldMode; var Mode = function() { this.HighlightRules = RubyHighlightRules; this.$outdent = new <API key>(); this.foldingRules = new FoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = " this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); var <API key> = line.match(/^\s*(class|def|module)\s.*$/); var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/); var startingConditional = line.match(/^\s*(if|else)\s*/) if (match || <API key> || startingDoBlock || startingConditional) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return /^\s+end$/.test(line + input) || /^\s+}$/.test(line + input) || /^\s+else$/.test(line + input); }; this.autoOutdent = function(state, doc, row) { var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; this.$id = "ace/mode/ruby"; }).call(Mode.prototype); exports.Mode = Mode; }); __ace_shadowed__.define('ace/mode/<API key>', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/<API key>'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./<API key>").TextHighlightRules; var constantOtherSymbol = exports.constantOtherSymbol = { token : "constant.other.symbol.ruby", // symbol regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" }; var qString = exports.qString = { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }; var qqString = exports.qqString = { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }; var tString = exports.tString = { token : "string", // backtick string regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]" }; var constantNumericHex = exports.constantNumericHex = { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b" }; var <API key> = exports.<API key> = { token : "constant.numeric", // float regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b" }; var RubyHighlightRules = function() { var builtinFunctions = ( "abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" + "assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" + "assert_raise|<API key>|assert_instance_of|assert_kind_of|assert_respond_to|" + "assert_operator|assert_send|assert_difference|<API key>|assert_recognizes|" + "assert_generates|assert_response|<API key>|assert_template|assert_select|" + "assert_select_email|assert_select_rjs|<API key>|css_select|at_exit|" + "attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" + "caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" + "exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" + "gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" + "<API key>|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" + "p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" + "raw|readline|readlines|redirect?|<API key>|require|scan|select|" + "set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" + "throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" + "render|<API key>|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" + "content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" + "fields_for|select_tag|options_for_select|<API key>|collection_select|" + "time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" + "select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" + "file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" + "<API key>|rescue_from|helper_method|redirect_to|before_filter|" + "send_data|send_file|<API key>|<API key>|validates_length_of|" + "validates_format_of|<API key>|<API key>|<API key>|" + "<API key>|<API key>|validates_with|validates_each|" + "<API key>|<API key>|" + "<API key>|match|get|post|resources|redirect|scope|assert_routing|" + "translate|localize|<API key>|caches_page|expire_page|caches_action|expire_action|" + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + "has_many|has_one|belongs_to|<API key>" ); var keywords = ( "alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" + "__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" + "redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield" ); var buildinConstants = ( "true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" + "RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING" ); var builtinVariables = ( "\$DEBUG|\$defout|\$FILENAME|\$LOAD_PATH|\$SAFE|\$stdin|\$stdout|\$stderr|\$VERBOSE|" + "$!|root_url|flash|session|cookies|params|request|response|logger|self" ); var keywordMapper = this.$keywords = this.createKeywordMapper({ "keyword": keywords, "constant.language": buildinConstants, "variable.language": builtinVariables, "support.function": builtinFunctions, "invalid.deprecated": "debugger" // TODO is this a remnant from js mode? }, "identifier"); this.$rules = { "start" : [ { token : "comment", regex : " }, { token : "comment", // multi line comment regex : "^=begin(?:$|\\s.*$)", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, qString, qqString, tString, { token : "text", // namespaces aren't symbols regex : "::" }, { token : "variable.instance", // instance variable regex : "@{1,2}[a-zA-Z_\\d]+" }, { token : "support.class", // class name regex : "[A-Z][a-zA-Z_\\d]+" }, constantOtherSymbol, constantNumericHex, <API key>, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "punctuation.separator.key-value", regex : "=>" }, { stateName: "heredoc", onMatch : function(value, currentState, stack) { var next = value[2] == '-' ? "indentedHeredoc" : "heredoc"; var tokens = value.split(this.splitRegex); stack.push(next, tokens[3]); return [ {type:"constant", value: tokens[1]}, {type:"string", value: tokens[2]}, {type:"support.class", value: tokens[3]}, {type:"string", value: tokens[4]} ]; }, regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)", rules: { heredoc: [{ onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }], indentedHeredoc: [{ token: "string", regex: "^ +" }, { onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }] } }, { regex : "$", token : "empty", next : function(currentState, stack) { if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc") return stack[0]; return currentState; } }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : "^=end(?:$|\\s.*$)", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ] }; this.normalizeRules(); }; oop.inherits(RubyHighlightRules, TextHighlightRules); exports.RubyHighlightRules = RubyHighlightRules; }); __ace_shadowed__.define('ace/mode/<API key>', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var <API key> = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(<API key>.prototype); exports.<API key> = <API key>; }); __ace_shadowed__.define('ace/mode/folding/coffee', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != " return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != " break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); });
a.reference.image-reference { border-bottom: none; }
// RUN: %clang_builtins %s %librt -o %t && %run %t // REQUIRES: librt_has_absvdi2 // <API key>: Apache-2.0 WITH LLVM-exception // This file tests __absvdi2 for the compiler_rt library. #include "int_lib.h" #include <stdio.h> #include <stdlib.h> // Returns: absolute value // Effects: aborts if abs(x) < 0 COMPILER_RT_ABI di_int __absvdi2(di_int a); int test__absvdi2(di_int a) { di_int x = __absvdi2(a); di_int expected = a; if (expected < 0) expected = -expected; if (x != expected || expected < 0) printf("error in __absvdi2(0x%llX) = %lld, expected positive %lld\n", a, x, expected); return x != expected; } int main() { // if (test__absvdi2(<API key>)) // should abort // return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; if (test__absvdi2(<API key>)) return 1; int i; for (i = 0; i < 10000; ++i) if (test__absvdi2(((di_int)rand() << 32) | rand())) return 1; return 0; }
// Currently this file is only used for the uninstall prompt. The install prompt // code is in <API key>.cc. #include "chrome/browser/extensions/<API key>.h" #include <gtk/gtk.h> #include "base/string_util.h" #include "base/<API key>.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/gtk/browser_window_gtk.h" #include "chrome/common/extensions/extension.h" #include "grit/generated_resources.h" #include "ui/base/gtk/gtk_hig_constants.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/gtk_util.h" namespace { // Left or right margin. const int kPanelHorizMargin = 13; // GTK implementation of the uninstall dialog. class <API key> : public <API key> { public: <API key>(Browser* browser, Delegate* delegate); virtual ~<API key>() OVERRIDE; private: virtual void Show() OVERRIDE; <API key>(<API key>, void, OnResponse, int); GtkWidget* dialog_; }; <API key>::<API key>( Browser* browser, <API key>::Delegate* delegate) : <API key>(browser, delegate), dialog_(NULL) {} void <API key>::Show() { BrowserWindow* browser_window = browser_->window(); if (!browser_window) { delegate_-><API key>(); return; } // Build the dialog. dialog_ = <API key>( l10n_util::GetStringUTF8(<API key>).c_str(), browser_window->GetNativeWindow(), GTK_DIALOG_MODAL, GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE, l10n_util::GetStringUTF8(<API key>).c_str(), GTK_RESPONSE_ACCEPT, NULL); #if !GTK_CHECK_VERSION(2, 22, 0) <API key>(GTK_DIALOG(dialog_), FALSE); #endif // Create a two column layout. GtkWidget* content_area = <API key>(GTK_DIALOG(dialog_)); gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing); GtkWidget* icon_hbox = gtk_hbox_new(FALSE, ui::kContentAreaSpacing); gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0); // Put Icon in the left column. GdkPixbuf* pixbuf = gfx::<API key>(*icon_.bitmap()); GtkWidget* icon = <API key>(pixbuf); g_object_unref(pixbuf); gtk_box_pack_start(GTK_BOX(icon_hbox), icon, TRUE, TRUE, 0); // Create a new vbox for the right column. GtkWidget* right_column_area = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0); std::string heading_text = l10n_util::GetStringFUTF8( <API key>, UTF8ToUTF16(extension_->name())); GtkWidget* heading_label = gtk_label_new(heading_text.c_str()); <API key>(GTK_MISC(heading_label), 0.0, 0.5); gtk_box_pack_start(GTK_BOX(right_column_area), heading_label, TRUE, TRUE, 0); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); <API key>(GTK_WINDOW(dialog_), FALSE); gtk_widget_show_all(dialog_); } <API key>::~<API key>() { delegate_ = NULL; if (dialog_) { gtk_widget_destroy(dialog_); dialog_ = NULL; } } void <API key>::OnResponse( GtkWidget* dialog, int response_id) { CHECK_EQ(dialog_, dialog); gtk_widget_destroy(dialog_); dialog_ = NULL; if (delegate_) { if (response_id == GTK_RESPONSE_ACCEPT) delegate_-><API key>(); else delegate_-><API key>(); } } } // namespace // static // Platform specific implementation of the uninstall dialog show method. <API key>* <API key>::Create( Browser* browser, Delegate* delegate) { return new <API key>(browser, delegate); }
#import <Cocoa/Cocoa.h> #include "base/callback.h" #include "remoting/host/disconnect_window.h" namespace remoting { class ChromotingHost; } // Controller for the disconnect window which allows the host user to // quickly disconnect a session. @interface <API key> : NSWindowController { @private remoting::ChromotingHost* host_; base::Closure <API key>; NSString* username_; IBOutlet NSTextField* connectedToField_; IBOutlet NSButton* disconnectButton_; } - (id)initWithHost:(remoting::ChromotingHost*)host callback:(const base::Closure&)disconnect_callback username:(NSString*)username; - (IBAction)stopSharing:(id)sender; @end // A floating window with a custom border. The custom border and background // content is defined by DisconnectView. Declared here so that it can be // instantiated via a xib. @interface DisconnectWindow : NSWindow @end // The custom background/border for the DisconnectWindow. Declared here so that // it can be instantiated via a xib. @interface DisconnectView : NSView @end
#include "build/build_config.h" #include "components/nacl/common/nacl_types.h" #include "ipc/ipc_platform_file.h" namespace nacl { NaClStartParams::NaClStartParams() : nexe_file(IPC::<API key>()), irt_handle(IPC::<API key>()), #if defined(OS_MACOSX) mac_shm_fd(IPC::<API key>()), #endif #if defined(OS_POSIX) <API key>(IPC::<API key>()), #endif <API key>(false), enable_debug_stub(false), process_type(<API key>), <API key>(base::SharedMemory::NULLHandle()) { } NaClStartParams::~NaClStartParams() { } <API key>::<API key>() : file(IPC::<API key>()) { } <API key>::<API key>( const IPC::<API key>& file, const base::FilePath& file_path_metadata, const std::string& file_key) : file(file), file_path_metadata(file_path_metadata), file_key(file_key) { } <API key>::~<API key>() { } <API key>::<API key>() { } <API key>::<API key>( const std::string& file_key, const std::string& resource_url) : file_key(file_key), resource_url(resource_url) { } <API key>::~<API key>() { } NaClLaunchParams::NaClLaunchParams() : nexe_file(IPC::<API key>()), nexe_token_lo(0), nexe_token_hi(0), render_view_id(0), permission_bits(0), process_type(<API key>) { } NaClLaunchParams::NaClLaunchParams( const std::string& manifest_url, const IPC::<API key>& nexe_file, uint64_t nexe_token_lo, uint64_t nexe_token_hi, const std::vector<<API key>>& <API key>, int render_view_id, uint32_t permission_bits, bool uses_nonsfi_mode, NaClAppProcessType process_type) : manifest_url(manifest_url), nexe_file(nexe_file), nexe_token_lo(nexe_token_lo), nexe_token_hi(nexe_token_hi), <API key>(<API key>), render_view_id(render_view_id), permission_bits(permission_bits), uses_nonsfi_mode(uses_nonsfi_mode), process_type(process_type) {} NaClLaunchParams::~NaClLaunchParams() { } NaClLaunchResult::NaClLaunchResult() : <API key>(), <API key>(), plugin_pid(base::kNullProcessId), plugin_child_id(0), <API key>(base::SharedMemory::NULLHandle()) { } NaClLaunchResult::NaClLaunchResult( const IPC::ChannelHandle& <API key>, const IPC::ChannelHandle& <API key>, const IPC::ChannelHandle& <API key>, base::ProcessId plugin_pid, int plugin_child_id, base::SharedMemoryHandle <API key>) : <API key>(<API key>), <API key>(<API key>), <API key>(<API key>), plugin_pid(plugin_pid), plugin_child_id(plugin_child_id), <API key>(<API key>) { } NaClLaunchResult::~NaClLaunchResult() { } } // namespace nacl
// modification, are permitted provided that the following conditions are // met: // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Stack-footprint reduction work done by Raksit Ashok // Implementation note: // We don't use heaps but only use stacks. We want to reduce the // stack consumption so that the symbolizer can run on small stacks. // Here are some numbers collected with GCC 4.1.0 on x86: // - sizeof(Elf32_Sym) = 16 // - sizeof(Elf32_Shdr) = 40 // - sizeof(Elf64_Sym) = 24 // - sizeof(Elf64_Shdr) = 64 // This implementation is intended to be async-signal-safe but uses // some functions which are not guaranteed to be so, such as memchr() // and memmove(). We assume they are async-signal-safe. // Additional header can be specified by the <API key> // macro to add platform specific defines (e.g. OS_OPENBSD). #ifdef <API key> #include <API key> #endif // <API key> #include "build/build_config.h" #include "utilities.h" #if defined(HAVE_SYMBOLIZE) #include <string.h> #include <algorithm> #include <limits> #include "symbolize.h" #include "demangle.h" <API key> // We don't use assert() since it's not guaranteed to be // async-signal-safe. Instead we define a minimal assertion // macro. So far, we don't need pretty printing for __FILE__, etc. // A wrapper for abort() to make it callable in ? :. static int AssertFail() { abort(); return 0; // Should not reach. } #define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail()) static SymbolizeCallback <API key> = NULL; void <API key>(SymbolizeCallback callback) { <API key> = callback; } static <API key> <API key> = NULL; void <API key>( <API key> callback) { <API key> = callback; } // This function wraps the Demangle function to provide an interface // where the input symbol is demangled in-place. // To keep stack consumption low, we would like this function to not // get inlined. static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size) { char demangled[256]; // Big enough for sane demangled symbols. if (Demangle(out, demangled, sizeof(demangled))) { // Demangling succeeded. Copy to out if the space allows. size_t len = strlen(demangled); if (len + 1 <= (size_t)out_size) { // +1 for '\0'. SAFE_ASSERT(len < sizeof(demangled)); memmove(out, demangled, len + 1); } } } <API key> #if defined(__ELF__) #if defined(HAVE_DLFCN_H) #include <dlfcn.h> #endif #if BUILDFLAG(IS_OPENBSD) #include <sys/exec_elf.h> #else #include <elf.h> #endif #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "symbolize.h" #include "config.h" #include "glog/raw_logging.h" // Re-runs fn until it doesn't cause EINTR. #define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR) <API key> // Read up to "count" bytes from "offset" in the file pointed by file // descriptor "fd" into the buffer starting at "buf" while handling short reads // and EINTR. On success, return the number of bytes read. Otherwise, return ssize_t ReadFromOffset(const int fd, void* buf, const size_t count, const off_t offset) { SAFE_ASSERT(fd >= 0); SAFE_ASSERT(count <= std::numeric_limits<ssize_t>::max()); char *buf0 = reinterpret_cast<char *>(buf); ssize_t num_bytes = 0; while (num_bytes < count) { ssize_t len; NO_INTR(len = pread(fd, buf0 + num_bytes, count - num_bytes, offset + num_bytes)); if (len < 0) { // There was an error other than EINTR. return -1; } if (len == 0) { // Reached EOF. break; } num_bytes += len; } SAFE_ASSERT(num_bytes <= count); return num_bytes; } // Try reading exactly "count" bytes from "offset" bytes in a file // pointed by "fd" into the buffer starting at "buf" while handling // short reads and EINTR. On success, return true. Otherwise, return // false. static bool ReadFromOffsetExact(const int fd, void *buf, const size_t count, const off_t offset) { ssize_t len = ReadFromOffset(fd, buf, count, offset); return len == count; } // Returns elf_header.e_type if the file pointed by fd is an ELF binary. static int FileGetElfType(const int fd) { ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { return -1; } if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) { return -1; } return elf_header.e_type; } // Read the section headers in the given ELF binary, and if a section // of the specified type is found, set the output to this section header // and return true. Otherwise, return false. // To keep stack consumption low, we would like this function to not get // inlined. static ATTRIBUTE_NOINLINE bool <API key>(const int fd, ElfW(Half) sh_num, const off_t sh_offset, ElfW(Word) type, ElfW(Shdr) *out) { // Read at most 16 section headers at a time to save read calls. ElfW(Shdr) buf[16]; for (int i = 0; i < sh_num;) { const ssize_t num_bytes_left = (sh_num - i) * sizeof(buf[0]); const ssize_t num_bytes_to_read = (sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf); const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read, sh_offset + i * sizeof(buf[0])); if (len == -1) { return false; } SAFE_ASSERT(len % sizeof(buf[0]) == 0); const ssize_t num_headers_in_buf = len / sizeof(buf[0]); SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0])); for (int j = 0; j < num_headers_in_buf; ++j) { if (buf[j].sh_type == type) { *out = buf[j]; return true; } } i += num_headers_in_buf; } return false; } // There is no particular reason to limit section name to 63 characters, // but there has (as yet) been no need for anything longer either. const int kMaxSectionNameLen = 64; // name_len should include terminating '\0'. bool <API key>(int fd, const char *name, size_t name_len, ElfW(Shdr) *out) { ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { return false; } ElfW(Shdr) shstrtab; off_t shstrtab_offset = (elf_header.e_shoff + elf_header.e_shentsize * elf_header.e_shstrndx); if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) { return false; } for (int i = 0; i < elf_header.e_shnum; ++i) { off_t <API key> = (elf_header.e_shoff + elf_header.e_shentsize * i); if (!ReadFromOffsetExact(fd, out, sizeof(*out), <API key>)) { return false; } char header_name[kMaxSectionNameLen]; if (sizeof(header_name) < name_len) { RAW_LOG(WARNING, "Section name '%s' is too long (%" PRIuS "); " "section will not be found (even if present).", name, name_len); // No point in even trying. return false; } off_t name_offset = shstrtab.sh_offset + out->sh_name; ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset); if (n_read == -1) { return false; } else if (n_read != name_len) { // Short read -- name could be at end of file. continue; } if (memcmp(header_name, name, name_len) == 0) { return true; } } return false; } // Read a symbol table and look for the symbol containing the // pc. Iterate over symbols in a symbol table and look for the symbol // containing "pc". On success, return true and write the symbol name // to out. Otherwise, return false. // To keep stack consumption low, we would like this function to not get // inlined. static ATTRIBUTE_NOINLINE bool FindSymbol(uint64_t pc, const int fd, char *out, int out_size, uint64_t symbol_offset, const ElfW(Shdr) *strtab, const ElfW(Shdr) *symtab) { if (symtab == NULL) { return false; } const int num_symbols = symtab->sh_size / symtab->sh_entsize; for (int i = 0; i < num_symbols;) { off_t offset = symtab->sh_offset + i * symtab->sh_entsize; // If we are reading Elf64_Sym's, we want to limit this array to // 32 elements (to keep stack consumption low), otherwise we can // have a 64 element Elf32_Sym array. #if __WORDSIZE == 64 #define NUM_SYMBOLS 32 #else #define NUM_SYMBOLS 64 #endif // Read at most NUM_SYMBOLS symbols at once to save read() calls. ElfW(Sym) buf[NUM_SYMBOLS]; int num_symbols_to_read = std::min(NUM_SYMBOLS, num_symbols - i); const ssize_t len = ReadFromOffset(fd, &buf, sizeof(buf[0]) * num_symbols_to_read, offset); SAFE_ASSERT(len % sizeof(buf[0]) == 0); const ssize_t num_symbols_in_buf = len / sizeof(buf[0]); SAFE_ASSERT(num_symbols_in_buf <= num_symbols_to_read); for (int j = 0; j < num_symbols_in_buf; ++j) { const ElfW(Sym)& symbol = buf[j]; uint64_t start_address = symbol.st_value; start_address += symbol_offset; uint64_t end_address = start_address + symbol.st_size; if (symbol.st_value != 0 && // Skip null value symbols. symbol.st_shndx != 0 && // Skip undefined symbols. start_address <= pc && pc < end_address) { ssize_t len1 = ReadFromOffset(fd, out, out_size, strtab->sh_offset + symbol.st_name); if (len1 <= 0 || memchr(out, '\0', out_size) == NULL) { memset(out, 0, out_size); return false; } return true; // Obtained the symbol name. } } i += num_symbols_in_buf; } return false; } // Get the symbol name of "pc" from the file pointed by "fd". Process // both regular and dynamic symbol tables if necessary. On success, // write the symbol name to "out" and return true. Otherwise, return // false. static bool <API key>(const int fd, uint64_t pc, char* out, int out_size, uint64_t base_address) { // Read the ELF header. ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { return false; } ElfW(Shdr) symtab, strtab; // Consult a regular symbol table first. if (<API key>(fd, elf_header.e_shnum, elf_header.e_shoff, SHT_SYMTAB, &symtab)) { if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + symtab.sh_link * sizeof(symtab))) { return false; } if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { return true; // Found the symbol in a regular symbol table. } } // If the symbol is not found, then consult a dynamic symbol table. if (<API key>(fd, elf_header.e_shnum, elf_header.e_shoff, SHT_DYNSYM, &symtab)) { if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + symtab.sh_link * sizeof(symtab))) { return false; } if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { return true; // Found the symbol in a dynamic symbol table. } } return false; } // Thin wrapper around a file descriptor so that the file descriptor // gets closed for sure. FileDescriptor::FileDescriptor(int fd) : fd_(fd) {} FileDescriptor::~FileDescriptor() { if (fd_ >= 0) { close(fd_); } } namespace { // Helper class for reading lines from file. // Note: we don't use ProcMapsIterator since the object is big (it has // a 5k array member) and uses async-unsafe functions such as sscanf() // and snprintf(). class LineReader { public: explicit LineReader(int fd, char *buf, int buf_len, off_t offset) : fd_(fd), buf_(buf), buf_len_(buf_len), offset_(offset), bol_(buf), eol_(buf), eod_(buf) {} // Read '\n'-terminated line from file. On success, modify "bol" // and "eol", then return true. Otherwise, return false. // Note: if the last line doesn't end with '\n', the line will be // dropped. It's an intentional behavior to make the code simple. bool ReadLine(const char **bol, const char **eol) { if (BufferIsEmpty()) { // First time. const ssize_t num_bytes = ReadFromOffset(fd_, buf_, buf_len_, offset_); if (num_bytes <= 0) { // EOF or error. return false; } offset_ += num_bytes; eod_ = buf_ + num_bytes; bol_ = buf_; } else { bol_ = eol_ + 1; // Advance to the next line in the buffer. SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_". if (!HasCompleteLine()) { const int <API key> = eod_ - bol_; // Move the trailing incomplete line to the beginning. memmove(buf_, bol_, <API key>); // Read text from file and append it. char * const append_pos = buf_ + <API key>; const int capacity_left = buf_len_ - <API key>; const ssize_t num_bytes = ReadFromOffset(fd_, append_pos, capacity_left, offset_); if (num_bytes <= 0) { // EOF or error. return false; } offset_ += num_bytes; eod_ = append_pos + num_bytes; bol_ = buf_; } } eol_ = FindLineFeed(); if (eol_ == NULL) { // '\n' not found. Malformed line. return false; } *eol_ = '\0'; // Replace '\n' with '\0'. *bol = bol_; *eol = eol_; return true; } // Beginning of line. const char *bol() { return bol_; } // End of line. const char *eol() { return eol_; } private: explicit LineReader(const LineReader&); void operator=(const LineReader&); char *FindLineFeed() { return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_)); } bool BufferIsEmpty() { return buf_ == eod_; } bool HasCompleteLine() { return !BufferIsEmpty() && FindLineFeed() != NULL; } const int fd_; char * const buf_; const int buf_len_; off_t offset_; char *bol_; char *eol_; const char *eod_; // End of data in "buf_". }; } // namespace // Place the hex number read from "start" into "*hex". The pointer to // the first non-hex character or "end" is returned. static char *GetHex(const char *start, const char *end, uint64_t *hex) { *hex = 0; const char *p; for (p = start; p < end; ++p) { int ch = *p; if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) { *hex = (*hex << 4) | (ch < 'A' ? ch - '0' : (ch & 0xF) + 9); } else { // Encountered the first non-hex character. break; } } SAFE_ASSERT(p <= end); return const_cast<char *>(p); } // Searches for the object file (from /proc/self/maps) that contains // the specified pc. If found, sets |start_address| to the start address // of where this object file is mapped in memory, sets the module base // address into |base_address|, copies the object file name into // |out_file_name|, and attempts to open the object file. If the object // file is opened successfully, returns the file descriptor. Otherwise, // returns -1. |out_file_name_size| is the size of the file name buffer // (including the null-terminator). ATTRIBUTE_NOINLINE int <API key>( uint64_t pc, uint64_t& start_address, uint64_t& end_address, uint64_t& base_address, char* out_file_name, int out_file_name_size) { int object_fd; int maps_fd; NO_INTR(maps_fd = open("/proc/self/maps", O_RDONLY)); FileDescriptor wrapped_maps_fd(maps_fd); if (wrapped_maps_fd.get() < 0) { return -1; } int mem_fd; NO_INTR(mem_fd = open("/proc/self/mem", O_RDONLY)); FileDescriptor wrapped_mem_fd(mem_fd); if (wrapped_mem_fd.get() < 0) { return -1; } // Iterate over maps and look for the map containing the pc. Then // look into the symbol tables inside. char buf[1024]; // Big enough for line of sane /proc/self/maps int num_maps = 0; LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf), 0); while (true) { num_maps++; const char *cursor; const char *eol; if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line. return -1; } // Start parsing line in /proc/self/maps. Here is an example: // 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat // We want start address (08048000), end address (0804c000), flags // (r-xp) and file name (/bin/cat). // Read start address. cursor = GetHex(cursor, eol, &start_address); if (cursor == eol || *cursor != '-') { return -1; // Malformed line. } ++cursor; // Skip '-'. // Read end address. cursor = GetHex(cursor, eol, &end_address); if (cursor == eol || *cursor != ' ') { return -1; // Malformed line. } ++cursor; // Skip ' '. // Read flags. Skip flags until we encounter a space or eol. const char * const flags_start = cursor; while (cursor < eol && *cursor != ' ') { ++cursor; } // We expect at least four letters for flags (ex. "r-xp"). if (cursor == eol || cursor < flags_start + 4) { return -1; // Malformed line. } // Determine the base address by reading ELF headers in process memory. ElfW(Ehdr) ehdr; // Skip non-readable maps. if (flags_start[0] == 'r' && ReadFromOffsetExact(mem_fd, &ehdr, sizeof(ElfW(Ehdr)), start_address) && memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) { switch (ehdr.e_type) { case ET_EXEC: base_address = 0; break; case ET_DYN: // Find the segment containing file offset 0. This will correspond // to the ELF header that we just read. Normally this will have // virtual address 0, but this is not guaranteed. We must subtract // the virtual address from the address where the ELF header was // mapped to get the base address. // If we fail to find a segment for file offset 0, use the address // of the ELF header as the base address. base_address = start_address; for (unsigned i = 0; i != ehdr.e_phnum; ++i) { ElfW(Phdr) phdr; if (ReadFromOffsetExact( mem_fd, &phdr, sizeof(phdr), start_address + ehdr.e_phoff + i * sizeof(phdr)) && phdr.p_type == PT_LOAD && phdr.p_offset == 0) { base_address = start_address - phdr.p_vaddr; break; } } break; default: // ET_REL or ET_CORE. These aren't directly executable, so they don't // affect the base address. break; } } // Check start and end addresses. if (!(start_address <= pc && pc < end_address)) { continue; // We skip this map. PC isn't in this map. } // Check flags. We are only interested in "r*x" maps. if (flags_start[0] != 'r' || flags_start[2] != 'x') { continue; // We skip this map. } ++cursor; // Skip ' '. // Read file offset. uint64_t file_offset; cursor = GetHex(cursor, eol, &file_offset); if (cursor == eol || *cursor != ' ') { return -1; // Malformed line. } ++cursor; // Skip ' '. // Skip to file name. "cursor" now points to dev. We need to // skip at least two spaces for dev and inode. int num_spaces = 0; while (cursor < eol) { if (*cursor == ' ') { ++num_spaces; } else if (num_spaces >= 2) { // The first non-space character after skipping two spaces // is the beginning of the file name. break; } ++cursor; } if (cursor == eol) { return -1; // Malformed line. } // Finally, "cursor" now points to file name of our interest. NO_INTR(object_fd = open(cursor, O_RDONLY)); if (object_fd < 0) { // Failed to open object file. Copy the object file name to // |out_file_name|. strncpy(out_file_name, cursor, out_file_name_size); // Making sure |out_file_name| is always null-terminated. out_file_name[out_file_name_size - 1] = '\0'; return -1; } return object_fd; } } // POSIX doesn't define any async-signal safe function for converting // an integer to ASCII. We'll have to define our own version. // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the // conversion was successful or NULL otherwise. It never writes more than "sz" // bytes. Output will be truncated as needed, and a NUL character is always // appended. // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc. char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) { // Make sure we can write at least one NUL byte. size_t n = 1; if (n > sz) return NULL; if (base < 2 || base > 16) { buf[0] = '\000'; return NULL; } char *start = buf; uintptr_t j = i; // Handle negative numbers (only for base 10). if (i < 0 && base == 10) { // This does "j = -i" while avoiding integer overflow. j = static_cast<uintptr_t>(-(i + 1)) + 1; // Make sure we can write the '-' character. if (++n > sz) { buf[0] = '\000'; return NULL; } *start++ = '-'; } // Loop until we have converted the entire number. Output at least one // character (i.e. '0'). char *ptr = start; do { // Make sure there is still enough space left in our output buffer. if (++n > sz) { buf[0] = '\000'; return NULL; } // Output the next digit. *ptr++ = "0123456789abcdef"[j % base]; j /= base; if (padding > 0) padding } while (j > 0 || padding > 0); // Terminate the output with a NUL character. *ptr = '\000'; // Conversion to ASCII actually resulted in the digits being in reverse // order. We can't easily generate them in forward order, as we can't tell // the number of characters needed until we are done converting. // So, now, we reverse the string (except for the possible "-" sign). while (--ptr > start) { char ch = *ptr; *ptr = *start; *start++ = ch; } return buf; } // Safely appends string |source| to string |dest|. Never writes past the // buffer size |dest_size| and guarantees that |dest| is null-terminated. static void SafeAppendString(const char* source, char* dest, int dest_size) { int dest_string_length = strlen(dest); SAFE_ASSERT(dest_string_length < dest_size); dest += dest_string_length; dest_size -= dest_string_length; strncpy(dest, source, dest_size); // Making sure |dest| is always null-terminated. dest[dest_size - 1] = '\0'; } // Converts a 64-bit value into a hex string, and safely appends it to |dest|. // Never writes past the buffer size |dest_size| and guarantees that |dest| is // null-terminated. static void SafeAppendHexNumber(uint64_t value, char* dest, int dest_size) { // 64-bit numbers in hex can have up to 16 digits. char buf[17] = {'\0'}; SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size); } // The implementation of our symbolization routine. If it // successfully finds the symbol containing "pc" and obtains the // symbol name, returns true and write the symbol name to "out". // Otherwise, returns false. If Callback function is installed via // <API key>(), the function is also called in this function, // and "out" is used as its output. // To keep stack consumption low, we would like this function to not // get inlined. static ATTRIBUTE_NOINLINE bool <API key>(void *pc, char *out, int out_size) { uint64_t pc0 = reinterpret_cast<uintptr_t>(pc); uint64_t start_address = 0; uint64_t end_address = 0; uint64_t base_address = 0; int object_fd = -1; if (out_size < 1) { return false; } out[0] = '\0'; SafeAppendString("(", out, out_size); if (<API key>) { object_fd = <API key>(pc0, start_address, base_address, out + 1, out_size - 1); } else { object_fd = <API key>( pc0, start_address, base_address, end_address, out + 1, out_size - 1); } FileDescriptor wrapped_object_fd(object_fd); #if defined(<API key>) { #else // Check whether a file name was returned. if (object_fd < 0) { #endif if (out[1]) { // The object file containing PC was determined successfully however the // object file was not opened successfully. This is still considered // success because the object file name and offset are known and tools // like asan_symbolize.py can be used for the symbolization. out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated. SafeAppendString("+0x", out, out_size); SafeAppendHexNumber(pc0 - base_address, out, out_size); SafeAppendString(")", out, out_size); return true; } // Failed to determine the object file containing PC. Bail out. return false; } int elf_type = FileGetElfType(wrapped_object_fd.get()); if (elf_type == -1) { return false; } if (<API key>) { // Run the call back if it's installed. // Note: relocation (and much of the rest of this code) will be // wrong for prelinked shared libraries and PIE executables. uint64_t relocation = (elf_type == ET_DYN) ? start_address : 0; int num_bytes_written = <API key>(wrapped_object_fd.get(), pc, out, out_size, relocation); if (num_bytes_written > 0) { out += num_bytes_written; out_size -= num_bytes_written; } } if (!<API key>(wrapped_object_fd.get(), pc0, out, out_size, base_address)) { if (out[1] && !<API key>) { // The object file containing PC was opened successfully however the // symbol was not found. The object may have been stripped. This is still // considered success because the object file name and offset are known // and tools like asan_symbolize.py can be used for the symbolization. out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated. SafeAppendString("+0x", out, out_size); SafeAppendHexNumber(pc0 - base_address, out, out_size); SafeAppendString(")", out, out_size); return true; } return false; } // Symbolization succeeded. Now we try to demangle the symbol. DemangleInplace(out, out_size); return true; } <API key> #elif BUILDFLAG(IS_APPLE) && defined(HAVE_DLADDR) #include <dlfcn.h> #include <string.h> <API key> static ATTRIBUTE_NOINLINE bool <API key>(void *pc, char *out, int out_size) { Dl_info info; if (dladdr(pc, &info)) { if ((int)strlen(info.dli_sname) < out_size) { strcpy(out, info.dli_sname); // Symbolization succeeded. Now we try to demangle the symbol. DemangleInplace(out, out_size); return true; } } return false; } <API key> #elif defined(OS_WINDOWS) || defined(OS_CYGWIN) #include <windows.h> #include <dbghelp.h> #ifdef _MSC_VER #pragma comment(lib, "dbghelp") #endif <API key> class SymInitializer { public: HANDLE process; bool ready; SymInitializer() : process(NULL), ready(false) { // Initialize the symbol handler. process = GetCurrentProcess(); // Defer symbol loading. // We do not request undecorated symbols with SYMOPT_UNDNAME // because the mangling library calls <API key>. SymSetOptions(<API key>); if (SymInitialize(process, NULL, true)) { ready = true; } } ~SymInitializer() { SymCleanup(process); // We do not need to close `HANDLE process` because it's a "pseudo handle." } private: SymInitializer(const SymInitializer&); SymInitializer& operator=(const SymInitializer&); }; static ATTRIBUTE_NOINLINE bool <API key>(void *pc, char *out, int out_size) { const static SymInitializer symInitializer; if (!symInitializer.ready) { return false; } // Resolve symbol information from address. char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(buf); symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME; // We use the ANSI version to ensure the string type is always `char *`. // This could break if a symbol has Unicode in it. BOOL ret = SymFromAddr(symInitializer.process, reinterpret_cast<DWORD64>(pc), 0, symbol); if (ret == 1 && static_cast<int>(symbol->NameLen) < out_size) { // `NameLen` does not include the null terminating character. strncpy(out, symbol->Name, static_cast<size_t>(symbol->NameLen) + 1); out[static_cast<size_t>(symbol->NameLen)] = '\0'; // Symbolization succeeded. Now we try to demangle the symbol. DemangleInplace(out, out_size); return true; } return false; } <API key> #else # error BUG: HAVE_SYMBOLIZE was wrongly set #endif <API key> bool Symbolize(void *pc, char *out, int out_size) { SAFE_ASSERT(out_size >= 0); return <API key>(pc, out, out_size); } <API key> #else /* HAVE_SYMBOLIZE */ #include <assert.h> #include "config.h" <API key> // TODO: Support other environments. bool Symbolize(void *pc, char *out, int out_size) { assert(0); return false; } <API key> #endif
#ifndef <API key> #define <API key> #include <atomic> #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/<API key>.h" #include "third_party/blink/renderer/platform/wtf/threading.h" #include "third_party/blink/renderer/platform/wtf/<API key>.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace base { class <API key>; } namespace blink { class BaseAudioContext; class OfflineAudioContext; class AudioHandler; class AudioNodeOutput; class <API key>; // DeferredTaskHandler manages the major part of pre- and post- rendering tasks, // and provides a lock mechanism against the audio rendering graph. A // DeferredTaskHandler object is created when an BaseAudioContext object is // created. // DeferredTaskHandler outlives the BaseAudioContext only if all of the // following conditions match: // - An audio rendering thread is running, // - It is requested to stop, // - The audio rendering thread calls <API key>(), // - It posts a task of <API key>(), and // - GC happens and it collects the BaseAudioContext before the task execution. class MODULES_EXPORT DeferredTaskHandler final : public <API key><DeferredTaskHandler>, public base::SupportsWeakPtr<DeferredTaskHandler> { public: static scoped_refptr<DeferredTaskHandler> Create( scoped_refptr<base::<API key>> task_runner); ~DeferredTaskHandler(); void HandleDeferredTasks(); void <API key>(); // BaseAudioContext can pull node(s) at the end of each render quantum even // when they are not connected to any downstream nodes. These two methods are // called by the nodes who want to add/remove themselves into/from the // automatic pull lists. void <API key>(scoped_refptr<AudioHandler>); void <API key>(AudioHandler*); // Return true if there is one or more nodes in the automatic pull node list. bool <API key>(); // Called right before <API key>() to handle nodes which need to // be pulled even when they are not connected to anything. void <API key>(uint32_t frames_to_process); // Keep track of AudioNode's that have their channel count mode changed. We // process the changes in the post rendering phase. void <API key>(AudioHandler*); void <API key>(AudioHandler*); // Keep track of AudioNode's that have their channel interpretation // changed. We process the changes in the post rendering phase. void <API key>(AudioHandler*); void <API key>(AudioHandler*); // Only accessed when the graph lock is held. void <API key>(<API key>*); // Only accessed when the graph lock is held. Must be called on the main // thread. void <API key>(<API key>*); void <API key>(AudioNodeOutput*); void <API key>(AudioNodeOutput*); // Break connections between nodes. This is done on the audio thread with the // graph lock. void BreakConnections(); void <API key>(scoped_refptr<AudioHandler>); void <API key>(); void <API key>(); // Clear the context from the rendering and deletable orphan handlers. void <API key>(); bool <API key>() const { return <API key>; } void <API key>() { <API key> = false; } // If |node| requires tail processing, add it to the list of tail // nodes so the tail is processed. void <API key>(scoped_refptr<AudioHandler>); // Remove |node| from the list of tail nodes (because the tail processing is // complete). Set |disable_outputs| to true if the outputs of the handler // should also be disabled. This should be true if the tail is done. But if // we're reconnected or re-enabled, then |disable_outputs| should be false. void <API key>(AudioHandler*, bool disable_outputs); // Remove all tail processing nodes. Should be called only when the // context is done. void <API key>(); // For handlers that have finished processing their tail and require disabling // the ouputs of the handler, we do that here. void <API key>(); // Thread Safety and Graph Locking: void <API key>(); // It is okay to use a relaxed (no-barrier) load here. Because the data // referenced by m_audioThread is not actually being used, thus we do not // need a barrier between the load of m_audioThread and of that data. bool IsAudioThread() const { return CurrentThread() == audio_thread_.load(std::<API key>); } void lock() <API key>(<API key>); bool TryLock() <API key>(true, <API key>); void unlock() UNLOCK_FUNCTION(<API key>); // This locks the audio render thread for OfflineAudioContext rendering. // MUST NOT be used in the real-time audio context. void OfflineLock() <API key>(<API key>); // In DCHECK builds, fails if this thread does not own the context's lock. void AssertGraphOwner() const <API key>(<API key>) { <API key>.AssertAcquired(); } class MODULES_EXPORT GraphAutoLocker { STACK_ALLOCATED(); public: explicit GraphAutoLocker(DeferredTaskHandler& handler) : handler_(handler) { handler_.lock(); } explicit GraphAutoLocker(const BaseAudioContext*); ~GraphAutoLocker() { handler_.unlock(); } private: DeferredTaskHandler& handler_; }; // This is for locking offline render thread (which is considered as the // audio thread) with unlocking on self-destruction at the end of the scope. // Also note that it uses lock() rather than tryLock() because the timing // MUST be accurate on offline rendering. class MODULES_EXPORT <API key> { STACK_ALLOCATED(); public: explicit <API key>(OfflineAudioContext*); ~<API key>() { handler_.unlock(); } private: DeferredTaskHandler& handler_; }; HashSet<scoped_refptr<AudioHandler>>* <API key>() { return &<API key>; } Vector<scoped_refptr<AudioHandler>>* <API key>() { return &<API key>; } // The number of frames to render each time. After construction, this value // is only read (never modified), and may be read by both the audio thread and // the main thread. unsigned int RenderQuantumFrames() const { return <API key>; } private: explicit DeferredTaskHandler(scoped_refptr<base::<API key>>); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); // Check tail processing handlers and remove any handler if the tail // has been processed. void <API key>(); // For the sake of thread safety, we maintain a seperate Vector of // AudioHandlers for "automatic-pull nodes": // |<API key>|. This storage will be copied from // |<API key>| by |<API key>()| at the beginning // or end of the render quantum. HashSet<scoped_refptr<AudioHandler>> <API key>; Vector<scoped_refptr<AudioHandler>> <API key>; // Keeps track if the |<API key>| storage is touched. bool <API key>; // Number of frames to use when rendering the graph. This is the frames to // process for each node. unsigned int <API key> = 128; // Collection of nodes where the channel count mode has changed. We want the // channel count mode to change in the pre- or post-rendering phase so as // not to disturb the running audio thread. HashSet<AudioHandler*> <API key>; HashSet<AudioHandler*> <API key>; // These two HashSet must be accessed only when the graph lock is held. // These raw pointers are safe because their destructors unregister them. HashSet<<API key>*> <API key>; HashSet<AudioNodeOutput*> <API key>; Vector<scoped_refptr<AudioHandler>> <API key>; Vector<scoped_refptr<AudioHandler>> <API key>; // Nodes that are processing its tail. Vector<scoped_refptr<AudioHandler>> <API key>; // Tail processing nodes that are now finished and want the output to be // disabled. This is updated in the audio thread (with the graph lock). The // main thread will disable the outputs. Vector<scoped_refptr<AudioHandler>> <API key>; // Once the associated context closes, new tail processing handlers are not // accepted. bool <API key> = true; // When source nodes are started, we place the handlers here to keep track of // these active sources. We must call AudioHandler::makeConnection() when we // add an AudioNode to this, and must call AudioHandler::breakConnection() // when we remove an AudioNode from this. // This can be accessed from either the main thread or the audio thread, so it // must be protected by the graph lock. HashSet<scoped_refptr<AudioHandler>> <API key>; // When source nodes are finished, the handler is placed here to make a note // of it. At a render quantum boundary, these are used to break the // connection and elements here are removed from |<API key>|. // This must be accessed only from the audio thread. Vector<scoped_refptr<AudioHandler>> <API key>; scoped_refptr<base::<API key>> task_runner_; // Graph locking. RecursiveMutex <API key>; // Protects |<API key>| when updating, processing, and // clearing. (See crbug.com/1061018) mutable Mutex <API key>; std::atomic<base::PlatformThreadId> audio_thread_; }; } // namespace blink #endif // <API key>
.resources.panel .sidebar { padding-left: 0; z-index: 10; display: block; } .resources.panel .sidebar li { height: 18px; white-space: nowrap; } .resources.panel .sidebar li.selected { color: white; text-shadow: rgba(0, 0, 0, 0.33) 1px 1px 0; } .resources.panel .sidebar li.selected .selection { background-image: linear-gradient(to bottom, rgb(162, 177, 207), rgb(120, 138, 177)); border-top: 1px solid #979797; height: 18px; } .resources.panel .sidebar :focus li.selected .selection { background-image: linear-gradient(to bottom, rgb(92, 147, 213), rgb(21, 83, 170)); border-top: 1px solid rgb(68, 128, 200); } body.inactive .resources.panel .sidebar li.selected .selection { background-image: linear-gradient(to bottom, rgb(180, 180, 180), rgb(138, 138, 138)); border-top: 1px solid rgb(151, 151, 151); } .resources.panel .sidebar .icon { width: 16px; height: 16px; float: left; } .resources.panel .<API key> { overflow: hidden; position: relative; text-overflow: ellipsis; padding-left: 2px; top: 1px; } .resources-toolbar { border-top: 1px solid #ccc; background-color: #eee; } li.selected .<API key> { color: white; } .<API key> { padding-left: 2px; color: rgb(80, 80, 80); text-shadow: none; } .resources.panel .status { float: right; height: 16px; margin-top: 1px; margin-left: 4px; line-height: 1em; } .resources.panel li .status .bubble-repeat-count { height: 13px; margin-top: 1px; padding-top: 0; } .storage-view { display: flex; overflow: hidden; } .storage-view { overflow: hidden; } .storage-view .data-grid:not(.inline) { border: none; flex: auto; } .storage-view .storage-table-error { color: rgb(66%, 33%, 33%); font-size: 24px; font-weight: bold; padding: 10px; display: flex; align-items: center; justify-content: center; } .storage-view.query { padding: 2px 0; overflow-y: overlay; overflow-x: hidden; } .<API key> { position: relative; padding: 1px 22px 1px 24px; min-height: 16px; white-space: pre-wrap; -webkit-user-modify: <API key>; -webkit-user-select: text; } .database-user-query::before, .<API key>::before, .<API key>::before { position: absolute; display: block; content: ""; left: 7px; top: 0.8em; width: 10px; height: 10px; margin-top: -7px; -webkit-user-select: none; background-image: url(Images/toolbarButtonGlyphs.png); background-size: 352px 168px; } @media (-<API key>: 1.5) { .database-user-query::before, .<API key>::before, .<API key>::before { background-image: url(Images/<API key>.png); } } /* media */ .<API key>::before { background-position: -192px -96px; } .database-user-query { position: relative; border-bottom: 1px solid rgb(245, 245, 245); padding: 1px 22px 1px 24px; min-height: 16px; flex-shrink: 0; } .database-user-query::before { background-position: -192px -107px; } .database-query-text { color: rgb(0, 128, 255); -webkit-user-select: text; } .<API key> { position: relative; padding: 1px 22px 1px 24px; min-height: 16px; margin-left: -24px; padding-right: 0; } .<API key>.error { color: red; -webkit-user-select: text; } .<API key>.error::before { background-position: -213px -96px; } .<API key> .icon { content: url(Images/resourcePlainIcon.png); } .children.small .<API key> .icon { content: url(Images/<API key>.png); } .<API key>.<API key> .icon { position: relative; background-image: url(Images/resourcePlainIcon.png); background-repeat: no-repeat; content: ""; } .<API key> .<API key> { position: absolute; margin: auto; top: 3px; bottom: 4px; left: 5px; right: 5px; max-width: 18px; max-height: 21px; min-width: 1px; min-height: 1px; } .children.small .<API key>.<API key> .icon { background-image: url(Images/<API key>.png); content: ""; } .children.small .<API key> .<API key> { top: 2px; bottom: 1px; left: 3px; right: 3px; max-width: 8px; max-height: 11px; overflow: hidden; } .<API key>.<API key> .icon { content: url(Images/<API key>.png); } .children.small .<API key>.<API key> .icon { content: url(Images/<API key>.png); } .<API key>.<API key> .icon { content: url(Images/resourceCSSIcon.png); } .children.small .<API key>.<API key> .icon { content: url(Images/<API key>.png); } .<API key>.<API key> .icon { position: relative; background-image: url(Images/resourcePlainIcon.png); background-repeat: no-repeat; content: ""; } .children.small .<API key>.<API key> .icon { background-image: url(Images/<API key>.png); content: ""; } .<API key>.resources-type-font .icon { content: url(Images/resourcePlainIcon.png); } .children.small .<API key>.resources-type-font .icon { content: url(Images/<API key>.png); } .<API key>.<API key> .icon { content: url(Images/resourceJSIcon.png); } .children.small .<API key>.<API key> .icon { content: url(Images/<API key>.png); } .<API key>.resources-type-xhr .icon { content: url(Images/resourcePlainIcon.png); } .children.small .<API key>.resources-type-xhr .icon { content: url(Images/<API key>.png); } .<API key> .icon { content: url(Images/frame.png); } .<API key> .icon { content: url(Images/database.png); } .<API key> .icon { content: url(Images/databaseTable.png); } .<API key> .icon { content: url(Images/indexedDB.png); } .<API key> .icon { content: url(Images/<API key>.png); } .<API key> .icon { content: url(Images/indexedDBIndex.png); } .<API key> .icon { content: url(Images/<API key>.png); } .<API key> .icon { content: url(Images/indexedDB.png); } .<API key> .icon { content: url(Images/serviceWorker.svg); } .<API key>.local-storage .icon { content: url(Images/localStorage.png); } .<API key>.session-storage .icon { content: url(Images/sessionStorage.png); } .<API key> .icon { content: url(Images/cookie.png); } .<API key> .icon { content: url(Images/applicationCache.png); } .<API key> .icon { content: url(Images/fileSystem.png); }
#ifndef <API key> #define <API key> #include "chromeos/assistant/internal/libassistant/shared_headers.h" #include "chromeos/services/libassistant/public/cpp/assistant_timer.h" namespace assistant { namespace api { class <API key>; namespace params { enum class TimerStatus; class Timer; class TimerParams; } // namespace params } // namespace api } // namespace assistant namespace chromeos { namespace libassistant { ::assistant::api::<API key> <API key>( const std::vector<chromeos::assistant::AssistantTimer>& all_curr_timers); // `timer_params` contains the information of all the current timers. std::vector<assistant::AssistantTimer> <API key>( const ::assistant::api::params::TimerParams& timer_params); void <API key>(const assistant::AssistantTimer& input, ::assistant::api::params::Timer* output); void <API key>( const ::assistant::api::params::Timer& input, chromeos::assistant::AssistantTimer* output); // Used both in |AssistantClientV1| and |FakeAssistantClient|. std::vector<chromeos::assistant::AssistantTimer> <API key>( const std::vector<assistant_client::AlarmTimerManager::Event>& events); } // namespace libassistant } // namespace chromeos #endif // <API key>
#include <string> #include <boost/filesystem.hpp> #include <boost/optional.hpp> #include <sqlite3.h> namespace osquery { static boost::optional<std::string> <API key>( const char* path, char escape_symbol, bool allow_quoting, bool shortest) { size_t length = strlen(path); std::string result; size_t pos = 0; // Skip spaces for (; pos < length; ++pos) { if (!isspace(path[pos])) { break; } } std::string temp_string; bool is_quoted = false; bool is_escaped = false; for (; pos < length; ++pos) { if (is_escaped) { temp_string += path[pos]; is_escaped = false; continue; } if (allow_quoting && path[pos] == '"') { is_quoted = !is_quoted; continue; } if (path[pos] == escape_symbol) { is_escaped = true; continue; } if (!is_quoted && isspace(path[pos])) { // validate temp string boost::filesystem::path test_path = temp_string; auto status = boost::filesystem::status(test_path); if (boost::filesystem::exists(status) && !boost::filesystem::is_directory(status)) { result = temp_string; if (shortest) { break; } } } temp_string += path[pos]; } if (result.length() == 0 || !shortest) { boost::filesystem::path test_path = temp_string; auto status = boost::filesystem::status(test_path); if (boost::filesystem::exists(status) && !boost::filesystem::is_directory(status)) { result = temp_string; } } return result; } static boost::optional<std::string> <API key>( int argc, sqlite3_value** argv, bool shortest) { if (argc == 0) { return boost::none; } // NULLs are not allowed for (int i = 0; i < argc; i++) { if (SQLITE_NULL == sqlite3_value_type(argv[i])) { return boost::none; } } const char* path = reinterpret_cast<const char*>(sqlite3_value_text(argv[0])); bool allow_quoting = false; if (argc > 1) { allow_quoting = sqlite3_value_int(argv[1]) != 0 ? true : false; } #ifdef WIN32 char escape_symbol = '^'; #else char escape_symbol = '\\'; #endif if (argc > 2) { const char* <API key> = reinterpret_cast<const char*>(sqlite3_value_text(argv[2])); if (<API key> == NULL || std::strlen(<API key>) != 1) { return boost::none; } escape_symbol = <API key>[0]; } return <API key>( path, escape_symbol, allow_quoting, shortest); } static void <API key>(sqlite3_context* context, int argc, sqlite3_value** argv) { auto result = <API key>(argc, argv, true); if (result) { sqlite3_result_text(context, result->c_str(), static_cast<int>(result->size()), SQLITE_TRANSIENT); } else { <API key>( context, "Invalid inputs to <API key>", -1); } } static void isPathDeterministic(sqlite3_context* context, int argc, sqlite3_value** argv) { auto shortest = <API key>(argc, argv, true); if (shortest) { const char* path = (const char*)sqlite3_value_text(argv[0]); if (shortest->length() == 0 || shortest->length() == strlen(path)) { // There are 2 cases: // 1 - empty string, all parts of path are invalid, // so path is deterministic // 2 - short == full, then there is only 1 valid path sqlite3_result_int(context, 1); return; } else { auto longest = <API key>(argc, argv, false); if (longest) { sqlite3_result_int(context, shortest->length() == longest->length() ? 1 : 0); return; } } } <API key>(context, "Invalid inputs to <API key>", -1); } static void getParentDirectory(sqlite3_context* context, int argc, sqlite3_value** argv) { if (sqlite3_value_type(argv[0]) != SQLITE_TEXT) { <API key>( context, "Invalid inputs to parent_directory, TEXT was expected", -1); return; } const char* path = reinterpret_cast<const char*>(sqlite3_value_text(argv[0])); if (path == nullptr) { sqlite3_result_null(context); return; } int pos = 0; int last_slash_pos = -1; #if defined(OSQUERY_WINDOWS) char directory_symbol = '\\'; #elif defined(OSQUERY_POSIX) char directory_symbol = '/'; #else #error Unsupported platform #endif while (path[pos] != '\0') { if (path[pos] == directory_symbol) { last_slash_pos = pos; } pos++; } if (last_slash_pos < 0) { // No parent directory sqlite3_result_null(context); return; } char* result = reinterpret_cast<char*>(malloc(last_slash_pos)); memcpy(result, path, last_slash_pos); sqlite3_result_text(context, result, last_slash_pos, free); } void <API key>(sqlite3* db) { <API key>(db, "<API key>", -1, SQLITE_UTF8 | <API key>, nullptr, isPathDeterministic, nullptr, nullptr); <API key>(db, "<API key>", -1, SQLITE_UTF8 | <API key>, nullptr, <API key>, nullptr, nullptr); <API key>(db, "parent_directory", 1, SQLITE_UTF8 | <API key>, nullptr, getParentDirectory, nullptr, nullptr); } } // namespace osquery
#endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; namespace Kooboo.CMS.Common.Runtime.Mvc { public class <API key> : <API key> { private readonly IEngine _engine; <summary> Initializes a new instance of the <see cref="<API key>"/> class. </summary> <param name="kernel">The kernel.</param> public <API key>(IEngine engine) { this._engine = engine; } <summary> Gets the controller attributes. </summary> <param name="controllerContext">The controller context.</param> <param name="actionDescriptor">The action descriptor.</param> <returns>The filters defined by attributes</returns> protected override IEnumerable<FilterAttribute> <API key>( ControllerContext controllerContext, ActionDescriptor actionDescriptor) { var attributes = base.<API key>(controllerContext, actionDescriptor); foreach (var attribute in attributes) { this._engine.InjectProperties(attribute); } return attributes; } <summary> Gets the action attributes. </summary> <param name="controllerContext">The controller context.</param> <param name="actionDescriptor">The action descriptor.</param> <returns>The filters defined by attributes.</returns> protected override IEnumerable<FilterAttribute> GetActionAttributes( ControllerContext controllerContext, ActionDescriptor actionDescriptor) { var attributes = base.GetActionAttributes(controllerContext, actionDescriptor); foreach (var attribute in attributes) { this._engine.InjectProperties(attribute); } return attributes; } } }
@IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0\..\optipng-bin\cli.js" %* ) ELSE ( node "%~dp0\..\optipng-bin\cli.js" %* )
using System; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Fscc { <summary> the response packet of <API key> </summary> public class <API key> : FsccStandardPacket<<API key>> { #region Properties <summary> the command of fscc packet </summary> public override uint Command { get { return (uint)FsControlCommand.<API key>; } } #endregion #region Constructors <summary> default constructor </summary> public <API key>() : base() { } #endregion #region Marshaling and Unmarshaling Methods <summary> marshaling this packet to bytes. </summary> <returns>the bytes of this packet </returns> public override byte[] ToBytes() { byte[] payload; if (this.Payload.Data == null || this.Payload.Data.Length == 0) { payload = new byte[0]; } else { payload = new byte[this.Payload.Data.Length]; Array.Copy(this.Payload.Data, payload, payload.Length); } return payload; } <summary> unmarshaling packet from bytes </summary> <param name = "packetBytes">the bytes of packet </param> public override void FromBytes(byte[] packetBytes) { byte[] payload; if (packetBytes == null || packetBytes.Length == 0) { payload = new byte[0]; } else { payload = new byte[packetBytes.Length]; Array.Copy(packetBytes, payload, packetBytes.Length); } <API key> transceivePayload = new <API key>(); transceivePayload.Data = payload; this.Payload = transceivePayload; } #endregion } }
<?php declare(strict_types=1); namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\<API key> */ final class <API key> extends AbstractSetTest { }
title: Telerik.Web.UI.GridEditableItem page_title: Telerik.Web.UI.GridEditableItem description: Telerik.Web.UI.GridEditableItem # Telerik.Web.UI.GridEditableItem Represents the base class for any items that display and edit data in a Telerik.Web.UI.GridTableView GridTableViewof RadGrid. Inheritors has the capabilities to:bullet Locate a table cell based on the column unique namesExtract values from the cells of column editorsHas a dictionary of saved-old-values that are necessary for optimistic concurency editing oprationsEdit/browse modeEditManager instance, which is capable of locating the column editors ## Inheritance Hierarchy * System.Object * System.Web.UI.Control * System.Web.UI.WebControls.WebControl * System.Web.UI.WebControls.TableRow * Telerik.Web.UI.GridTableRow * Telerik.Web.UI.GridItem * Telerik.Web.UI.GridEditableItem ## Properties EditManager `GridEditManager` Allows you to access the column editors Item `TableCell` Item `TableCell` SavedOldValues `IDictionary` Gets the old value of the edited item CanExtractValues `Boolean` KeyValues `String` OwnerTableView `GridTableView` Gets a reference to the GridTableView that owns this GridItem. OwnerID `String` Gets the ClientID of the GridTableView that owns this instance. OwnerGridID `String` Gets the ClientID of the RadGrid instance that owns the item. # Remarks This would be useful if several controls use the same eventhandler and you need to diferentiate the Grid instances in the handler. HasChildItems `Boolean` Gets a value indicating whether this item has child items - or items somehow related to this. CanExpand `Boolean` Gets a value indicating whether the item can be "expanded" to show its child items DataItem `Object` The original DataItem from the DataSource. See examples section below. DataSetIndex `Int32` Gets the index of the GridDataItem in the underlying DataTable/specified table from a DataSet. ItemIndex `Int32` Gets the index of the grid item among the collection. This index also can be used to get the DataKeyValues corresponding to this item from a GridTableView. ClientRowIndex `Int32` Gets the index of the row as in the html table object rendered on the client RowIndex `Int32` Gets the index of the item in the rows collection of the underlying Table server control <API key> `Int32` Get the unique item index among all the item in the hierarchy. This index is used when setting item to selected, edited, etc ItemType `GridItemType` Gets the respective GridItemType of the grid item. Expanded `Boolean` Gets or sets a value indicating whether the grid item is expanded or collapsed. ConditionalExpanded `Boolean` Used in HierarchyLoadMode="Conditional" Display `Boolean` Sets whether the GridItem will be visible or with style="display:none;" Selected `Boolean` Gets or set a value indicating whether the grid item is selected SelectableMode `<API key>` Gets or sets a value determining if the chould be selected either on the client or on the server. Edit `Boolean` Sets the Item in edit mode. Requires Telerik RadGrid to rebind. # Remarks If is set to InPlace, the grid column editors will be displayed inline of this item. If is set to EditForms, a new GridItem will be created, which will be child of this item (GridEditFormItem). The new item will hold the edit form. GroupIndex `String` Gets the index of the Item in the group. This works only when grouping. IsDataBound `Boolean` Gets a value indicating whether the grid item is bound to a data source. IsInEditMode `Boolean` Gets a value indicating whether the grid item is in edit mode at the moment. OriginalClientID `String` ClientID `String` Gets the server control identifier generated by ASP.NET. ## Methods <API key> # Returns `System.Void` ExtractValues Extracts values for each column, using # Parameters # newValues `System.Collections.IDictionary` This dictionary to fill, this parameter should not be null # Returns `System.Void` UpdateValues Extracts values for each column, using and updates values in provided object; # Parameters # objectToUpdate `System.Object` The object that should be updated # Returns `System.Void` GetDataKeyValue Get the DataKeyValues from the owner GridTableView with the corresponding item ItemIndex and keyName. The keyName should be one of the specified in the array # Parameters # keyName `System.String` data key name # Returns `System.Object` data key value FireCommandEvent Use this method to simulate item command event that bubbles to RadGrid and can be handeled automatically or in a custom manner, handling RadGrid.ItemCommand event. # Parameters # commandName `System.String` command to bubble, for example 'Page' # commandArgument `System.Object` command argument, for example 'Next' # Returns `System.Void` RestoreDecorator This method is not intended to be used directly from your code. # Returns `System.Void` Initialize This method is not intended to be used directly from your code # Returns `System.Void` SetupItem This method is not intended to be used directly from your code # Returns `System.Void` PrepareItemStyle Override this method to change the default logic for rendering the item # Returns `System.Void` <API key> Override this method to change the default logic for item visibility # Returns `System.Void` <API key> Used after postback before ViewState becomes available - for example in ItemCreated and ItemDataBound events # Parameters # value `System.String` # Returns `System.Void` <API key> # Returns `System.Void` <API key> # Returns `System.Void` SetChildrenVisible # Returns `System.Void` SetVisibleChildren # Returns `System.Void` <API key> # Returns `System.Void` CalcColSpan Calculate column-span value for a cell using column list, when the cell indicated with FromCellIndex should be spanned to ToCellIndex # Parameters # columns `Telerik.Web.UI.GridColumn` columns - visible property is taken in count # FromCellIndex `System.Int32` cell inbdex of spanned cell # ToCellIndex `System.Int32` cell index of next not-spanned cell or -1 for the last cell index # Returns `System.Int32` ColSpan number
{% extends "problem/base.html" %} {% load staticfiles %} {% load bootstrap %} {% block title_name %} <title>Edit Problem {{ problem.pk }}</title> {% endblock title_name %} {% block import_source %} {{ block.super }} <link rel="stylesheet" href="{% static 'problem/css/edit.css' %}"> {% endblock %} {% block body_block %} <div class="container" id="Body"> <h2> {{ problem.pk }} - {{ problem.pname }} <a href="{% url 'problem:detail' problem.pk %}" class="btn btn-primary"> See this problem </a> <a href="{% url 'problem:problem' %}" class="btn btn-info"> Back to problem panel </a> </h2> <div style="width:80%; float:left;"> <ul class="nav nav-tabs" role="tablist"> <li class="active"> <a href="#info" role="tab" data-toggle="tab">Info</a> </li> <li> <a href="#description" role="tab" data-toggle="tab">Description</a> </li> <li> <a href="#sample_io" role="tab" data-toggle="tab">Sample IO</a> </li> <li> <a href="#tag" role="tab" data-toggle="tab">Tag</a> </li> <li> <a href="#testcase" role="tab" data-toggle="tab">TestCase</a> </li> </ul> <div class="tab-content"> <form method="POST" id="problem_info" action="" enctype="multipart/form-data"> {{ form.media }} <div> <input type="submit" value="Preview" class="btn btn-success" id="preview_button"> <input type="submit" value="Save" class="btn btn-primary" id="save_button"> <a class="btn btn-warning" href="{% url 'problem:detail' problem.pk %}">Cancel</a> </div> {% csrf_token %} <div class="tab-pane active" id="info"> {% include "problem/editTab/info.html" with form=form pid=problem.pk path=path %} </div> <div class="tab-pane" id="description"> {{ form.description|bootstrap }} {{ form.input|bootstrap }} {{ form.output|bootstrap }} </div> <div class="tab-pane" id="sample_io"> <div class="panel panel-default" style="float:left;width:47%"> <div class="panel-heading">Sample Input</div> <textarea name="sample_in" class="panel-body" style="width:100%" rows="20">{{ problem.sample_in }}</textarea> </div> <div class="panel panel-default" style="float:right;width:47%"> <div class="panel-heading">Sample Output</div> <textarea name="sample_out" class="panel-body" style="width:100%" rows="20">{{ problem.sample_out }}</textarea> </div> </div> </form> <div class="tab-pane" id="tag"> {% include "problem/editTab/tag.html" with pid=problem.pk %} </div> <div class="tab-pane" id="testcase"> {% include "problem/editTab/testcase.html" with pid=problem.pk %} </div> </div> </div> </div> <script src="{% static 'problem/js/edit.js' %}"></script> </body> {% endblock %}