code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package de.darwinspl.feature.graphical.configurator.predicates; import java.util.function.Predicate; import org.eclipse.emf.ecore.util.EcoreUtil; import eu.hyvar.dataValues.HyValue; import eu.hyvar.feature.HyFeatureAttribute; import eu.hyvar.feature.configuration.HyAttributeValueAssignment; public class DwConfiguratorElementHasAttributePredicate<HyConfigurationElement> implements Predicate<HyConfigurationElement> { public HyFeatureAttribute attribute; public HyValue value; @Override public boolean test(HyConfigurationElement configuration) { if(configuration instanceof HyAttributeValueAssignment){ HyAttributeValueAssignment attributeValueAssignment = (HyAttributeValueAssignment) configuration; if(EcoreUtil.equals(attributeValueAssignment.getAttribute(), attribute) && EcoreUtil.equals(attributeValueAssignment.getValue(), value)) { return true; } } return false; } }
HyVar/DarwinSPL
plugins/de.darwinspl.feature.graphical.configurator/src/de/darwinspl/feature/graphical/configurator/predicates/DwConfiguratorElementHasAttributePredicate.java
Java
apache-2.0
909
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <title>Communicator</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Communicator"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Communicator.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/myrobotlab/service/interfaces/CommunicationInterface.html" title="interface in org.myrobotlab.service.interfaces"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/myrobotlab/service/interfaces/HTTPProcessor.html" title="interface in org.myrobotlab.service.interfaces"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/myrobotlab/service/interfaces/Communicator.html" target="_top">Frames</a></li> <li><a href="Communicator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.myrobotlab.service.interfaces</div> <h2 title="Interface Communicator" class="title">Interface Communicator</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../org/myrobotlab/net/CommObjectStreamOverDynamicProtocol.html" title="class in org.myrobotlab.net">CommObjectStreamOverDynamicProtocol</a>, <a href="../../../../org/myrobotlab/net/CommObjectStreamOverTCP.html" title="class in org.myrobotlab.net">CommObjectStreamOverTCP</a>, <a href="../../../../org/myrobotlab/net/CommObjectStreamOverUDP.html" title="class in org.myrobotlab.net">CommObjectStreamOverUDP</a>, <a href="../../../../org/myrobotlab/service/RemoteAdapter.html" title="class in org.myrobotlab.service">RemoteAdapter</a>, <a href="../../../../org/myrobotlab/service/XMPP.html" title="class in org.myrobotlab.service">XMPP</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">Communicator</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/myrobotlab/service/interfaces/Communicator.html#addClient(java.net.URI, java.lang.Object)">addClient</a></strong>(java.net.URI&nbsp;uri, java.lang.Object&nbsp;commData)</code> <div class="block">DEPRICATE adds remote client data - the uri key will be used for messages which need to be sent to the remote client the commData is all the data necessary to communicate to that client there might be enough info in just the uri - but depending on the protocol - more info might be needed</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.HashMap&lt;java.net.URI,<a href="../../../../org/myrobotlab/net/CommData.html" title="class in org.myrobotlab.net">CommData</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/myrobotlab/service/interfaces/Communicator.html#getClients()">getClients</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/myrobotlab/service/interfaces/Communicator.html#sendRemote(java.net.URI, org.myrobotlab.framework.Message)">sendRemote</a></strong>(java.net.URI&nbsp;uri, <a href="../../../../org/myrobotlab/framework/Message.html" title="class in org.myrobotlab.framework">Message</a>&nbsp;msg)</code> <div class="block">will send a message to the mrl key'ed uri the expectation is the uri is directly from the hosts registry in runtime therefore it has the following format mrl://[hostname]/proto://protohost:protoport/otherkeyinfo e.g.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="sendRemote(java.net.URI, org.myrobotlab.framework.Message)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sendRemote</h4> <pre>void&nbsp;sendRemote(java.net.URI&nbsp;uri, <a href="../../../../org/myrobotlab/framework/Message.html" title="class in org.myrobotlab.framework">Message</a>&nbsp;msg)</pre> <div class="block">will send a message to the mrl key'ed uri the expectation is the uri is directly from the hosts registry in runtime therefore it has the following format mrl://[hostname]/proto://protohost:protoport/otherkeyinfo e.g. a tcp connection throughh a RemoteAdapter instance named "remote" would be mrl://remote/tcp://somehost:6767</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>uri</code> - </dd><dd><code>msg</code> - </dd></dl> </li> </ul> <a name="addClient(java.net.URI, java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>addClient</h4> <pre>void&nbsp;addClient(java.net.URI&nbsp;uri, java.lang.Object&nbsp;commData)</pre> <div class="block">DEPRICATE adds remote client data - the uri key will be used for messages which need to be sent to the remote client the commData is all the data necessary to communicate to that client there might be enough info in just the uri - but depending on the protocol - more info might be needed</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>uri</code> - </dd><dd><code>commData</code> - </dd></dl> </li> </ul> <a name="getClients()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getClients</h4> <pre>java.util.HashMap&lt;java.net.URI,<a href="../../../../org/myrobotlab/net/CommData.html" title="class in org.myrobotlab.net">CommData</a>&gt;&nbsp;getClients()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Communicator.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/myrobotlab/service/interfaces/CommunicationInterface.html" title="interface in org.myrobotlab.service.interfaces"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/myrobotlab/service/interfaces/HTTPProcessor.html" title="interface in org.myrobotlab.service.interfaces"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/myrobotlab/service/interfaces/Communicator.html" target="_top">Frames</a></li> <li><a href="Communicator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
sujitbehera27/MyRoboticsProjects-Arduino
javadoc/org/myrobotlab/service/interfaces/Communicator.html
HTML
apache-2.0
10,492
package network import "github.com/Azure/azure-sdk-for-go/version" // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { return "Azure-SDK-For-Go/" + Version() + " network/2020-11-01" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { return version.Number }
cilium/cilium
vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2020-11-01/network/version.go
GO
apache-2.0
673
(Click "Preview" to turn any URL into a clickable link) If you have build or run problems, please read [troubleshooting](https://github.com/DiligentGraphics/DiligentEngine/blob/master/Troubleshooting.md) first. Please double-check that your [code is up-to-date, including all submodules](https://github.com/DiligentGraphics/DiligentEngine#cloning-the-repository). If you have a question that does not require creating an issue, you may ask it on [discord](https://discord.gg/t7HGBK7). For performance issues, please make sure you are running release builds. Debug builds may be significantly slower, especially on Windows. For GPU-related problems, please make sure you have up-to-date drivers. Please provide the following information: - OS and version you are running (e.g. Windows 10.0.18362, MacOS Catalina 10.15, etc.) - Build tools and configuration you used to build the engine (e.g. Visual Studio 2017 Debug x64 + CMake 3.15.4) - GPU and driver version you have installed on your system - Debug output, especially messages from Diligent - Call stack (if available) - If you experience a problem with one back-end, please try running other back-ends and see if the same issue arises
DiligentGraphics/DiligentSamples
.github/issue_template.md
Markdown
apache-2.0
1,197
# Copyright 2014 N3TWORK, Inc. # # Licensed under Apache 2.0 - see the LICENSE file
optimizely/chef-druid
recipes/default.rb
Ruby
apache-2.0
84
package org.batfish.datamodel; import static org.batfish.datamodel.matchers.IpSpaceMatchers.containsIp; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import com.google.common.collect.ImmutableList; import java.io.IOException; import org.batfish.common.util.BatfishObjectMapper; import org.junit.Test; public class IpSpaceTest { @Test public void testIpSpace() { IpWildcardSetIpSpace any = IpWildcardSetIpSpace.builder().including(IpWildcard.ANY).build(); IpWildcardSetIpSpace justMax = IpWildcardSetIpSpace.builder().including(IpWildcard.create(Ip.MAX)).build(); IpWildcardSetIpSpace anyExceptMax = IpWildcardSetIpSpace.builder() .including(IpWildcard.ANY) .excluding(IpWildcard.create(Ip.MAX)) .build(); IpWildcardSetIpSpace none1 = IpWildcardSetIpSpace.builder().build(); IpWildcardSetIpSpace none2 = IpWildcardSetIpSpace.builder().including(IpWildcard.ANY).excluding(IpWildcard.ANY).build(); IpWildcardSetIpSpace someButNotMax = IpWildcardSetIpSpace.builder().including(IpWildcard.parse("1.2.3.4")).build(); /* * Contains every IP, so should contain Ip.MAX */ assertThat(any, containsIp(Ip.MAX)); /* * Contains just IP.MAX, so should contain Ip.MAX */ assertThat(justMax, containsIp(Ip.MAX)); /* * Should not contain Ip.MAX because of explicit blacklist */ assertThat(anyExceptMax, not(containsIp(Ip.MAX))); /* * Should not contain Ip.MAX because contains nothing */ assertThat(none1, not(containsIp(Ip.MAX))); /* * Should not contain Ip.MAX because of general blacklist */ assertThat(none2, not(containsIp(Ip.MAX))); /* * Should not contain Ip.MAX because not in whitelist */ assertThat(someButNotMax, not(containsIp(Ip.MAX))); } @Test public void testIpSpaceJacksonSerialization() throws IOException { Ip ip = Ip.parse("1.0.0.0"); IpIpSpace ipIpSpace = ip.toIpSpace(); Prefix p = Prefix.create(ip, 24); IpSpace prefixIpSpace = p.toIpSpace(); IpWildcard ipWildcard1 = IpWildcard.create(p); IpWildcardIpSpace ipWildcard1IpSpace = ipWildcard1.toIpSpace(); IpWildcard ipWildcard2 = IpWildcard.create(ip); IpWildcardIpSpace ipWildcard2IpSpace = ipWildcard2.toIpSpace(); IpWildcard ipWildcard3 = IpWildcard.ipWithWildcardMask(ip, Ip.parse("0.255.0.255")); IpWildcardIpSpace ipWildcard3IpSpace = ipWildcard3.toIpSpace(); IpSpace ipWildcardSetIpSpace = IpWildcardSetIpSpace.builder().including(ipWildcard1, ipWildcard2, ipWildcard3).build(); IpSpace aclIpSpace1 = AclIpSpace.permitting(ipWildcardSetIpSpace) .thenPermitting(ipIpSpace) .thenPermitting(prefixIpSpace) .thenRejecting(ipWildcard1IpSpace) .thenPermitting(EmptyIpSpace.INSTANCE) .thenRejecting(UniverseIpSpace.INSTANCE) .build(); for (IpSpace ipSpace : ImmutableList.<IpSpace>of( ipIpSpace, prefixIpSpace, ipWildcard1IpSpace, ipWildcard2IpSpace, ipWildcard3IpSpace, ipWildcardSetIpSpace, aclIpSpace1)) { String jsonString = BatfishObjectMapper.writePrettyString(ipSpace); IpSpace deserializedIpSpace = BatfishObjectMapper.mapper().readValue(jsonString, IpSpace.class); /* IpSpace should be equal to deserialized version */ assertThat(ipSpace, equalTo(deserializedIpSpace)); } } }
intentionet/batfish
projects/batfish-common-protocol/src/test/java/org/batfish/datamodel/IpSpaceTest.java
Java
apache-2.0
3,615
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.sakserv.minicluster.mapreduce; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class Driver { private static Configuration configuration; public Configuration getConfiguration() { return configuration; } public void setConfiguration(Configuration configuration) { this.configuration = configuration; } public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("usage: [input] [output]"); System.exit(-1); } if (null == configuration) { configuration = new Configuration(); } Job job = Job.getInstance(configuration); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(WordMapper.class); job.setReducerClass(SumReducer.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setJarByClass(Driver.class); job.waitForCompletion(true); } }
yonchev/hadoop-mini-clusters
test/main/java/com/github/sakserv/minicluster/mapreduce/Driver.java
Java
apache-2.0
2,197
package filter import ( "fmt" "strings" "github.com/elastic/beats/libbeat/common" "github.com/elastic/beats/libbeat/logp" ) type FilterCondition struct { } type FilterRule interface { Filter(event common.MapStr) (common.MapStr, error) String() string } /* extends FilterRule */ type IncludeFields struct { Fields []string // condition } /* extend FilterRule */ type DropFields struct { Fields []string // condition } type FilterList struct { filters []FilterRule } /* FilterList methods */ func New(config []FilterConfig) (*FilterList, error) { Filters := &FilterList{} Filters.filters = []FilterRule{} logp.Debug("filter", "configuration %v", config) for _, filterConfig := range config { if filterConfig.DropFields != nil { Filters.Register(NewDropFields(filterConfig.DropFields.Fields)) } if filterConfig.IncludeFields != nil { Filters.Register(NewIncludeFields(filterConfig.IncludeFields.Fields)) } } logp.Debug("filter", "filters: %v", Filters) return Filters, nil } func (filters *FilterList) Register(filter FilterRule) { filters.filters = append(filters.filters, filter) logp.Debug("filter", "Register filter: %v", filter) } func (filters *FilterList) Get(index int) FilterRule { return filters.filters[index] } // Applies a sequence of filtering rules and returns the filtered event func (filters *FilterList) Filter(event common.MapStr) common.MapStr { // Check if filters are set, just return event if not if len(filters.filters) == 0 { return event } // clone the event at first, before starting filtering filtered := event.Clone() var err error for _, filter := range filters.filters { filtered, err = filter.Filter(filtered) if err != nil { logp.Debug("filter", "fail to apply filtering rule %s: %s", filter, err) } } return filtered } func (filters *FilterList) String() string { s := []string{} for _, filter := range filters.filters { s = append(s, filter.String()) } return strings.Join(s, ", ") } /* IncludeFields methods */ func NewIncludeFields(fields []string) *IncludeFields { /* add read only fields if they are not yet */ for _, readOnly := range MandatoryExportedFields { found := false for _, field := range fields { if readOnly == field { found = true } } if !found { fields = append(fields, readOnly) } } return &IncludeFields{Fields: fields} } func (f *IncludeFields) Filter(event common.MapStr) (common.MapStr, error) { filtered := common.MapStr{} for _, field := range f.Fields { hasKey, err := event.HasKey(field) if err != nil { return filtered, fmt.Errorf("Fail to check the key %s: %s", field, err) } if hasKey { errorOnCopy := event.CopyFieldsTo(filtered, field) if errorOnCopy != nil { return filtered, fmt.Errorf("Fail to copy key %s: %s", field, err) } } } return filtered, nil } func (f *IncludeFields) String() string { return "include_fields=" + strings.Join(f.Fields, ", ") } /* DropFields methods */ func NewDropFields(fields []string) *DropFields { /* remove read only fields */ for _, readOnly := range MandatoryExportedFields { for i, field := range fields { if readOnly == field { fields = append(fields[:i], fields[i+1:]...) } } } return &DropFields{Fields: fields} } func (f *DropFields) Filter(event common.MapStr) (common.MapStr, error) { for _, field := range f.Fields { err := event.Delete(field) if err != nil { return event, fmt.Errorf("Fail to delete key %s: %s", field, err) } } return event, nil } func (f *DropFields) String() string { return "drop_fields=" + strings.Join(f.Fields, ", ") }
ninjasftw/libertyproxybeat
vendor/github.com/elastic/beats/libbeat/filter/filter.go
GO
apache-2.0
3,640
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.osgi; import java.io.*; import java.util.*; import org.ice4j.*; import org.jitsi.impl.neomedia.*; import org.jitsi.impl.neomedia.device.*; import org.jitsi.impl.neomedia.transform.csrc.*; import org.jitsi.impl.neomedia.transform.srtp.*; import org.jitsi.impl.osgi.framework.*; import org.jitsi.service.configuration.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import org.jitsi.videobridge.transform.*; import org.osgi.framework.*; /** * Represents the entry point of the OSGi environment of the Jitsi Videobridge * application. * * @author Lyubomir Marinov * @author Pawel Domas * @author George Politis */ public class OSGi { /** * The default filename of the bundles launch sequence file. This class * expects to find that file in SC_HOME_DIR_LOCATION/SC_HOME_DIR_NAME. */ private static final String BUNDLES_FILE = "bundles.txt"; /** * The locations of the OSGi bundles (or rather of the class files of their * <tt>BundleActivator</tt> implementations) comprising Jitsi Videobridge. * An element of the <tt>BUNDLES</tt> array is an array of <tt>String</tt>s * and represents an OSGi start level. */ private static final String[][] BUNDLES = { { "org/jitsi/videobridge/eventadmin/Activator" }, { "org/jitsi/service/libjitsi/LibJitsiActivator" }, { "net/java/sip/communicator/util/UtilActivator", "net/java/sip/communicator/impl/fileaccess/FileAccessActivator" }, { "net/java/sip/communicator/impl/configuration/ConfigurationActivator" }, { "net/java/sip/communicator/impl/resources/ResourceManagementActivator" }, { "net/java/sip/communicator/impl/netaddr/NetaddrActivator" }, { "net/java/sip/communicator/impl/packetlogging/PacketLoggingActivator" }, { "net/java/sip/communicator/service/gui/internal/GuiServiceActivator" }, { "net/java/sip/communicator/service/protocol/media/ProtocolMediaActivator" }, { "org/jitsi/videobridge/influxdb/Activator" }, { "org/jitsi/videobridge/metrics/MetricLoggingActivator" }, { "org/jitsi/videobridge/VideobridgeBundleActivator" }, { "org/jitsi/videobridge/version/VersionActivator" }, { /* * The HTTP/JSON API of Videobridge is started after and in a * start level separate from Videobridge because the HTTP/JSON * API is useless if Videobridge fails to start. */ "org/jitsi/videobridge/rest/RESTBundleActivator", /* * The statistics/health reports are a non-vital, optional, * additional piece of functionality of the Videobridge. * Consequently, they do not have to be started before the * Videobridge. Besides, they employ OSGi and, hence, they * should be capable of acting as a plug-in. They do not have to * be started before the HTTP/JSON API because the HTTP/JSON API * (1) exposes the vital, non-optional, non-additional pieces of * functionality of the Videobridge and (2) it pulls, does not * push. */ "org/jitsi/videobridge/stats/StatsManagerBundleActivator" }, { /* * Started last and in its own start level because its purpose * is to let the application know that everything OSGi-related * has been started. */ "org/jitsi/videobridge/osgi/OSGiBundleActivator" } }; /** * The {@link OSGiLauncher} used to start/stop OSGi system. */ private static OSGiLauncher launcher; static { /* * Before we start OSGi and, more specifically, the very Jitsi * Videobridge application, set the default values of the System * properties which affect the (optional) behavior of the application. */ setSystemPropertyDefaults(); } /** * Sets default values on <tt>System</tt> properties which affect the * (optional) behavior of the Jitsi Videobridge application and the * libraries that it utilizes. Because <tt>ConfigurationServiceImpl</tt> * will override <tt>System</tt> property values, the set default * <tt>System</tt> property values will not prevent the user from overriding * them. */ private static void setSystemPropertyDefaults() { /* * XXX A default System property value specified bellow will eventually * be set only if the System property in question does not have a value * set yet. */ Map<String,String> defaults = new HashMap<String,String>(); String true_ = Boolean.toString(true); String false_ = Boolean.toString(false); /* * The design at the time of this writing considers the configuration * file read-only (in a read-only directory) and provides only manual * editing for it. */ defaults.put( ConfigurationService.PNAME_CONFIGURATION_FILE_IS_READ_ONLY, true_); // Jitsi Videobridge is a relay so it does not need to capture media. defaults.put( MediaServiceImpl.DISABLE_AUDIO_SUPPORT_PNAME, true_); defaults.put( MediaServiceImpl.DISABLE_VIDEO_SUPPORT_PNAME, true_); // It makes no sense for Jitsi Videobridge to pace its RTP output. defaults.put( DeviceConfiguration.PROP_VIDEO_RTP_PACING_THRESHOLD, Integer.toString(Integer.MAX_VALUE)); /* * XXX Explicitly support JitMeet by default because is is the primary * use case of Jitsi Videobridge right now. */ defaults.put( SsrcTransformEngine .DROP_MUTED_AUDIO_SOURCE_IN_REVERSE_TRANSFORM, true_); defaults.put(SRTPCryptoContext.CHECK_REPLAY_PNAME, false_); // In the majority of use-cases the clients which connect to Jitsi // Videobridge are not in the same network, so we don't need to // advertise link-local addresses. defaults.put(StackProperties.DISABLE_LINK_LOCAL_ADDRESSES, true_); // If DTMF handling is enabled, DTMF packets will be read and swallowed. // We want them forwarded as normal packets. defaults.put(AudioMediaStream.DISABLE_DTMF_HANDLING_PNAME, true_); // This will eventually be enabled by default, but keep it off until // more testing. defaults.put(RtpChannelTransformEngine.DISABLE_RETRANSMISSION_REQUESTS, true_); // This causes RTP/RTCP packets received before the DTLS agent is ready // to decrypt them to be dropped. Without it, these packets are passed // on without decryption and this leads to: // 1. Garbage being sent to the endpoints (or at least something they // cannot decrypt). // 2. Failed attempts to parse encrypted RTCP packets (in a compound // packet, the headers of all but the first packet are encrypted). // This is currently disabled, because it makes DTLS mandatory, and // thus breaks communication with jigasi and jitsi. //defaults.put("org.jitsi.impl.neomedia.transform.dtls." // + "DtlsPacketTransformer.dropUnencryptedPkts", // true_); for (Map.Entry<String,String> e : defaults.entrySet()) { String key = e.getKey(); if (System.getProperty(key) == null) System.setProperty(key, e.getValue()); } } /** * Starts the OSGi implementation and the Jitsi Videobridge bundles. * * @param bundleActivator */ public static synchronized void start(BundleActivator bundleActivator) { if (launcher == null) { launcher = new OSGiLauncher(getBundles()); } launcher.start(bundleActivator); } /** * Stops the Jitsi Videobridge bundles and the OSGi implementation. * * @param bundleActivator */ public static synchronized void stop(BundleActivator bundleActivator) { if (launcher != null) { launcher.stop(bundleActivator); } } /** * Gets the list of the OSGi bundles to launch. It either loads that list * from SC_HOME_DIR_LOCATION/SC_HOME_DIR_NAME/BUNDLES_FILE, or, if that file * doesn't exist, from the <tt>BUNDLES</tt> variable. * * @return the list of OSGi bundles to launch. */ private static String[][] getBundles() { File file = ConfigUtils .getAbsoluteFile(BUNDLES_FILE, null); if (file == null || !file.exists()) { return BUNDLES; } List<String[]> lines = new ArrayList<String[]>(); Scanner input = null; try { input = new Scanner(file); while(input.hasNextLine()) { String line = input.nextLine(); if (!StringUtils.isNullOrEmpty(line)) { lines.add(new String[] { line.trim() }); } } } catch (FileNotFoundException e) { return BUNDLES; } finally { if (input != null) { input.close(); } } String[][] bundles = lines.isEmpty() ? BUNDLES : lines.toArray(new String[lines.size()][]); return bundles; } }
ReadyTalk/jitsi-videobridge
src/main/java/org/jitsi/videobridge/osgi/OSGi.java
Java
apache-2.0
10,921
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tez.dag.app.rm; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.tez.common.ContainerSignatureMatcher; import org.apache.tez.common.TezUtils; import org.apache.tez.dag.api.NamedEntityDescriptor; import org.apache.tez.dag.api.TaskLocationHint; import org.apache.tez.dag.api.TezConfiguration; import org.apache.tez.dag.api.TezConstants; import org.apache.tez.dag.api.TezException; import org.apache.tez.dag.api.UserPayload; import org.apache.tez.dag.api.client.DAGClientServer; import org.apache.tez.dag.app.AppContext; import org.apache.tez.dag.app.ContainerContext; import org.apache.tez.dag.app.ServicePluginLifecycleAbstractService; import org.apache.tez.dag.app.dag.TaskAttempt; import org.apache.tez.dag.app.dag.impl.TaskAttemptImpl; import org.apache.tez.dag.app.dag.impl.TaskImpl; import org.apache.tez.dag.app.dag.impl.VertexImpl; import org.apache.tez.dag.app.rm.container.AMContainer; import org.apache.tez.dag.app.rm.container.AMContainerEventAssignTA; import org.apache.tez.dag.app.rm.container.AMContainerEventCompleted; import org.apache.tez.dag.app.rm.container.AMContainerEventType; import org.apache.tez.dag.app.rm.container.AMContainerMap; import org.apache.tez.dag.app.rm.container.AMContainerState; import org.apache.tez.dag.app.web.WebUIService; import org.apache.tez.dag.records.TaskAttemptTerminationCause; import org.apache.tez.dag.records.TezDAGID; import org.apache.tez.dag.records.TezTaskAttemptID; import org.apache.tez.dag.records.TezTaskID; import org.apache.tez.dag.records.TezVertexID; import org.apache.tez.runtime.api.impl.TaskSpec; import org.apache.tez.serviceplugins.api.TaskAttemptEndReason; import org.apache.tez.serviceplugins.api.TaskScheduler; import org.apache.tez.serviceplugins.api.TaskSchedulerContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.google.common.collect.Lists; @SuppressWarnings("rawtypes") public class TestTaskSchedulerManager { class TestEventHandler implements EventHandler{ List<Event> events = Lists.newLinkedList(); @Override public void handle(Event event) { events.add(event); } } class MockTaskSchedulerManager extends TaskSchedulerManager { final AtomicBoolean notify = new AtomicBoolean(false); public MockTaskSchedulerManager(AppContext appContext, DAGClientServer clientService, EventHandler eventHandler, ContainerSignatureMatcher containerSignatureMatcher, WebUIService webUI) { super(appContext, clientService, eventHandler, containerSignatureMatcher, webUI, Lists.newArrayList(new NamedEntityDescriptor("FakeDescriptor", null)), false); } @Override protected void instantiateSchedulers(String host, int port, String trackingUrl, AppContext appContext) { taskSchedulers[0] = mockTaskScheduler; taskSchedulerServiceWrappers[0] = new ServicePluginLifecycleAbstractService<>(taskSchedulers[0]); } @Override protected void notifyForTest() { synchronized (notify) { notify.set(true); notify.notifyAll(); } } } AppContext mockAppContext; DAGClientServer mockClientService; TestEventHandler mockEventHandler; ContainerSignatureMatcher mockSigMatcher; MockTaskSchedulerManager schedulerHandler; TaskScheduler mockTaskScheduler; AMContainerMap mockAMContainerMap; WebUIService mockWebUIService; @Before public void setup() { mockAppContext = mock(AppContext.class, RETURNS_DEEP_STUBS); doReturn(new Configuration(false)).when(mockAppContext).getAMConf(); mockClientService = mock(DAGClientServer.class); mockEventHandler = new TestEventHandler(); mockSigMatcher = mock(ContainerSignatureMatcher.class); mockTaskScheduler = mock(TaskScheduler.class); mockAMContainerMap = mock(AMContainerMap.class); mockWebUIService = mock(WebUIService.class); when(mockAppContext.getAllContainers()).thenReturn(mockAMContainerMap); when(mockClientService.getBindAddress()).thenReturn(new InetSocketAddress(10000)); schedulerHandler = new MockTaskSchedulerManager( mockAppContext, mockClientService, mockEventHandler, mockSigMatcher, mockWebUIService); } @Test(timeout = 5000) public void testSimpleAllocate() throws Exception { Configuration conf = new Configuration(false); schedulerHandler.init(conf); schedulerHandler.start(); TaskAttemptImpl mockTaskAttempt = mock(TaskAttemptImpl.class); TezTaskAttemptID mockAttemptId = mock(TezTaskAttemptID.class); when(mockAttemptId.getId()).thenReturn(0); when(mockTaskAttempt.getID()).thenReturn(mockAttemptId); Resource resource = Resource.newInstance(1024, 1); ContainerContext containerContext = new ContainerContext(new HashMap<String, LocalResource>(), new Credentials(), new HashMap<String, String>(), ""); int priority = 10; TaskLocationHint locHint = TaskLocationHint.createTaskLocationHint(new HashSet<String>(), null); ContainerId mockCId = mock(ContainerId.class); Container container = mock(Container.class); when(container.getId()).thenReturn(mockCId); AMContainer mockAMContainer = mock(AMContainer.class); when(mockAMContainer.getContainerId()).thenReturn(mockCId); when(mockAMContainer.getState()).thenReturn(AMContainerState.IDLE); when(mockAMContainerMap.get(mockCId)).thenReturn(mockAMContainer); AMSchedulerEventTALaunchRequest lr = new AMSchedulerEventTALaunchRequest(mockAttemptId, resource, null, mockTaskAttempt, locHint, priority, containerContext, 0, 0, 0); schedulerHandler.taskAllocated(0, mockTaskAttempt, lr, container); assertEquals(2, mockEventHandler.events.size()); assertTrue(mockEventHandler.events.get(1) instanceof AMContainerEventAssignTA); AMContainerEventAssignTA assignEvent = (AMContainerEventAssignTA) mockEventHandler.events.get(1); assertEquals(priority, assignEvent.getPriority()); assertEquals(mockAttemptId, assignEvent.getTaskAttemptId()); } @Test (timeout = 5000) public void testTaskBasedAffinity() throws Exception { Configuration conf = new Configuration(false); schedulerHandler.init(conf); schedulerHandler.start(); TaskAttemptImpl mockTaskAttempt = mock(TaskAttemptImpl.class); TezTaskAttemptID taId = mock(TezTaskAttemptID.class); String affVertexName = "srcVertex"; int affTaskIndex = 1; TaskLocationHint locHint = TaskLocationHint.createTaskLocationHint(affVertexName, affTaskIndex); VertexImpl affVertex = mock(VertexImpl.class); TaskImpl affTask = mock(TaskImpl.class); TaskAttemptImpl affAttempt = mock(TaskAttemptImpl.class); ContainerId affCId = mock(ContainerId.class); when(affVertex.getTotalTasks()).thenReturn(2); when(affVertex.getTask(affTaskIndex)).thenReturn(affTask); when(affTask.getSuccessfulAttempt()).thenReturn(affAttempt); when(affAttempt.getAssignedContainerID()).thenReturn(affCId); when(mockAppContext.getCurrentDAG().getVertex(affVertexName)).thenReturn(affVertex); Resource resource = Resource.newInstance(100, 1); AMSchedulerEventTALaunchRequest event = new AMSchedulerEventTALaunchRequest (taId, resource, null, mockTaskAttempt, locHint, 3, null, 0, 0, 0); schedulerHandler.notify.set(false); schedulerHandler.handle(event); synchronized (schedulerHandler.notify) { while (!schedulerHandler.notify.get()) { schedulerHandler.notify.wait(); } } // verify mockTaskAttempt affinitized to expected affCId verify(mockTaskScheduler, times(1)).allocateTask(mockTaskAttempt, resource, affCId, Priority.newInstance(3), null, event); schedulerHandler.stop(); schedulerHandler.close(); } @Test (timeout = 5000) public void testContainerPreempted() throws IOException { Configuration conf = new Configuration(false); schedulerHandler.init(conf); schedulerHandler.start(); String diagnostics = "Container preempted by RM."; TaskAttemptImpl mockTask = mock(TaskAttemptImpl.class); ContainerStatus mockStatus = mock(ContainerStatus.class); ContainerId mockCId = mock(ContainerId.class); AMContainer mockAMContainer = mock(AMContainer.class); when(mockAMContainerMap.get(mockCId)).thenReturn(mockAMContainer); when(mockAMContainer.getContainerId()).thenReturn(mockCId); when(mockStatus.getContainerId()).thenReturn(mockCId); when(mockStatus.getDiagnostics()).thenReturn(diagnostics); when(mockStatus.getExitStatus()).thenReturn(ContainerExitStatus.PREEMPTED); schedulerHandler.containerCompleted(0, mockTask, mockStatus); assertEquals(1, mockEventHandler.events.size()); Event event = mockEventHandler.events.get(0); assertEquals(AMContainerEventType.C_COMPLETED, event.getType()); AMContainerEventCompleted completedEvent = (AMContainerEventCompleted) event; assertEquals(mockCId, completedEvent.getContainerId()); assertEquals("Container preempted externally. Container preempted by RM.", completedEvent.getDiagnostics()); assertTrue(completedEvent.isPreempted()); assertEquals(TaskAttemptTerminationCause.EXTERNAL_PREEMPTION, completedEvent.getTerminationCause()); Assert.assertFalse(completedEvent.isDiskFailed()); schedulerHandler.stop(); schedulerHandler.close(); } @Test (timeout = 5000) public void testContainerInternalPreempted() throws IOException { Configuration conf = new Configuration(false); schedulerHandler.init(conf); schedulerHandler.start(); AMContainer mockAmContainer = mock(AMContainer.class); when(mockAmContainer.getTaskSchedulerIdentifier()).thenReturn(0); when(mockAmContainer.getContainerLauncherIdentifier()).thenReturn(0); when(mockAmContainer.getTaskCommunicatorIdentifier()).thenReturn(0); ContainerId mockCId = mock(ContainerId.class); verify(mockTaskScheduler, times(0)).deallocateContainer((ContainerId) any()); when(mockAMContainerMap.get(mockCId)).thenReturn(mockAmContainer); schedulerHandler.preemptContainer(0, mockCId); verify(mockTaskScheduler, times(1)).deallocateContainer(mockCId); assertEquals(1, mockEventHandler.events.size()); Event event = mockEventHandler.events.get(0); assertEquals(AMContainerEventType.C_COMPLETED, event.getType()); AMContainerEventCompleted completedEvent = (AMContainerEventCompleted) event; assertEquals(mockCId, completedEvent.getContainerId()); assertEquals("Container preempted internally", completedEvent.getDiagnostics()); assertTrue(completedEvent.isPreempted()); Assert.assertFalse(completedEvent.isDiskFailed()); assertEquals(TaskAttemptTerminationCause.INTERNAL_PREEMPTION, completedEvent.getTerminationCause()); schedulerHandler.stop(); schedulerHandler.close(); } @Test (timeout = 5000) public void testContainerDiskFailed() throws IOException { Configuration conf = new Configuration(false); schedulerHandler.init(conf); schedulerHandler.start(); String diagnostics = "NM disk failed."; TaskAttemptImpl mockTask = mock(TaskAttemptImpl.class); ContainerStatus mockStatus = mock(ContainerStatus.class); ContainerId mockCId = mock(ContainerId.class); AMContainer mockAMContainer = mock(AMContainer.class); when(mockAMContainerMap.get(mockCId)).thenReturn(mockAMContainer); when(mockAMContainer.getContainerId()).thenReturn(mockCId); when(mockStatus.getContainerId()).thenReturn(mockCId); when(mockStatus.getDiagnostics()).thenReturn(diagnostics); when(mockStatus.getExitStatus()).thenReturn(ContainerExitStatus.DISKS_FAILED); schedulerHandler.containerCompleted(0, mockTask, mockStatus); assertEquals(1, mockEventHandler.events.size()); Event event = mockEventHandler.events.get(0); assertEquals(AMContainerEventType.C_COMPLETED, event.getType()); AMContainerEventCompleted completedEvent = (AMContainerEventCompleted) event; assertEquals(mockCId, completedEvent.getContainerId()); assertEquals("Container disk failed. NM disk failed.", completedEvent.getDiagnostics()); Assert.assertFalse(completedEvent.isPreempted()); assertTrue(completedEvent.isDiskFailed()); assertEquals(TaskAttemptTerminationCause.NODE_DISK_ERROR, completedEvent.getTerminationCause()); schedulerHandler.stop(); schedulerHandler.close(); } @Test (timeout = 5000) public void testContainerExceededPMem() throws IOException { Configuration conf = new Configuration(false); schedulerHandler.init(conf); schedulerHandler.start(); String diagnostics = "Exceeded Physical Memory"; TaskAttemptImpl mockTask = mock(TaskAttemptImpl.class); ContainerStatus mockStatus = mock(ContainerStatus.class); ContainerId mockCId = mock(ContainerId.class); AMContainer mockAMContainer = mock(AMContainer.class); when(mockAMContainerMap.get(mockCId)).thenReturn(mockAMContainer); when(mockAMContainer.getContainerId()).thenReturn(mockCId); when(mockStatus.getContainerId()).thenReturn(mockCId); when(mockStatus.getDiagnostics()).thenReturn(diagnostics); // use -104 rather than ContainerExitStatus.KILLED_EXCEEDED_PMEM because // ContainerExitStatus.KILLED_EXCEEDED_PMEM is only available after hadoop-2.5 when(mockStatus.getExitStatus()).thenReturn(-104); schedulerHandler.containerCompleted(0, mockTask, mockStatus); assertEquals(1, mockEventHandler.events.size()); Event event = mockEventHandler.events.get(0); assertEquals(AMContainerEventType.C_COMPLETED, event.getType()); AMContainerEventCompleted completedEvent = (AMContainerEventCompleted) event; assertEquals(mockCId, completedEvent.getContainerId()); assertEquals("Container failed, exitCode=-104. Exceeded Physical Memory", completedEvent.getDiagnostics()); Assert.assertFalse(completedEvent.isPreempted()); Assert.assertFalse(completedEvent.isDiskFailed()); assertEquals(TaskAttemptTerminationCause.CONTAINER_EXITED, completedEvent.getTerminationCause()); schedulerHandler.stop(); schedulerHandler.close(); } @Test (timeout = 5000) public void testHistoryUrlConf() throws Exception { Configuration conf = schedulerHandler.appContext.getAMConf(); // ensure history url is empty when timeline server is not the logging class conf.set(TezConfiguration.TEZ_HISTORY_URL_BASE, "http://ui-host:9999"); assertTrue("".equals(schedulerHandler.getHistoryUrl())); // ensure expansion of url happens conf.set(TezConfiguration.TEZ_HISTORY_LOGGING_SERVICE_CLASS, "org.apache.tez.dag.history.logging.ats.ATSHistoryLoggingService"); final ApplicationId mockApplicationId = mock(ApplicationId.class); doReturn("TEST_APP_ID").when(mockApplicationId).toString(); doReturn(mockApplicationId).when(mockAppContext).getApplicationID(); assertTrue("http://ui-host:9999/#/tez-app/TEST_APP_ID" .equals(schedulerHandler.getHistoryUrl())); // ensure the trailing / in history url is handled conf.set(TezConfiguration.TEZ_HISTORY_URL_BASE, "http://ui-host:9998/"); assertTrue("http://ui-host:9998/#/tez-app/TEST_APP_ID" .equals(schedulerHandler.getHistoryUrl())); // ensure missing scheme in history url is handled conf.set(TezConfiguration.TEZ_HISTORY_URL_BASE, "ui-host:9998/"); Assert.assertTrue("http://ui-host:9998/#/tez-app/TEST_APP_ID" .equals(schedulerHandler.getHistoryUrl())); // handle bad template ex without begining / conf.set(TezConfiguration.TEZ_AM_TEZ_UI_HISTORY_URL_TEMPLATE, "__HISTORY_URL_BASE__#/somepath"); assertTrue("http://ui-host:9998/#/somepath" .equals(schedulerHandler.getHistoryUrl())); conf.set(TezConfiguration.TEZ_AM_TEZ_UI_HISTORY_URL_TEMPLATE, "__HISTORY_URL_BASE__?viewPath=tez-app/__APPLICATION_ID__"); conf.set(TezConfiguration.TEZ_HISTORY_URL_BASE, "http://localhost/ui/tez"); assertTrue("http://localhost/ui/tez?viewPath=tez-app/TEST_APP_ID" .equals(schedulerHandler.getHistoryUrl())); } @Test(timeout = 5000) public void testNoSchedulerSpecified() throws IOException { try { new TSEHForMultipleSchedulersTest(mockAppContext, mockClientService, mockEventHandler, mockSigMatcher, mockWebUIService, null, false); fail("Expecting an IllegalStateException with no schedulers specified"); } catch (IllegalArgumentException e) { } } // Verified via statics @Test(timeout = 5000) public void testCustomTaskSchedulerSetup() throws IOException { Configuration conf = new Configuration(false); conf.set("testkey", "testval"); UserPayload defaultPayload = TezUtils.createUserPayloadFromConf(conf); String customSchedulerName = "fakeScheduler"; List<NamedEntityDescriptor> taskSchedulers = new LinkedList<>(); ByteBuffer bb = ByteBuffer.allocate(4); bb.putInt(0, 3); UserPayload userPayload = UserPayload.create(bb); taskSchedulers.add( new NamedEntityDescriptor(customSchedulerName, FakeTaskScheduler.class.getName()) .setUserPayload(userPayload)); taskSchedulers.add(new NamedEntityDescriptor(TezConstants.getTezYarnServicePluginName(), null) .setUserPayload(defaultPayload)); TSEHForMultipleSchedulersTest tseh = new TSEHForMultipleSchedulersTest(mockAppContext, mockClientService, mockEventHandler, mockSigMatcher, mockWebUIService, taskSchedulers, false); tseh.init(conf); tseh.start(); // Verify that the YARN task scheduler is installed by default assertTrue(tseh.getYarnSchedulerCreated()); assertFalse(tseh.getUberSchedulerCreated()); assertEquals(2, tseh.getNumCreateInvocations()); // Verify the order of the schedulers assertEquals(customSchedulerName, tseh.getTaskSchedulerName(0)); assertEquals(TezConstants.getTezYarnServicePluginName(), tseh.getTaskSchedulerName(1)); // Verify the payload setup for the custom task scheduler assertNotNull(tseh.getTaskSchedulerContext(0)); assertEquals(bb, tseh.getTaskSchedulerContext(0).getInitialUserPayload().getPayload()); // Verify the payload on the yarn scheduler assertNotNull(tseh.getTaskSchedulerContext(1)); Configuration parsed = TezUtils.createConfFromUserPayload(tseh.getTaskSchedulerContext(1).getInitialUserPayload()); assertEquals("testval", parsed.get("testkey")); } @Test(timeout = 5000) public void testTaskSchedulerRouting() throws Exception { Configuration conf = new Configuration(false); UserPayload defaultPayload = TezUtils.createUserPayloadFromConf(conf); String customSchedulerName = "fakeScheduler"; List<NamedEntityDescriptor> taskSchedulers = new LinkedList<>(); ByteBuffer bb = ByteBuffer.allocate(4); bb.putInt(0, 3); UserPayload userPayload = UserPayload.create(bb); taskSchedulers.add( new NamedEntityDescriptor(customSchedulerName, FakeTaskScheduler.class.getName()) .setUserPayload(userPayload)); taskSchedulers.add(new NamedEntityDescriptor(TezConstants.getTezYarnServicePluginName(), null) .setUserPayload(defaultPayload)); TSEHForMultipleSchedulersTest tseh = new TSEHForMultipleSchedulersTest(mockAppContext, mockClientService, mockEventHandler, mockSigMatcher, mockWebUIService, taskSchedulers, false); tseh.init(conf); tseh.start(); // Verify that the YARN task scheduler is installed by default assertTrue(tseh.getYarnSchedulerCreated()); assertFalse(tseh.getUberSchedulerCreated()); assertEquals(2, tseh.getNumCreateInvocations()); // Verify the order of the schedulers assertEquals(customSchedulerName, tseh.getTaskSchedulerName(0)); assertEquals(TezConstants.getTezYarnServicePluginName(), tseh.getTaskSchedulerName(1)); verify(tseh.getTestTaskScheduler(0)).initialize(); verify(tseh.getTestTaskScheduler(0)).start(); ApplicationId appId = ApplicationId.newInstance(1000, 1); TezDAGID dagId = TezDAGID.getInstance(appId, 1); TezVertexID vertexID = TezVertexID.getInstance(dagId, 1); TezTaskID taskId1 = TezTaskID.getInstance(vertexID, 1); TezTaskAttemptID attemptId11 = TezTaskAttemptID.getInstance(taskId1, 1); TezTaskID taskId2 = TezTaskID.getInstance(vertexID, 2); TezTaskAttemptID attemptId21 = TezTaskAttemptID.getInstance(taskId2, 1); Resource resource = Resource.newInstance(1024, 1); TaskAttempt mockTaskAttempt1 = mock(TaskAttempt.class); TaskAttempt mockTaskAttempt2 = mock(TaskAttempt.class); AMSchedulerEventTALaunchRequest launchRequest1 = new AMSchedulerEventTALaunchRequest(attemptId11, resource, mock(TaskSpec.class), mockTaskAttempt1, mock(TaskLocationHint.class), 1, mock(ContainerContext.class), 0, 0, 0); tseh.handle(launchRequest1); verify(tseh.getTestTaskScheduler(0)).allocateTask(eq(mockTaskAttempt1), eq(resource), any(String[].class), any(String[].class), any(Priority.class), any(Object.class), eq(launchRequest1)); AMSchedulerEventTALaunchRequest launchRequest2 = new AMSchedulerEventTALaunchRequest(attemptId21, resource, mock(TaskSpec.class), mockTaskAttempt2, mock(TaskLocationHint.class), 1, mock(ContainerContext.class), 1, 0, 0); tseh.handle(launchRequest2); verify(tseh.getTestTaskScheduler(1)).allocateTask(eq(mockTaskAttempt2), eq(resource), any(String[].class), any(String[].class), any(Priority.class), any(Object.class), eq(launchRequest2)); } public static class TSEHForMultipleSchedulersTest extends TaskSchedulerManager { private final TaskScheduler yarnTaskScheduler; private final TaskScheduler uberTaskScheduler; private final AtomicBoolean uberSchedulerCreated = new AtomicBoolean(false); private final AtomicBoolean yarnSchedulerCreated = new AtomicBoolean(false); private final AtomicInteger numCreateInvocations = new AtomicInteger(0); private final Set<Integer> seenSchedulers = new HashSet<>(); private final List<TaskSchedulerContext> taskSchedulerContexts = new LinkedList<>(); private final List<String> taskSchedulerNames = new LinkedList<>(); private final List<TaskScheduler> testTaskSchedulers = new LinkedList<>(); public TSEHForMultipleSchedulersTest(AppContext appContext, DAGClientServer clientService, EventHandler eventHandler, ContainerSignatureMatcher containerSignatureMatcher, WebUIService webUI, List<NamedEntityDescriptor> schedulerDescriptors, boolean isPureLocalMode) { super(appContext, clientService, eventHandler, containerSignatureMatcher, webUI, schedulerDescriptors, isPureLocalMode); yarnTaskScheduler = mock(TaskScheduler.class); uberTaskScheduler = mock(TaskScheduler.class); } @Override TaskScheduler createTaskScheduler(String host, int port, String trackingUrl, AppContext appContext, NamedEntityDescriptor taskSchedulerDescriptor, long customAppIdIdentifier, int schedulerId) throws TezException { numCreateInvocations.incrementAndGet(); boolean added = seenSchedulers.add(schedulerId); assertTrue("Cannot add multiple schedulers with the same schedulerId", added); taskSchedulerNames.add(taskSchedulerDescriptor.getEntityName()); return super.createTaskScheduler(host, port, trackingUrl, appContext, taskSchedulerDescriptor, customAppIdIdentifier, schedulerId); } @Override TaskSchedulerContext wrapTaskSchedulerContext(TaskSchedulerContext rawContext) { // Avoid wrapping in threads return rawContext; } @Override TaskScheduler createYarnTaskScheduler(TaskSchedulerContext taskSchedulerContext, int schedulerId) { taskSchedulerContexts.add(taskSchedulerContext); testTaskSchedulers.add(yarnTaskScheduler); yarnSchedulerCreated.set(true); return yarnTaskScheduler; } @Override TaskScheduler createUberTaskScheduler(TaskSchedulerContext taskSchedulerContext, int schedulerId) { taskSchedulerContexts.add(taskSchedulerContext); uberSchedulerCreated.set(true); testTaskSchedulers.add(yarnTaskScheduler); return uberTaskScheduler; } @Override TaskScheduler createCustomTaskScheduler(TaskSchedulerContext taskSchedulerContext, NamedEntityDescriptor taskSchedulerDescriptor, int schedulerId) throws TezException { taskSchedulerContexts.add(taskSchedulerContext); TaskScheduler taskScheduler = spy(super.createCustomTaskScheduler(taskSchedulerContext, taskSchedulerDescriptor, schedulerId)); testTaskSchedulers.add(taskScheduler); return taskScheduler; } @Override // Inline handling of events. public void handle(AMSchedulerEvent event) { handleEvent(event); } public boolean getUberSchedulerCreated() { return uberSchedulerCreated.get(); } public boolean getYarnSchedulerCreated() { return yarnSchedulerCreated.get(); } public int getNumCreateInvocations() { return numCreateInvocations.get(); } public TaskSchedulerContext getTaskSchedulerContext(int schedulerId) { return taskSchedulerContexts.get(schedulerId); } public String getTaskSchedulerName(int schedulerId) { return taskSchedulerNames.get(schedulerId); } public TaskScheduler getTestTaskScheduler(int schedulerId) { return testTaskSchedulers.get(schedulerId); } } public static class FakeTaskScheduler extends TaskScheduler { public FakeTaskScheduler( TaskSchedulerContext taskSchedulerContext) { super(taskSchedulerContext); } @Override public Resource getAvailableResources() { return null; } @Override public int getClusterNodeCount() { return 0; } @Override public void dagComplete() { } @Override public Resource getTotalResources() { return null; } @Override public void blacklistNode(NodeId nodeId) { } @Override public void unblacklistNode(NodeId nodeId) { } @Override public void allocateTask(Object task, Resource capability, String[] hosts, String[] racks, Priority priority, Object containerSignature, Object clientCookie) { } @Override public void allocateTask(Object task, Resource capability, ContainerId containerId, Priority priority, Object containerSignature, Object clientCookie) { } @Override public boolean deallocateTask(Object task, boolean taskSucceeded, TaskAttemptEndReason endReason, String diagnostics) { return false; } @Override public Object deallocateContainer(ContainerId containerId) { return null; } @Override public void setShouldUnregister() { } @Override public boolean hasUnregistered() { return false; } } }
guiling/tez
tez-dag/src/test/java/org/apache/tez/dag/app/rm/TestTaskSchedulerManager.java
Java
apache-2.0
30,102
// // Created by Bruno Wernimont on 2012 // Copyright 2012 BaseKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> @interface UIBarButtonItem (BaseKit) + (UIBarButtonItem *)flexibleSpace; + (UIBarButtonItem *)barButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action; @end
ListFranz/NoteItIOS
Vendor/View/UIBarButtonItem+BaseKit.h
C
apache-2.0
915
#!/bin/sh set -e ./gradlew clean build git checkout gh-pages git pull --rebase git rm -r jgiven-report/* mkdir -p jgiven-report/html5 cp -r jgiven-tests/build/reports/jgiven/html5/ jgiven-report/ git add jgiven-report/ git commit -m 'added generated jgiven report to gh-pages' git push git checkout -f master
ahus1/JGiven
scripts/publishJGivenReports.sh
Shell
apache-2.0
309
using System; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// The <see cref="Scorer"/> for <see cref="DisjunctionMaxQuery"/>. The union of all documents generated by the the subquery scorers /// is generated in document number order. The score for each document is the maximum of the scores computed /// by the subquery scorers that generate that document, plus <see cref="tieBreakerMultiplier"/> times the sum of the scores /// for the other subqueries that generate the document. /// </summary> internal class DisjunctionMaxScorer : DisjunctionScorer { /// <summary>Multiplier applied to non-maximum-scoring subqueries for a document as they are summed into the result.</summary> private readonly float tieBreakerMultiplier; private int freq = -1; /// <summary>Used when scoring currently matching doc.</summary> private float scoreSum; private float scoreMax; /// <summary> /// Creates a new instance of <see cref="DisjunctionMaxScorer"/> /// </summary> /// <param name="weight"> /// The <see cref="Weight"/> to be used. </param> /// <param name="tieBreakerMultiplier"> /// Multiplier applied to non-maximum-scoring subqueries for a /// document as they are summed into the result. </param> /// <param name="subScorers"> /// The sub scorers this <see cref="Scorer"/> should iterate on </param> public DisjunctionMaxScorer(Weight weight, float tieBreakerMultiplier, Scorer[] subScorers) : base(weight, subScorers) { this.tieBreakerMultiplier = tieBreakerMultiplier; } /// <summary> /// Determine the current document score. Initially invalid, until <see cref="DocIdSetIterator.NextDoc()"/> is called the first time. </summary> /// <returns> The score of the current generated document </returns> public override float GetScore() { return scoreMax + (scoreSum - scoreMax) * tieBreakerMultiplier; } protected override void AfterNext() { m_doc = m_subScorers[0].DocID; if (m_doc != NO_MORE_DOCS) { scoreSum = scoreMax = m_subScorers[0].GetScore(); freq = 1; ScoreAll(1); ScoreAll(2); } } /// <summary> /// Recursively iterate all subScorers that generated last doc computing sum and max /// </summary> private void ScoreAll(int root) { if (root < m_numScorers && m_subScorers[root].DocID == m_doc) { float sub = m_subScorers[root].GetScore(); freq++; scoreSum += sub; scoreMax = Math.Max(scoreMax, sub); ScoreAll((root << 1) + 1); ScoreAll((root << 1) + 2); } } public override int Freq => freq; } }
jeme/lucenenet
src/Lucene.Net/Search/DisjunctionMaxScorer.cs
C#
apache-2.0
3,907
<?php /* * services_ntpd_pps.php * * part of pfSense (https://www.pfsense.org) * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate) * Copyright (c) 2013 Dagorlad * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ##|+PRIV ##|*IDENT=page-services-ntpd-pps ##|*NAME=Services: NTP PPS ##|*DESCR=Allow access to the 'Services: NTP PPS' page. ##|*MATCH=services_ntpd_pps.php* ##|-PRIV require_once("guiconfig.inc"); if (!is_array($config['ntpd'])) { $config['ntpd'] = array(); } if (!is_array($config['ntpd']['pps'])) { $config['ntpd']['pps'] = array(); } if ($_POST) { unset($input_errors); if (!$input_errors) { if (!empty($_POST['ppsport']) && file_exists('/dev/'.$_POST['ppsport'])) { $config['ntpd']['pps']['port'] = $_POST['ppsport']; } else { /* if port is not set, remove all the pps config */ unset($config['ntpd']['pps']); } if (!empty($_POST['ppsfudge1'])) { $config['ntpd']['pps']['fudge1'] = $_POST['ppsfudge1']; } elseif (isset($config['ntpd']['pps']['fudge1'])) { unset($config['ntpd']['pps']['fudge1']); } if (!empty($_POST['ppsstratum']) && ($_POST['ppsstratum']) < 17) { $config['ntpd']['pps']['stratum'] = $_POST['ppsstratum']; } elseif (isset($config['ntpd']['pps']['stratum'])) { unset($config['ntpd']['pps']['stratum']); } if (!empty($_POST['ppsselect'])) { $config['ntpd']['pps']['noselect'] = $_POST['ppsselect']; } elseif (isset($config['ntpd']['pps']['noselect'])) { unset($config['ntpd']['pps']['noselect']); } if (!empty($_POST['ppsflag2'])) { $config['ntpd']['pps']['flag2'] = $_POST['ppsflag2']; } elseif (isset($config['ntpd']['pps']['flag2'])) { unset($config['ntpd']['pps']['flag2']); } if (!empty($_POST['ppsflag3'])) { $config['ntpd']['pps']['flag3'] = $_POST['ppsflag3']; } elseif (isset($config['ntpd']['pps']['flag3'])) { unset($config['ntpd']['pps']['flag3']); } if (!empty($_POST['ppsflag4'])) { $config['ntpd']['pps']['flag4'] = $_POST['ppsflag4']; } elseif (isset($config['ntpd']['pps']['flag4'])) { unset($config['ntpd']['pps']['flag4']); } if (!empty($_POST['ppsrefid'])) { $config['ntpd']['pps']['refid'] = $_POST['ppsrefid']; } elseif (isset($config['ntpd']['pps']['refid'])) { unset($config['ntpd']['pps']['refid']); } write_config("Updated NTP PPS Settings"); $changes_applied = true; $retval = 0; $retval |= system_ntp_configure(); } } $pconfig = &$config['ntpd']['pps']; $pgtitle = array(gettext("Services"), gettext("NTP"), gettext("PPS")); $pglinks = array("", "services_ntpd.php", "@self"); $shortcut_section = "ntp"; include("head.inc"); if ($input_errors) { print_input_errors($input_errors); } if ($changes_applied) { print_apply_result_box($retval); } $tab_array = array(); $tab_array[] = array(gettext("Settings"), false, "services_ntpd.php"); $tab_array[] = array(gettext("ACLs"), false, "services_ntpd_acls.php"); $tab_array[] = array(gettext("Serial GPS"), false, "services_ntpd_gps.php"); $tab_array[] = array(gettext("PPS"), true, "services_ntpd_pps.php"); display_top_tabs($tab_array); $form = new Form; $section = new Form_Section('NTP Serial PPS Configuration'); $section->addInput(new Form_StaticText( 'Notes', 'Devices with a Pulse Per Second output such as radios that receive a time signal from DCF77 (DE), JJY (JP), MSF (GB) or WWVB (US) may be used as a PPS reference for NTP. ' . 'A serial GPS may also be used, but the serial GPS driver would usually be the better option. ' . 'A PPS signal only provides a reference to the change of a second, so at least one other source to number the seconds is required.' . '<br /><br />' . 'At least 3 additional time sources should be configured under ' . '<a href="services_ntpd.php">' . 'Services > NTP > Settings' . '</a>' . ' to reliably supply the time of each PPS pulse.' )); $serialports = glob("/dev/cua?[0-9]{,.[0-9]}", GLOB_BRACE); if (!empty($serialports)) { $splist = array(); foreach ($serialports as $port) { $shortport = substr($port, 5); $splist[$shortport] = $shortport; } $section->addInput(new Form_Select( 'ppsport', 'Serial Port', $pconfig['port'], ['' => gettext('None')] + $splist ))->setHelp('All serial ports are listed, be sure to pick the port with the PPS source attached. '); } $section->addInput(new Form_Input( 'ppsfudge1', 'Fudge Time', 'text', $pconfig['fudge1'] ))->setHelp('Fudge time is used to specify the PPS signal offset from the actual second such as the transmission delay between the transmitter and the receiver (default: 0.0).'); $section->addInput(new Form_Input( 'ppsstratum', 'Stratum', 'text', $pconfig['stratum'] ))->setHelp('This may be used to change the PPS Clock stratum (default: 0). This may be useful to, for some reason, have ntpd prefer a different clock and just monitor this source.'); $section->addInput(new Form_Checkbox( 'ppsflag2', 'Flags', 'Enable falling edge PPS signal processing (default: unchecked, rising edge).', $pconfig['flag2'] )); $section->addInput(new Form_Checkbox( 'ppsflag3', null, 'Enable kernel PPS clock discipline (default: unchecked).', $pconfig['flag3'] )); $section->addInput(new Form_Checkbox( 'ppsflag4', null, 'Record a timestamp once for each second, useful for constructing Allan deviation plots (default: unchecked).', $pconfig['flag4'] )); $section->addInput(new Form_Input( 'ppsrefid', 'Clock ID', 'text', $pconfig['refid'], ['placeholder' => '1 to 4 characters'] ))->setHelp('This may be used to change the PPS Clock ID (default: PPS).'); $form->add($section); print($form); include("foot.inc");
NOYB/pfsense
src/usr/local/www/services_ntpd_pps.php
PHP
apache-2.0
6,148
// Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "deps_log.h" #include "graph.h" #include "missing_deps.h" #include "state.h" #include "test.h" const char kTestDepsLogFilename[] = "MissingDepTest-tempdepslog"; class MissingDependencyTestDelegate : public MissingDependencyScannerDelegate { void OnMissingDep(Node* node, const std::string& path, const Rule& generator) {} }; struct MissingDependencyScannerTest : public testing::Test { MissingDependencyScannerTest() : generator_rule_("generator_rule"), compile_rule_("compile_rule"), scanner_(&delegate_, &deps_log_, &state_, &filesystem_) { std::string err; deps_log_.OpenForWrite(kTestDepsLogFilename, &err); ASSERT_EQ("", err); } MissingDependencyScanner& scanner() { return scanner_; } void RecordDepsLogDep(const std::string& from, const std::string& to) { Node* node_deps[] = { state_.LookupNode(to) }; deps_log_.RecordDeps(state_.LookupNode(from), 0, 1, node_deps); } void ProcessAllNodes() { std::string err; std::vector<Node*> nodes = state_.RootNodes(&err); EXPECT_EQ("", err); for (std::vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); ++it) { scanner().ProcessNode(*it); } } void CreateInitialState() { EvalString deps_type; deps_type.AddText("gcc"); compile_rule_.AddBinding("deps", deps_type); generator_rule_.AddBinding("deps", deps_type); Edge* header_edge = state_.AddEdge(&generator_rule_); state_.AddOut(header_edge, "generated_header", 0); Edge* compile_edge = state_.AddEdge(&compile_rule_); state_.AddOut(compile_edge, "compiled_object", 0); } void CreateGraphDependencyBetween(const char* from, const char* to) { Node* from_node = state_.LookupNode(from); Edge* from_edge = from_node->in_edge(); state_.AddIn(from_edge, to, 0); } void AssertMissingDependencyBetween(const char* flaky, const char* generated, Rule* rule) { Node* flaky_node = state_.LookupNode(flaky); ASSERT_EQ(1u, scanner().nodes_missing_deps_.count(flaky_node)); Node* generated_node = state_.LookupNode(generated); ASSERT_EQ(1u, scanner().generated_nodes_.count(generated_node)); ASSERT_EQ(1u, scanner().generator_rules_.count(rule)); } MissingDependencyTestDelegate delegate_; Rule generator_rule_; Rule compile_rule_; DepsLog deps_log_; State state_; VirtualFileSystem filesystem_; MissingDependencyScanner scanner_; }; TEST_F(MissingDependencyScannerTest, EmptyGraph) { ProcessAllNodes(); ASSERT_FALSE(scanner().HadMissingDeps()); } TEST_F(MissingDependencyScannerTest, NoMissingDep) { CreateInitialState(); ProcessAllNodes(); ASSERT_FALSE(scanner().HadMissingDeps()); } TEST_F(MissingDependencyScannerTest, MissingDepPresent) { CreateInitialState(); // compiled_object uses generated_header, without a proper dependency RecordDepsLogDep("compiled_object", "generated_header"); ProcessAllNodes(); ASSERT_TRUE(scanner().HadMissingDeps()); ASSERT_EQ(1u, scanner().nodes_missing_deps_.size()); ASSERT_EQ(1u, scanner().missing_dep_path_count_); AssertMissingDependencyBetween("compiled_object", "generated_header", &generator_rule_); } TEST_F(MissingDependencyScannerTest, MissingDepFixedDirect) { CreateInitialState(); // Adding the direct dependency fixes the missing dep CreateGraphDependencyBetween("compiled_object", "generated_header"); RecordDepsLogDep("compiled_object", "generated_header"); ProcessAllNodes(); ASSERT_FALSE(scanner().HadMissingDeps()); } TEST_F(MissingDependencyScannerTest, MissingDepFixedIndirect) { CreateInitialState(); // Adding an indirect dependency also fixes the issue Edge* intermediate_edge = state_.AddEdge(&generator_rule_); state_.AddOut(intermediate_edge, "intermediate", 0); CreateGraphDependencyBetween("compiled_object", "intermediate"); CreateGraphDependencyBetween("intermediate", "generated_header"); RecordDepsLogDep("compiled_object", "generated_header"); ProcessAllNodes(); ASSERT_FALSE(scanner().HadMissingDeps()); } TEST_F(MissingDependencyScannerTest, CyclicMissingDep) { CreateInitialState(); RecordDepsLogDep("generated_header", "compiled_object"); RecordDepsLogDep("compiled_object", "generated_header"); // In case of a cycle, both paths are reported (and there is // no way to fix the issue by adding deps). ProcessAllNodes(); ASSERT_TRUE(scanner().HadMissingDeps()); ASSERT_EQ(2u, scanner().nodes_missing_deps_.size()); ASSERT_EQ(2u, scanner().missing_dep_path_count_); AssertMissingDependencyBetween("compiled_object", "generated_header", &generator_rule_); AssertMissingDependencyBetween("generated_header", "compiled_object", &compile_rule_); } TEST_F(MissingDependencyScannerTest, CycleInGraph) { CreateInitialState(); CreateGraphDependencyBetween("compiled_object", "generated_header"); CreateGraphDependencyBetween("generated_header", "compiled_object"); // The missing-deps tool doesn't deal with cycles in the graph, because // there will be an error loading the graph before we get to the tool. // This test is to illustrate that. std::string err; std::vector<Node*> nodes = state_.RootNodes(&err); ASSERT_NE("", err); }
ninja-build/ninja
src/missing_deps_test.cc
C++
apache-2.0
5,978
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.ospf.protocol.lsa.linksubtype; import com.google.common.base.MoreObjects; import com.google.common.primitives.Bytes; import org.jboss.netty.buffer.ChannelBuffer; import org.onosproject.ospf.protocol.lsa.TlvHeader; import org.onosproject.ospf.protocol.util.OspfUtil; /** * Representation of maximum reservable bandwidth TE value. */ public class MaximumReservableBandwidth extends TlvHeader implements LinkSubType { private float maximumReservableBandwidth; /** * Creates an instance of maximum reservable bandwidth. * * @param header tlv header */ public MaximumReservableBandwidth(TlvHeader header) { this.setTlvType(header.tlvType()); this.setTlvLength(header.tlvLength()); } /** * Sets value of maximum reversible bandwidth. * * @param maximumBandwidth maximum reversible bandwidth */ public void setMaximumBandwidth(float maximumBandwidth) { this.maximumReservableBandwidth = maximumBandwidth; } /** * Gets value of maximum reversible bandwidth. * * @return maximumBandwidth maximum reversible bandwidth */ public float getMaximumBandwidthValue() { return this.maximumReservableBandwidth; } /** * Reads bytes from channel buffer. * * @param channelBuffer channel buffer instance */ public void readFrom(ChannelBuffer channelBuffer) { byte[] tempByteArray = new byte[tlvLength()]; channelBuffer.readBytes(tempByteArray, 0, tlvLength()); int maxBandwidth = (OspfUtil.byteToInteger(tempByteArray)); this.setMaximumBandwidth(Float.intBitsToFloat(maxBandwidth)); } /** * Returns byte array of maximum reservable bandwidth. * * @return byte array of maximum reservable bandwidth */ public byte[] asBytes() { byte[] linkSubType = null; byte[] linkSubTlvHeader = getTlvHeaderAsByteArray(); byte[] linkSubTlvBody = getLinksubTypeTlvBodyAsByteArray(); linkSubType = Bytes.concat(linkSubTlvHeader, linkSubTlvBody); return linkSubType; } /** * Gets maximum reservable bandwidth sub tlv body as byte array. * * @return byte of maximum reservable bandwidth sub tlv body */ public byte[] getLinksubTypeTlvBodyAsByteArray() { byte[] linkSubTypeBody; linkSubTypeBody = OspfUtil.convertToFourBytes(Float.floatToIntBits(this.maximumReservableBandwidth)); return linkSubTypeBody; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("maximumReservableBandwidth", maximumReservableBandwidth) .toString(); } }
sdnwiselab/onos
protocols/ospf/protocol/src/main/java/org/onosproject/ospf/protocol/lsa/linksubtype/MaximumReservableBandwidth.java
Java
apache-2.0
3,359
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-12-09 21:59 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('osf', '0025_preprintprovider_social_instagram'), ] operations = [ migrations.AddField( model_name='preprintservice', name='license', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='osf.NodeLicenseRecord'), ), ]
mluo613/osf.io
osf/migrations/0026_preprintservice_license.py
Python
apache-2.0
583
<body data-spy="scroll" data-target=".topbar" data-offset="90"> <nav class="navbar navbar-default navbar-fixed-top topbar"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="https://github.com/linkedin/naarad">naarad</a> </div> <div id="navbar"> <ul class="nav navbar-nav"> {% if summary_enabled %} <li><a href="summary_report.html" title="Summary"><span>Summary</span></a></li> {% endif %} <li class="active dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <span>Metrics</span> <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> {%- for metric_name in metric_list %} <li> <a href="{{ metric_name.label }}_report.html"> <span>{{ metric_name.label }}</span> </a> </li> {%- endfor %} </ul> </li> <li><a href="report.html"></span>Chart</span></a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Back to Top</a></li> </ul> </div> </div> </nav> <!-- Container --> <div class="container-fluid"> <div class="content"> <!-- Title --> <div id="{{ metric.label }}-header" class="row"> <div id="{{ metric.label }}-header-span" class="col-md-12"> <h2 class="content-title"> <span class="text">{{ metric.label }}</span> </h2> </div> </div> <div class="btn-group" role="group" aria-label="btn-group"> {%- if metric.anomalies|length > 0 %} <button type="button" class="btn btn-default" onclick="jumpTo('anomalies')"> Anomalies </button> {%- endif %} {%- if metric.sla_list|length > 0 %} <button type="button" class="btn btn-default" onclick="jumpTo('sla')"> SLA Summary </button> {%- endif %} {%- if metric.summary_stats|length %} <button type="button" class="btn btn-default" onclick="jumpTo('metric-summary')"> Metric Summary </button> {%- endif %} {%- if plot_div_content %} <button type="button" class="btn btn-default" onclick="jumpTo('metric-plots')"> Metric Plots </button> {%- endif %} </div> <!-- Anomalies //TODO --> {%- if metric.anomalies|length > 0 %} <a name="anomalies"></a> <div id="{{ metric.label }}-anomalies-table" class="row"> <div id="{{ metric.label }}-anomalies-table-span" class="col-md-12"> <h3>Notes</h3> <div style="overflow-x:auto;"> <p>Anomalous behavior was detected in {% set metrics_list = [] %} {%- for submetric in metric.anomalies.keys() %} <a href="report.html?charts=resources/{{ metric.label }}.{{ submetric }}.csv" target="_blank"><b>{{ submetric }}</b></a> ( {%- for anomaly in metric.anomalies[submetric] %} <a href="report.html?charts=resources/{{ metric.label }}.{{ submetric }}.csv&range={{ anomaly.start_timestamp }},{{ anomaly.end_timestamp}}" target="_blank">#{{ loop.index }} </a> {%- endfor %} ) {%- if loop.index < metric.anomalies|length %} , {%- endif %} {%- if metrics_list.append('resources/' + metric.label + '.' + submetric + '.csv') %} {%- endif %} {%- endfor %} [<a href="report.html?charts={{ metrics_list|join(',')}}" target="_blank">View All</a>] </p> </div> </div> </div> {%- endif %} <!-- Metrics SLA //TODO --> {%- if metric.sla_list|length > 0 %} <a name="sla"></a> <div id="{{ metric.label }}-sla-table" class="row"> <div id="{{ metric.label }}-sla-table-span" class="col-md-12"> <h3>SLA Summary</h3> <div style="overflow-x:auto;"> <table class="table table-hover table-striped table-bordered sortable"> <thead> <tr> <th>metric</th> <th>sub_metric</th> <th>sla rule</th> <th>value</th> </tr> </thead> <tbody> {%- for sla in metric.sla_list %} {%- if sla.sla_passed == True %} <tr class="success"> {%- elif sla.sla_passed == False %} <tr class="danger"> {%- else %} <tr> {%- endif %} <td>{{ sla.metric }}</td> <td>{{ sla.sub_metric }}</td> <td>{{ sla.stat_name }} {{ sla.sla_type }} {{ sla.threshold}}</td> <td>{{ sla.stat_value }}</td> </tr> {%- endfor %} </tbody> <tfoot></tfoot> </table> </div> </div> </div> {%- endif %} <!-- Metrics Summary --> {%- if metric.summary_stats|length %} <a name="metric-summary"></a> <div id="{{ metric.label }}-summary-table" class="row"> <div id="{{ metric.label }}-summary-table-span" class="col-md-12"> <h3>Metric Summary</h3> <div style="overflow-x:auto;"> <table class="table table-hover table-striped table-bordered sortable"> <thead> <tr> <th>sub_metric</th> {%- for header in metric.summary_stats[metric.summary_stats.keys()[0]].keys()|sort %} <th>{{ header }}</th> {%- endfor %} </tr> </thead> <tbody> {%- for sub_metric in metric.summary_stats.keys() %} <tr> <td> {%- if plot_div_content %} <a href="#{{ metric.label }}.{{ sub_metric | sanitize_string }}">{{ sub_metric }}</a> {%- else %} {{ sub_metric }} {%- endif %} </td> {%- for stat in metric.summary_stats[sub_metric]|sort %} {%- if sub_metric in metric.sla_map.keys() %} {%- if stat in metric.sla_map[sub_metric].keys() %} {%- if metric.sla_map[sub_metric][stat].sla_passed == True %} <td class="success" title="{{ metric.sla_map[sub_metric][stat].stat_name }} {{ metric.sla_map[sub_metric][stat].sla_type }} {{ metric.sla_map[sub_metric][stat].threshold}}">{{ metric.summary_stats[sub_metric][stat] }}</td> {%- elif metric.sla_map[sub_metric][stat].sla_passed == False %} <td class="danger" title="{{ metric.sla_map[sub_metric][stat].stat_name }} {{ metric.sla_map[sub_metric][stat].sla_type }} {{ metric.sla_map[sub_metric][stat].threshold}}">{{ metric.summary_stats[sub_metric][stat] }}</td> {%- else %} <td>{{ metric.summary_stats[sub_metric][stat] }}</td> {%- endif %} {%- else %} <td>{{ metric.summary_stats[sub_metric][stat] }}</td> {%- endif %} {%- else %} <td>{{ metric.summary_stats[sub_metric][stat] }}</td> {%- endif %} {%- endfor %} </tr> {%- endfor %} </tbody> <tfoot></tfoot> </table> </div> </div> </div> {%- endif %} <!-- Metric Plots --> {%- if plot_div_content %} <a name="metric-plots"></a> <div id="{{ metric }}-metric-plots" class="row"> <div id="{{ metric }}-metric-plots-span" class="col-md-12"> <h3>Metric Plots</h3> <p><strong>{{ plot_div_content }}</strong></p> </div> </div> {%- endif %} </div><!-- /content --> </div><!-- /container -->
linkedin/naarad
src/naarad/resources/default_metric_page.html
HTML
apache-2.0
7,886
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Redirection</title> <meta http-equiv="refresh" content="0; url=html/index.html" /> </head> <body> <a href="html/index.html">index.html</a> </body> </html>
mlaz/mynewt-core
net/ip/lwip_base/doc/doxygen/output/index.html
HTML
apache-2.0
351
// Automatically generated by MockGen. DO NOT EDIT! // Source: github.com/docker/infrakit/pkg/spi/flavor (interfaces: Plugin) package flavor import ( types0 "github.com/docker/infrakit/pkg/plugin/group/types" flavor "github.com/docker/infrakit/pkg/spi/flavor" instance "github.com/docker/infrakit/pkg/spi/instance" types "github.com/docker/infrakit/pkg/types" gomock "github.com/golang/mock/gomock" ) // Mock of Plugin interface type MockPlugin struct { ctrl *gomock.Controller recorder *_MockPluginRecorder } // Recorder for MockPlugin (not exported) type _MockPluginRecorder struct { mock *MockPlugin } func NewMockPlugin(ctrl *gomock.Controller) *MockPlugin { mock := &MockPlugin{ctrl: ctrl} mock.recorder = &_MockPluginRecorder{mock} return mock } func (_m *MockPlugin) EXPECT() *_MockPluginRecorder { return _m.recorder } func (_m *MockPlugin) Drain(_param0 *types.Any, _param1 instance.Description) error { ret := _m.ctrl.Call(_m, "Drain", _param0, _param1) ret0, _ := ret[0].(error) return ret0 } func (_mr *_MockPluginRecorder) Drain(arg0, arg1 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCall(_mr.mock, "Drain", arg0, arg1) } func (_m *MockPlugin) Healthy(_param0 *types.Any, _param1 instance.Description) (flavor.Health, error) { ret := _m.ctrl.Call(_m, "Healthy", _param0, _param1) ret0, _ := ret[0].(flavor.Health) ret1, _ := ret[1].(error) return ret0, ret1 } func (_mr *_MockPluginRecorder) Healthy(arg0, arg1 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCall(_mr.mock, "Healthy", arg0, arg1) } func (_m *MockPlugin) Prepare(_param0 *types.Any, _param1 instance.Spec, _param2 types0.AllocationMethod, _param3 types0.Index) (instance.Spec, error) { ret := _m.ctrl.Call(_m, "Prepare", _param0, _param1, _param2, _param3) ret0, _ := ret[0].(instance.Spec) ret1, _ := ret[1].(error) return ret0, ret1 } func (_mr *_MockPluginRecorder) Prepare(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCall(_mr.mock, "Prepare", arg0, arg1, arg2, arg3) } func (_m *MockPlugin) Validate(_param0 *types.Any, _param1 types0.AllocationMethod) error { ret := _m.ctrl.Call(_m, "Validate", _param0, _param1) ret0, _ := ret[0].(error) return ret0 } func (_mr *_MockPluginRecorder) Validate(arg0, arg1 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCall(_mr.mock, "Validate", arg0, arg1) }
FrenchBen/infrakit
pkg/provider/google/mock/flavor/flavor.go
GO
apache-2.0
2,386
/** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package org.waveprotocol.box.server.robots.active; import com.google.inject.Inject; import com.google.wave.api.OperationType; import org.waveprotocol.box.server.robots.AbstractOperationServiceRegistry; import org.waveprotocol.box.server.robots.operations.BlipOperationServices; import org.waveprotocol.box.server.robots.operations.CreateWaveletService; import org.waveprotocol.box.server.robots.operations.DocumentModifyService; import org.waveprotocol.box.server.robots.operations.FetchProfilesService; import org.waveprotocol.box.server.robots.operations.FetchWaveService; import org.waveprotocol.box.server.robots.operations.FolderActionService; import org.waveprotocol.box.server.robots.operations.NotifyOperationService; import org.waveprotocol.box.server.robots.operations.OperationService; import org.waveprotocol.box.server.robots.operations.ParticipantServices; import org.waveprotocol.box.server.robots.operations.WaveletSetTitleService; /** * A registry of {@link OperationService}s for the active robot API. * * @author ljvderijk@google.com (Lennard de Rijk) */ public final class ActiveApiOperationServiceRegistry extends AbstractOperationServiceRegistry { // Suppressing warnings about operations that are deprecated but still used by // the default client libraries @SuppressWarnings("deprecation") @Inject public ActiveApiOperationServiceRegistry(NotifyOperationService notifyOpService) { super(); // Register all the OperationProviders register(OperationType.ROBOT_NOTIFY, notifyOpService); register(OperationType.ROBOT_NOTIFY_CAPABILITIES_HASH, notifyOpService); register(OperationType.WAVELET_ADD_PARTICIPANT_NEWSYNTAX, ParticipantServices.create()); register(OperationType.WAVELET_APPEND_BLIP, BlipOperationServices.create()); register(OperationType.WAVELET_REMOVE_PARTICIPANT_NEWSYNTAX, ParticipantServices.create()); register(OperationType.BLIP_CONTINUE_THREAD, BlipOperationServices.create()); register(OperationType.BLIP_CREATE_CHILD, BlipOperationServices.create()); register(OperationType.BLIP_DELETE, BlipOperationServices.create()); register(OperationType.DOCUMENT_APPEND_INLINE_BLIP, BlipOperationServices.create()); register(OperationType.DOCUMENT_APPEND_MARKUP, BlipOperationServices.create()); register(OperationType.DOCUMENT_INSERT_INLINE_BLIP, BlipOperationServices.create()); register( OperationType.DOCUMENT_INSERT_INLINE_BLIP_AFTER_ELEMENT, BlipOperationServices.create()); register(OperationType.ROBOT_CREATE_WAVELET, CreateWaveletService.create()); register(OperationType.ROBOT_FETCH_WAVE, FetchWaveService.create()); register(OperationType.DOCUMENT_MODIFY, DocumentModifyService.create()); register(OperationType.WAVELET_SET_TITLE, WaveletSetTitleService.create()); register(OperationType.ROBOT_FOLDER_ACTION, FolderActionService.create()); register(OperationType.ROBOT_FETCH_PROFILES, FetchProfilesService.create()); } }
nelsonsilva/wave-protocol
src/org/waveprotocol/box/server/robots/active/ActiveApiOperationServiceRegistry.java
Java
apache-2.0
3,570
/** * SyntaxHighlighter * http://alexgorbatchev.com/ * * @version * 2.0.278 (February 03 2009) * * @author * Alex Gorbatchev * * @copyright * Copyright (C) 2004-2009 Alex Gorbatchev. * * Licensed under a GNU Lesser General Public License. * http://creativecommons.org/licenses/LGPL/2.1/ * * SyntaxHighlighter is donationware. You are allowed to download, modify and distribute * the source code in accordance with LGPL 2.1 license, however if you want to use * SyntaxHighlighter on your site or include it in your product, you must donate. * http://alexgorbatchev.com/wiki/SyntaxHighlighter:Donate */ .syntaxhighlighter, .syntaxhighlighter .bold, .syntaxhighlighter .italic, .syntaxhighlighter .line .number, .syntaxhighlighter .line .content, .syntaxhighlighter .line .content code, .syntaxhighlighter .line .content .block, .syntaxhighlighter .line .content .spaces, .syntaxhighlighter .bar, .syntaxhighlighter .ruler, .syntaxhighlighter .toolbar, .syntaxhighlighter .toolbar a, .syntaxhighlighter .toolbar a:hover { margin: 0; padding: 0; border: 0; outline: 0; background: none; text-align: left; float: none; vertical-align: baseline; position: static; left: auto; top: auto; right: auto; bottom: auto; height: auto; width: auto; line-height: normal; font-family: "Consolas", "Monaco", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace; font-weight: normal; font-style: normal; /*font-size: 80%;*/ } .syntaxhighlighter { width: 100%; margin: 1em 0 1em 0; padding: 1px; /* adds a little border on top and bottom */ position: relative; } .syntaxhighlighter .bold { font-weight: bold; } .syntaxhighlighter .italic { font-style: italic; } .syntaxhighlighter .line .number { float: left; width: 3em; padding-right: .3em; text-align: right; display: block; } /* Disable numbers when no gutter option is set */ .syntaxhighlighter.nogutter .line .number { display: none; } .syntaxhighlighter .line .content { margin-left: 3.3em; padding-left: .5em; display: block; } .syntaxhighlighter .line .content .block { display: block; padding-left: 1.5em; text-indent: -1.5em; } .syntaxhighlighter .line .content .spaces { display: none; } /* Disable border and margin on the lines when no gutter option is set */ .syntaxhighlighter.nogutter .line .content { margin-left: 0; border-left: none; } .syntaxhighlighter .bar { } .syntaxhighlighter.collapsed .bar { } .syntaxhighlighter.nogutter .ruler { margin-left: 0; padding-left: 0; } .syntaxhighlighter .ruler { padding: 0 0 .5em .5em; margin-left: 3.3em; overflow: hidden; } /* Adjust some properties when collapsed */ .syntaxhighlighter.collapsed .lines, .syntaxhighlighter.collapsed .ruler { display: none; } /* Styles for the toolbar */ .syntaxhighlighter .toolbar { position: absolute; right: 0px; top: 0px; font-size: 1px; padding: 8px 8px 8px 0; /* in px because images don't scale with ems */ } .syntaxhighlighter.collapsed .toolbar { font-size: 80%; padding: .2em 0 .5em .5em; position: static; } .syntaxhighlighter .toolbar a.item, .syntaxhighlighter .toolbar .item { display: block; float: left; margin-left: 8px; background-repeat: no-repeat; overflow: hidden; text-indent: -5000px; } .syntaxhighlighter.collapsed .toolbar .item { display: none; } .syntaxhighlighter.collapsed .toolbar .item.expandSource { background-image: url(magnifier.png); display: inline; text-indent: 0; width: auto; float: none; height: 16px; padding-left: 20px; } .syntaxhighlighter .toolbar .item.viewSource { background-image: url(page_white_code.png); } .syntaxhighlighter .toolbar .item.printSource { background-image: url(printer.png); } .syntaxhighlighter .toolbar .item.copyToClipboard { text-indent: 0; background: none; overflow: visible; } .syntaxhighlighter .toolbar .item.about { background-image: url(help.png); } /** * Print view. * Colors are based on the default theme without background. */ .syntaxhighlighter.printing, .syntaxhighlighter.printing .line.alt1 .content, .syntaxhighlighter.printing .line.alt2 .content, .syntaxhighlighter.printing .line.highlighted .number, .syntaxhighlighter.printing .line.highlighted.alt1 .content, .syntaxhighlighter.printing .line.highlighted.alt2 .content, .syntaxhighlighter.printing .line .content .block { background: none; } /* Gutter line numbers */ .syntaxhighlighter.printing .line .number { color: #bbb; } /* Add border to the lines */ .syntaxhighlighter.printing .line .content { color: #000; } /* Toolbar when visible */ .syntaxhighlighter.printing .toolbar, .syntaxhighlighter.printing .ruler { display: none; } .syntaxhighlighter.printing a { text-decoration: none; } .syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { color: #000; } .syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { color: #008200; } .syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { color: blue; } .syntaxhighlighter.printing .keyword { color: #069; font-weight: bold; } .syntaxhighlighter.printing .preprocessor { color: gray; } .syntaxhighlighter.printing .variable { color: #a70; } .syntaxhighlighter.printing .value { color: #090; } .syntaxhighlighter.printing .functions { color: #ff1493; } .syntaxhighlighter.printing .constants { color: #0066CC; } .syntaxhighlighter.printing .script { font-weight: bold; } .syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { color: #808080; } .syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { color: #ff1493; } .syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { color: red; }
Ange1o/ange1o.github.io
css/shCore.css
CSS
apache-2.0
5,745
<?php /** * Contains all client objects for the ReportDefinitionService service. * * PHP version 5 * * Copyright 2013, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package GoogleApiAdsAdWords * @subpackage v201306 * @category WebServices * @copyright 2013, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 * @author Paul Matthews */ /** Required classes. **/ require_once "Google/Api/Ads/AdWords/Lib/AdWordsSoapClient.php"; if (!class_exists("EnumValuePair", FALSE)) { /** * Represents information about enum values. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class EnumValuePair { /** * @access public * @var string */ public $enumValue; /** * @access public * @var string */ public $enumDisplayValue; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "EnumValuePair"; } public function __construct($enumValue = NULL, $enumDisplayValue = NULL) { $this->enumValue = $enumValue; $this->enumDisplayValue = $enumDisplayValue; } }} if (!class_exists("ReportDefinitionField", FALSE)) { /** * Represents the fields that can be used to create a ReportDefinition. * This class allows the user to query the list of fields applicable to a * given report type. Consumers of reports will be able use the retrieved * fields through the {@link ReportDefinitionService#getReportFields} * api and run the corresponding reports. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ReportDefinitionField { /** * @access public * @var string */ public $fieldName; /** * @access public * @var string */ public $displayFieldName; /** * @access public * @var string */ public $xmlAttributeName; /** * @access public * @var string */ public $fieldType; /** * @access public * @var string[] */ public $enumValues; /** * @access public * @var boolean */ public $canSelect; /** * @access public * @var boolean */ public $canFilter; /** * @access public * @var boolean */ public $isEnumType; /** * @access public * @var boolean */ public $isBeta; /** * @access public * @var EnumValuePair[] */ public $enumValuePairs; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ReportDefinitionField"; } public function __construct($fieldName = NULL, $displayFieldName = NULL, $xmlAttributeName = NULL, $fieldType = NULL, $enumValues = NULL, $canSelect = NULL, $canFilter = NULL, $isEnumType = NULL, $isBeta = NULL, $enumValuePairs = NULL) { $this->fieldName = $fieldName; $this->displayFieldName = $displayFieldName; $this->xmlAttributeName = $xmlAttributeName; $this->fieldType = $fieldType; $this->enumValues = $enumValues; $this->canSelect = $canSelect; $this->canFilter = $canFilter; $this->isEnumType = $isEnumType; $this->isBeta = $isBeta; $this->enumValuePairs = $enumValuePairs; } }} if (!class_exists("SoapRequestHeader", FALSE)) { /** * Defines the required and optional elements within the header of a SOAP request. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class SoapRequestHeader { /** * @access public * @var string */ public $authToken; /** * @access public * @var string */ public $clientCustomerId; /** * @access public * @var string */ public $developerToken; /** * @access public * @var string */ public $userAgent; /** * @access public * @var boolean */ public $validateOnly; /** * @access public * @var boolean */ public $partialFailure; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "SoapHeader"; } public function __construct($authToken = NULL, $clientCustomerId = NULL, $developerToken = NULL, $userAgent = NULL, $validateOnly = NULL, $partialFailure = NULL) { $this->authToken = $authToken; $this->clientCustomerId = $clientCustomerId; $this->developerToken = $developerToken; $this->userAgent = $userAgent; $this->validateOnly = $validateOnly; $this->partialFailure = $partialFailure; } }} if (!class_exists("SoapResponseHeader", FALSE)) { /** * Defines the elements within the header of a SOAP response. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class SoapResponseHeader { /** * @access public * @var string */ public $requestId; /** * @access public * @var string */ public $serviceName; /** * @access public * @var string */ public $methodName; /** * @access public * @var integer */ public $operations; /** * @access public * @var integer */ public $responseTime; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "SoapResponseHeader"; } public function __construct($requestId = NULL, $serviceName = NULL, $methodName = NULL, $operations = NULL, $responseTime = NULL) { $this->requestId = $requestId; $this->serviceName = $serviceName; $this->methodName = $methodName; $this->operations = $operations; $this->responseTime = $responseTime; } }} if (!class_exists("ApiError", FALSE)) { /** * The API error base class that provides details about an error that occurred * while processing a service request. * * <p>The OGNL field path is provided for parsers to identify the request data * element that may have caused the error.</p> * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ApiError { /** * @access public * @var string */ public $fieldPath; /** * @access public * @var string */ public $trigger; /** * @access public * @var string */ public $errorString; /** * @access public * @var string */ public $ApiErrorType; private $_parameterMap = array ( "ApiError.Type" => "ApiErrorType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get. * @return mixed Variable value */ public function __get($var) { if (!array_key_exists($var, $this->_parameterMap)) { return NULL; } else { return $this->{$this->_parameterMap[$var]}; } } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApiError"; } public function __construct($fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ApplicationException", FALSE)) { /** * Base class for exceptions. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ApplicationException { /** * @access public * @var string */ public $message; /** * @access public * @var string */ public $ApplicationExceptionType; private $_parameterMap = array ( "ApplicationException.Type" => "ApplicationExceptionType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get. * @return mixed Variable value */ public function __get($var) { if (!array_key_exists($var, $this->_parameterMap)) { return NULL; } else { return $this->{$this->_parameterMap[$var]}; } } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApplicationException"; } public function __construct($message = NULL, $ApplicationExceptionType = NULL) { $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } }} if (!class_exists("AuthenticationErrorReason", FALSE)) { /** * The single reason for the authentication failure. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class AuthenticationErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AuthenticationError.Reason"; } public function __construct() { } }} if (!class_exists("AuthorizationErrorReason", FALSE)) { /** * The reasons for the database error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class AuthorizationErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AuthorizationError.Reason"; } public function __construct() { } }} if (!class_exists("BetaErrorReason", FALSE)) { /** * The reasons for the beta error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class BetaErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "BetaError.Reason"; } public function __construct() { } }} if (!class_exists("ClientTermsErrorReason", FALSE)) { /** * Enums for the various reasons an error can be thrown as a result of * ClientTerms violation. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ClientTermsErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ClientTermsError.Reason"; } public function __construct() { } }} if (!class_exists("CollectionSizeErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class CollectionSizeErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CollectionSizeError.Reason"; } public function __construct() { } }} if (!class_exists("DatabaseErrorReason", FALSE)) { /** * The reasons for the database error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class DatabaseErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DatabaseError.Reason"; } public function __construct() { } }} if (!class_exists("DateErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class DateErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DateError.Reason"; } public function __construct() { } }} if (!class_exists("DistinctErrorReason", FALSE)) { /** * The reasons for the validation error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class DistinctErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DistinctError.Reason"; } public function __construct() { } }} if (!class_exists("IdErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class IdErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "IdError.Reason"; } public function __construct() { } }} if (!class_exists("InternalApiErrorReason", FALSE)) { /** * The single reason for the internal API error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class InternalApiErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "InternalApiError.Reason"; } public function __construct() { } }} if (!class_exists("NotEmptyErrorReason", FALSE)) { /** * The reasons for the validation error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class NotEmptyErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NotEmptyError.Reason"; } public function __construct() { } }} if (!class_exists("NotWhitelistedErrorReason", FALSE)) { /** * The single reason for the whitelist error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class NotWhitelistedErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NotWhitelistedError.Reason"; } public function __construct() { } }} if (!class_exists("NullErrorReason", FALSE)) { /** * The reasons for the validation error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class NullErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NullError.Reason"; } public function __construct() { } }} if (!class_exists("OperatorErrorReason", FALSE)) { /** * The reasons for the validation error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class OperatorErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "OperatorError.Reason"; } public function __construct() { } }} if (!class_exists("QuotaCheckErrorReason", FALSE)) { /** * Enums for all the reasons an error can be thrown to the user during * billing quota checks. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class QuotaCheckErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "QuotaCheckError.Reason"; } public function __construct() { } }} if (!class_exists("RangeErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RangeErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RangeError.Reason"; } public function __construct() { } }} if (!class_exists("RateExceededErrorReason", FALSE)) { /** * The reason for the rate exceeded error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RateExceededErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RateExceededError.Reason"; } public function __construct() { } }} if (!class_exists("ReadOnlyErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ReadOnlyErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ReadOnlyError.Reason"; } public function __construct() { } }} if (!class_exists("RejectedErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RejectedErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RejectedError.Reason"; } public function __construct() { } }} if (!class_exists("ReportDefinitionReportType", FALSE)) { /** * Enums for report types. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ReportDefinitionReportType { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ReportDefinition.ReportType"; } public function __construct() { } }} if (!class_exists("ReportDefinitionErrorReason", FALSE)) { /** * Enums for all the reasons an error can be thrown to the user during * a {@link ReportDefinitionService#mutate(java.util.List)} operation. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ReportDefinitionErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ReportDefinitionError.Reason"; } public function __construct() { } }} if (!class_exists("RequestErrorReason", FALSE)) { /** * Error reason is unknown. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RequestErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequestError.Reason"; } public function __construct() { } }} if (!class_exists("RequiredErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RequiredErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequiredError.Reason"; } public function __construct() { } }} if (!class_exists("SizeLimitErrorReason", FALSE)) { /** * The reasons for Ad Scheduling errors. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class SizeLimitErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "SizeLimitError.Reason"; } public function __construct() { } }} if (!class_exists("StringLengthErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class StringLengthErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "StringLengthError.Reason"; } public function __construct() { } }} if (!class_exists("getReportFields", FALSE)) { /** * <span class="constraint Required">This field is required and should not be {@code null}.</span> * * * * Returns the available report fields for a given report type. * * @param reportType The type of report. * @return The list of available report fields. Each * {@link ReportDefinitionField} encapsulates the field name, the * field data type, and the enum values (if the field's type is * {@code enum}). * @throws ApiException if a problem occurred while fetching the * ReportDefinitionField information. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class getReportFields { /** * @access public * @var tnsReportDefinitionReportType */ public $reportType; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return ""; } public function __construct($reportType = NULL) { $this->reportType = $reportType; } }} if (!class_exists("getReportFieldsResponse", FALSE)) { /** * * @package GoogleApiAdsAdWords * @subpackage v201306 */ class getReportFieldsResponse { /** * @access public * @var ReportDefinitionField[] */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return ""; } public function __construct($rval = NULL) { $this->rval = $rval; } }} if (!class_exists("AuthenticationError", FALSE)) { /** * Errors returned when Authentication failed. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class AuthenticationError extends ApiError { /** * @access public * @var tnsAuthenticationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AuthenticationError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("AuthorizationError", FALSE)) { /** * Errors encountered when trying to authorize a user. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class AuthorizationError extends ApiError { /** * @access public * @var tnsAuthorizationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AuthorizationError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("BetaError", FALSE)) { /** * Errors that are thrown when a Beta feature is accessed incorrectly. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class BetaError extends ApiError { /** * @access public * @var tnsBetaErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "BetaError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ClientTermsError", FALSE)) { /** * Error due to user not accepting the AdWords terms of service. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ClientTermsError extends ApiError { /** * @access public * @var tnsClientTermsErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ClientTermsError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("CollectionSizeError", FALSE)) { /** * Errors associated with the size of the given collection being * out of bounds. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class CollectionSizeError extends ApiError { /** * @access public * @var tnsCollectionSizeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CollectionSizeError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("DateError", FALSE)) { /** * Errors associated with invalid dates and date ranges. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class DateError extends ApiError { /** * @access public * @var tnsDateErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DateError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("DistinctError", FALSE)) { /** * Errors related to distinct ids or content. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class DistinctError extends ApiError { /** * @access public * @var tnsDistinctErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DistinctError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("IdError", FALSE)) { /** * Errors associated with the ids. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class IdError extends ApiError { /** * @access public * @var tnsIdErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "IdError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("InternalApiError", FALSE)) { /** * Indicates that a server-side error has occured. {@code InternalApiError}s * are generally not the result of an invalid request or message sent by the * client. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class InternalApiError extends ApiError { /** * @access public * @var tnsInternalApiErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "InternalApiError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("NotEmptyError", FALSE)) { /** * Errors corresponding with violation of a NOT EMPTY check. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class NotEmptyError extends ApiError { /** * @access public * @var tnsNotEmptyErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NotEmptyError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("NotWhitelistedError", FALSE)) { /** * Indicates that the customer is not whitelisted for accessing the API. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class NotWhitelistedError extends ApiError { /** * @access public * @var tnsNotWhitelistedErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NotWhitelistedError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("NullError", FALSE)) { /** * Errors associated with violation of a NOT NULL check. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class NullError extends ApiError { /** * @access public * @var tnsNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NullError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("OperatorError", FALSE)) { /** * Errors due to the use of unsupported operations. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class OperatorError extends ApiError { /** * @access public * @var tnsOperatorErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "OperatorError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("QuotaCheckError", FALSE)) { /** * Encapsulates the errors thrown during developer quota checks. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class QuotaCheckError extends ApiError { /** * @access public * @var tnsQuotaCheckErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "QuotaCheckError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RangeError", FALSE)) { /** * A list of all errors associated with the Range constraint. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RangeError extends ApiError { /** * @access public * @var tnsRangeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RangeError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RateExceededError", FALSE)) { /** * Signals that a call failed because a measured rate exceeded. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RateExceededError extends ApiError { /** * @access public * @var tnsRateExceededErrorReason */ public $reason; /** * @access public * @var string */ public $rateName; /** * @access public * @var string */ public $rateScope; /** * @access public * @var integer */ public $retryAfterSeconds; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RateExceededError"; } public function __construct($reason = NULL, $rateName = NULL, $rateScope = NULL, $retryAfterSeconds = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->rateName = $rateName; $this->rateScope = $rateScope; $this->retryAfterSeconds = $retryAfterSeconds; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ReadOnlyError", FALSE)) { /** * Errors from attempting to write to read-only fields. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ReadOnlyError extends ApiError { /** * @access public * @var tnsReadOnlyErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ReadOnlyError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RejectedError", FALSE)) { /** * Indicates that a field was rejected due to compatibility issues. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RejectedError extends ApiError { /** * @access public * @var tnsRejectedErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RejectedError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ReportDefinitionError", FALSE)) { /** * Encapsulates the errors that can be thrown during {@link ReportDefinition} * mutate operation. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ReportDefinitionError extends ApiError { /** * @access public * @var tnsReportDefinitionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ReportDefinitionError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RequestError", FALSE)) { /** * Encapsulates the generic errors thrown when there's an error with user * request. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RequestError extends ApiError { /** * @access public * @var tnsRequestErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequestError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RequiredError", FALSE)) { /** * Errors due to missing required field. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class RequiredError extends ApiError { /** * @access public * @var tnsRequiredErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequiredError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("SizeLimitError", FALSE)) { /** * Indicates that the number of entries in the request or response exceeds the system limit. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class SizeLimitError extends ApiError { /** * @access public * @var tnsSizeLimitErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "SizeLimitError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("StringLengthError", FALSE)) { /** * Errors associated with the length of the given string being * out of bounds. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class StringLengthError extends ApiError { /** * @access public * @var tnsStringLengthErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "StringLengthError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("DatabaseError", FALSE)) { /** * Errors that are thrown due to a database access problem. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class DatabaseError extends ApiError { /** * @access public * @var tnsDatabaseErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DatabaseError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ApiException", FALSE)) { /** * Exception class for holding a list of service errors. * @package GoogleApiAdsAdWords * @subpackage v201306 */ class ApiException extends ApplicationException { /** * @access public * @var ApiError[] */ public $errors; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://adwords.google.com/api/adwords/cm/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApiException"; } public function __construct($errors = NULL, $message = NULL, $ApplicationExceptionType = NULL) { parent::__construct(); $this->errors = $errors; $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } }} if (!class_exists("ReportDefinitionService", FALSE)) { /** * ReportDefinitionService * @package GoogleApiAdsAdWords * @subpackage v201306 * @author WSDLInterpreter */ class ReportDefinitionService extends AdWordsSoapClient { /** * Default class map for wsdl=>php * @access private * @var array */ public static $classmap = array( "getResponse" => "ReportDefinitionServiceGetResponse", "get" => "ReportDefinitionServiceGet", "mutate" => "ReportDefinitionServiceMutate", "mutateResponse" => "ReportDefinitionServiceMutateResponse", "DateTime" => "AdWordsDateTime", "SoapHeader" => "SoapRequestHeader", "AuthenticationError" => "AuthenticationError", "ApiError" => "ApiError", "AuthorizationError" => "AuthorizationError", "BetaError" => "BetaError", "ClientTermsError" => "ClientTermsError", "CollectionSizeError" => "CollectionSizeError", "DateError" => "DateError", "DistinctError" => "DistinctError", "EnumValuePair" => "EnumValuePair", "IdError" => "IdError", "InternalApiError" => "InternalApiError", "NotEmptyError" => "NotEmptyError", "NotWhitelistedError" => "NotWhitelistedError", "NullError" => "NullError", "OperatorError" => "OperatorError", "QuotaCheckError" => "QuotaCheckError", "RangeError" => "RangeError", "RateExceededError" => "RateExceededError", "ReadOnlyError" => "ReadOnlyError", "RejectedError" => "RejectedError", "ReportDefinitionError" => "ReportDefinitionError", "ReportDefinitionField" => "ReportDefinitionField", "RequestError" => "RequestError", "RequiredError" => "RequiredError", "SizeLimitError" => "SizeLimitError", "SoapResponseHeader" => "SoapResponseHeader", "StringLengthError" => "StringLengthError", "DatabaseError" => "DatabaseError", "ApiException" => "ApiException", "ApplicationException" => "ApplicationException", "AuthenticationError.Reason" => "AuthenticationErrorReason", "AuthorizationError.Reason" => "AuthorizationErrorReason", "BetaError.Reason" => "BetaErrorReason", "ClientTermsError.Reason" => "ClientTermsErrorReason", "CollectionSizeError.Reason" => "CollectionSizeErrorReason", "DatabaseError.Reason" => "DatabaseErrorReason", "DateError.Reason" => "DateErrorReason", "DistinctError.Reason" => "DistinctErrorReason", "IdError.Reason" => "IdErrorReason", "InternalApiError.Reason" => "InternalApiErrorReason", "NotEmptyError.Reason" => "NotEmptyErrorReason", "NotWhitelistedError.Reason" => "NotWhitelistedErrorReason", "NullError.Reason" => "NullErrorReason", "OperatorError.Reason" => "OperatorErrorReason", "QuotaCheckError.Reason" => "QuotaCheckErrorReason", "RangeError.Reason" => "RangeErrorReason", "RateExceededError.Reason" => "RateExceededErrorReason", "ReadOnlyError.Reason" => "ReadOnlyErrorReason", "RejectedError.Reason" => "RejectedErrorReason", "ReportDefinition.ReportType" => "ReportDefinitionReportType", "ReportDefinitionError.Reason" => "ReportDefinitionErrorReason", "RequestError.Reason" => "RequestErrorReason", "RequiredError.Reason" => "RequiredErrorReason", "SizeLimitError.Reason" => "SizeLimitErrorReason", "StringLengthError.Reason" => "StringLengthErrorReason", "getReportFields" => "getReportFields", "getReportFieldsResponse" => "getReportFieldsResponse", ); /** * The endpoint of the service * @var string */ public static $endpoint = "https://adwords.google.com/api/adwords/cm/v201306/ReportDefinitionService"; /** * Constructor using wsdl location and options array * @param string $wsdl WSDL location for this service * @param array $options Options for the SoapClient */ public function __construct($wsdl=null, $options, $user) { $options["classmap"] = ReportDefinitionService::$classmap; parent::__construct($wsdl, $options, $user, 'ReportDefinitionService', 'https://adwords.google.com/api/adwords/cm/v201306'); } /** * <span class="constraint Required">This field is required and should not be {@code null}.</span> * * * * Returns the available report fields for a given report type. * * @param reportType The type of report. * @return The list of available report fields. Each * {@link ReportDefinitionField} encapsulates the field name, the * field data type, and the enum values (if the field's type is * {@code enum}). * @throws ApiException if a problem occurred while fetching the * ReportDefinitionField information. */ public function getReportFields($reportType) { $arg = new getReportFields($reportType); $result = $this->__soapCall("getReportFields", array($arg)); return $result->rval; } }}
surapan2521/google-api-adwords-php
src/Google/Api/Ads/AdWords/v201306/ReportDefinitionService.php
PHP
apache-2.0
57,967
<!DOCTYPE html> <html lang="en"> <head> <title>How do I enable student peer review for an assignment?</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta content="sakai.assignment" name="description"> <meta content="peer review, peer assessment, peer evaluation" name="search"> <link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="../css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <script src="/library/webjars/jquery/1.12.4/jquery.min.js" type="text/javascript" charset="utf-8"></script><script src="/library/js/jquery/featherlight/0.4.0/featherlight.min.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='featherlight']").featherlight({ type: { image:true }, closeOnClick: 'anywhere' }); }); </script> </head> <body> <div id="wrapper"><div id="article-content"> <div id="article-header"><h1 class="article-title">How do I modify Calendar permissions?</h1></div> <div id="article-description"> <div class="step screensteps-section screensteps-depth-1" id="go-to-calendar"> <h2 id="go-to-calendar" class="step-title screensteps-heading">Go to Calendar.</h2> <div class="image screensteps-image"> <img src="https://media.screensteps.com/image_assets/assets/001/152/663/original/1f786832-1d06-4edb-ae61-260e128d0248.png" alt="" height="118" width="199"> </div> <div class="step-instructions screensteps-textblock"> <p>Select the <strong>Calendar</strong> tool from the Tool Menu in your site. </p> </div> </div> <div class="step screensteps-section screensteps-depth-1" id="click-permissions"> <h2 id="click-permissions" class="step-title screensteps-heading">Click Permissions.</h2> <div class="image screensteps-image"> <a rel="nofollow" href="https://media.screensteps.com/image_assets/assets/001/152/666/original/664c6f91-efc4-406f-adcd-89ea6acf56bb.png" class="screensteps-image-zoom"> <img src="https://media.screensteps.com/image_assets/assets/001/152/666/medium/664c6f91-efc4-406f-adcd-89ea6acf56bb.png" alt="" height="486" width="855"> </a> </div> </div> <div class="step screensteps-section screensteps-depth-1" id="modify-the-permissions-for-the-roles-listed"> <h2 id="modify-the-permissions-for-the-roles-listed" class="step-title screensteps-heading">Modify the permissions for the roles listed.</h2> <div class="image screensteps-image"> <img src="https://media.screensteps.com/image_assets/assets/001/152/669/original/83058e24-8459-4591-9de1-eec3dfa85dce.png" alt="" height="624" width="758"> </div> <div class="step-instructions screensteps-textblock"> <ol> <li>Check the box next to each permission you would like to allow for a given role. (Deselecting a box will remove the corresponding permission.)</li> <li>Click <strong>Save</strong> to save your changes.</li> </ol> <p><em>Note: You may see different roles listed depending on the roles which exist in your site. A role must be present in the site in order for you to modify its permissions.</em></p> </div> </div> </div> </div></div> </body> </html>
OpenCollabZA/sakai
help/help/src/sakai_screensteps_calendarUserGuide/howdoImodifyCalendarpermissions.html
HTML
apache-2.0
3,536
// Package level implements leveled logging on top of package log. To use the // level package, create a logger as per normal in your func main, and wrap it // with level.NewFilter. // // var logger log.Logger // logger = log.NewLogfmtLogger(os.Stderr) // logger = level.NewFilter(logger, level.AllowInfo()) // <-- // logger = log.With(logger, "ts", log.DefaultTimestampUTC) // // Then, at the callsites, use one of the level.Debug, Info, Warn, or Error // helper methods to emit leveled log events. // // logger.Log("foo", "bar") // as normal, no level // level.Debug(logger).Log("request_id", reqID, "trace_data", trace.Get()) // if value > 100 { // level.Error(logger).Log("value", value) // } // // NewFilter allows precise control over what happens when a log event is // emitted without a level key, or if a squelched level is used. Check the // Option functions for details. package level
Thib17/graphite-remote-adapter
vendor/github.com/go-kit/kit/log/level/doc.go
GO
apache-2.0
927
/* * Copyright 2013, 2014 Deutsche Nationalbibliothek * * Licensed under the Apache License, Version 2.0 the "License"; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.culturegraph.mf.types; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Basic implementation of {@link MultiMap} * * @author Markus Michael Geipel * */ public class MultiHashMap implements MultiMap{ private final Map<String, Map<String, String>> data = new HashMap<String, Map<String, String>>(); @Override public final Map<String, String> getMap(final String mapName) { final Map<String, String> map = data.get(mapName); if (map == null) { return Collections.emptyMap(); } return map; } @Override public final String getValue(final String mapName, final String key) { final Map<String, String> map = getMap(mapName); final String value = map.get(key); if (value == null) { return map.get(MultiMap.DEFAULT_MAP_KEY); } return value; } @Override public final String toString() { return data.toString(); } @Override public final Map<String, String> putMap(final String mapName, final Map<String, String> map) { return data.put(mapName, map); } @Override public final String putValue(final String mapName, final String key, final String value) { Map<String, String> map = data.get(mapName); if (map == null) { map = new HashMap<String, String>(); data.put(mapName, map); } return map.put(key, value); } @Override public final Collection<String> getMapNames() { return Collections.unmodifiableSet(data.keySet()); } }
philboeselager/metafacture-core
src/main/java/org/culturegraph/mf/types/MultiHashMap.java
Java
apache-2.0
2,104
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.util; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.PsiModificationTrackerImpl; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author peter */ public abstract class SdkHomeSettings implements PersistentStateComponent<SdkHomeConfigurable.SdkHomeBean> { private final PsiModificationTrackerImpl myTracker; private SdkHomeConfigurable.SdkHomeBean mySdkPath; protected SdkHomeSettings(Project project) { myTracker = (PsiModificationTrackerImpl)PsiManager.getInstance(project).getModificationTracker(); } public SdkHomeConfigurable.SdkHomeBean getState() { return mySdkPath; } public void loadState(SdkHomeConfigurable.SdkHomeBean state) { mySdkPath = state; myTracker.incCounter(); } @Nullable private static VirtualFile calcHome(final SdkHomeConfigurable.SdkHomeBean state) { if (state == null) { return null; } @SuppressWarnings({"NonPrivateFieldAccessedInSynchronizedContext"}) final String sdk_home = state.SDK_HOME; if (StringUtil.isEmpty(sdk_home)) { return null; } return LocalFileSystem.getInstance().findFileByPath(sdk_home); } @Nullable public VirtualFile getSdkHome() { return calcHome(mySdkPath); } public List<VirtualFile> getClassRoots() { return calcRoots(getSdkHome()); } private static List<VirtualFile> calcRoots(@Nullable VirtualFile home) { if (home == null) { return Collections.emptyList(); } final VirtualFile lib = home.findChild("lib"); if (lib == null) { return Collections.emptyList(); } final ArrayList<VirtualFile> result = new ArrayList<VirtualFile>(); for (VirtualFile file : lib.getChildren()) { if ("jar".equals(file.getExtension())) { ContainerUtil.addIfNotNull(JarFileSystem.getInstance().getJarRootForLocalFile(file), result); } } return result; } }
android-ia/platform_tools_idea
plugins/groovy/src/org/jetbrains/plugins/groovy/util/SdkHomeSettings.java
Java
apache-2.0
2,956
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.llap.registry; import com.google.common.base.Preconditions; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.llap.LlapUtil; import org.apache.hadoop.hive.registry.ServiceInstance; import org.apache.hadoop.yarn.api.records.Resource; public interface LlapServiceInstance extends ServiceInstance { /** * Management endpoint for service instance * * @return */ public int getManagementPort(); /** * Shuffle Endpoint for service instance * * @return */ public int getShufflePort(); /** * Address for services hosted on http * @return */ public String getServicesAddress(); /** * OutputFormat endpoint for service instance * * @return */ public int getOutputFormatPort(); /** * External host, usually needed in cloud envs where we cannot access internal host from outside * * @return */ String getExternalHostname(); /** * RPC endpoint for external clients - tcp traffic on this port should be opened on cloud. * * @return */ int getExternalClientsRpcPort(); default void ensureCloudEnv(Configuration conf) { Preconditions.checkState(LlapUtil.isCloudDeployment(conf), "Only supported in cloud based deployments"); } /** * Memory and Executors available for the LLAP tasks * * This does not include the size of the cache or the actual vCores allocated via YARN. * * @return */ public Resource getResource(); }
sankarh/hive
llap-client/src/java/org/apache/hadoop/hive/llap/registry/LlapServiceInstance.java
Java
apache-2.0
2,069
/** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.eca.component.eca; import java.util.concurrent.BlockingQueue; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.WaitForTaskToComplete; import org.apache.camel.component.seda.SedaProducer; public class EcaProducer extends SedaProducer { EcaEndpoint ecaEndpoint; public EcaProducer(EcaEndpoint endpoint, BlockingQueue<Exchange> queue, WaitForTaskToComplete waitForTaskToComplete, long timeout) { super(endpoint, queue, waitForTaskToComplete, timeout); this.ecaEndpoint = endpoint; } @Override public boolean process(Exchange exchange, AsyncCallback callback) { // TODO: Remove this when CAMEL-4806 is in released Fuse Camel version exchange.getIn().setHeader("EcaRouteId", exchange.getFromRouteId()); return super.process(exchange, callback); } }
janstey/fuse
sandbox/eca/eca-core/src/main/java/org/fusesource/eca/component/eca/EcaProducer.java
Java
apache-2.0
1,510
/* FONT STACK */ body, input, select, textarea { font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; } h1, h2, h3, h4, h5, h6 { line-height: 1.1; } /* BASE LAYOUT */ html { background-color: #ddd; background-image: -moz-linear-gradient(center top, #aaa, #ddd); background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #aaa), color-stop(1, #ddd)); background-image: linear-gradient(top, #aaa, #ddd); filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#aaaaaa', EndColorStr='#dddddd'); background-repeat: no-repeat; height: 100%; /* change the box model to exclude the padding from the calculation of 100% height (IE8+) */ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } html.no-cssgradients { background-color: #aaa; } .ie6 html { height: 100%; } html * { margin: 0; } body { background: #ffffff; color: #333333; margin: 0 auto; max-width: 960px; overflow-x: hidden; /* prevents box-shadow causing a horizontal scrollbar in firefox when viewport < 960px wide */ -moz-box-shadow: 0 0 0.3em #255b17; -webkit-box-shadow: 0 0 0.3em #255b17; box-shadow: 0 0 0.3em #255b17; } #grailsLogo { background-color: #abbf78; } /* replace with .no-boxshadow body if you have modernizr available */ .ie6 body, .ie7 body, .ie8 body { border-color: #255b17; border-style: solid; border-width: 0 1px; } .ie6 body { height: 100%; } a:link, a:visited, a:hover { color: #48802c; } a:hover, a:active { outline: none; /* prevents outline in webkit on active links but retains it for tab focus */ } h1 { color: #48802c; font-weight: normal; font-size: 1.25em; margin: 0.8em 0 0.3em 0; } ul { padding: 0; } img { border: 0; } /* GENERAL */ #grailsLogo a { display: inline-block; margin: 1em; } .content { } .content h1 { border-bottom: 1px solid #CCCCCC; margin: 0.8em 1em 0.3em; padding: 0 0.25em; } .scaffold-list h1 { border: none; } .footer { background: #abbf78; color: #000; clear: both; font-size: 0.8em; margin-top: 1.5em; padding: 1em; min-height: 1em; } .footer a { color: #255b17; } .spinner { background: url(../images/spinner.gif) 50% 50% no-repeat transparent; height: 16px; width: 16px; padding: 0.5em; position: absolute; right: 0; top: 0; text-indent: -9999px; } /* NAVIGATION MENU */ .nav { background-color: #efefef; padding: 0.5em 0.75em; -moz-box-shadow: 0 0 3px 1px #aaaaaa; -webkit-box-shadow: 0 0 3px 1px #aaaaaa; box-shadow: 0 0 3px 1px #aaaaaa; zoom: 1; } .nav ul { overflow: hidden; padding-left: 0; zoom: 1; } .nav li { display: block; float: left; list-style-type: none; margin-right: 0.5em; padding: 0; } .nav a { color: #666666; display: block; padding: 0.25em 0.7em; text-decoration: none; -moz-border-radius: 0.3em; -webkit-border-radius: 0.3em; border-radius: 0.3em; } .nav a:active, .nav a:visited { color: #666666; } .nav a:focus, .nav a:hover { background-color: #999999; color: #ffffff; outline: none; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.8); } .no-borderradius .nav a:focus, .no-borderradius .nav a:hover { background-color: transparent; color: #444444; text-decoration: underline; } .nav a.home, .nav a.list, .nav a.create { background-position: 0.7em center; background-repeat: no-repeat; text-indent: 25px; } .nav a.home { background-image: url(../images/skin/house.png); } .nav a.list { background-image: url(../images/skin/database_table.png); } .nav a.create { background-image: url(../images/skin/database_add.png); } /* CREATE/EDIT FORMS AND SHOW PAGES */ fieldset, .property-list { margin: 0.6em 1.25em 0 1.25em; padding: 0.3em 1.8em 1.25em; position: relative; zoom: 1; border: none; } .property-list .fieldcontain { list-style: none; overflow: hidden; zoom: 1; } .fieldcontain { margin-top: 1em; } .fieldcontain label, .fieldcontain .property-label { color: #666666; text-align: right; width: 25%; } .fieldcontain .property-label { float: left; } .fieldcontain .property-value { display: block; margin-left: 27%; } label { cursor: pointer; display: inline-block; margin: 0 0.25em 0 0; } input, select, textarea { background-color: #fcfcfc; border: 1px solid #cccccc; font-size: 1em; padding: 0.2em 0.4em; } select { padding: 0.2em 0.2em 0.2em 0; } select[multiple] { vertical-align: top; } textarea { width: 250px; height: 150px; overflow: auto; /* IE always renders vertical scrollbar without this */ vertical-align: top; } input[type=checkbox], input[type=radio] { background-color: transparent; border: 0; padding: 0; } input:focus, select:focus, textarea:focus { background-color: #ffffff; border: 1px solid #eeeeee; outline: 0; -moz-box-shadow: 0 0 0.5em #ffffff; -webkit-box-shadow: 0 0 0.5em #ffffff; box-shadow: 0 0 0.5em #ffffff; } .required-indicator { color: #48802C; display: inline-block; font-weight: bold; margin-left: 0.3em; position: relative; top: 0.1em; } ul.one-to-many { display: inline-block; list-style-position: inside; vertical-align: top; } .ie6 ul.one-to-many, .ie7 ul.one-to-many { display: inline; zoom: 1; } ul.one-to-many li.add { list-style-type: none; } /* EMBEDDED PROPERTIES */ fieldset.embedded { background-color: transparent; border: 1px solid #CCCCCC; margin-left: 0; margin-right: 0; padding-left: 0; padding-right: 0; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } fieldset.embedded legend { margin: 0 1em; } /* MESSAGES AND ERRORS */ .errors, .message { font-size: 0.8em; line-height: 2; margin: 1em 2em; padding: 0.25em; } .message { background: #f3f3ff; border: 1px solid #b2d1ff; color: #006dba; -moz-box-shadow: 0 0 0.25em #b2d1ff; -webkit-box-shadow: 0 0 0.25em #b2d1ff; box-shadow: 0 0 0.25em #b2d1ff; } .errors { background: #fff3f3; border: 1px solid #ffaaaa; color: #cc0000; -moz-box-shadow: 0 0 0.25em #ff8888; -webkit-box-shadow: 0 0 0.25em #ff8888; box-shadow: 0 0 0.25em #ff8888; } .errors ul, .message { padding: 0; } .errors li { list-style: none; background: transparent url(../images/skin/exclamation.png) 0.5em 50% no-repeat; text-indent: 2.2em; } .message { background: transparent url(../images/skin/information.png) 0.5em 50% no-repeat; text-indent: 2.2em; } /* form fields with errors */ .error input, .error select, .error textarea { background: #fff3f3; border-color: #ffaaaa; color: #cc0000; } .error input:focus, .error select:focus, .error textarea:focus { -moz-box-shadow: 0 0 0.5em #ffaaaa; -webkit-box-shadow: 0 0 0.5em #ffaaaa; box-shadow: 0 0 0.5em #ffaaaa; } /* same effects for browsers that support HTML5 client-side validation (these have to be specified separately or IE will ignore the entire rule) */ input:invalid, select:invalid, textarea:invalid { background: #fff3f3; border-color: #ffaaaa; color: #cc0000; } input:invalid:focus, select:invalid:focus, textarea:invalid:focus { -moz-box-shadow: 0 0 0.5em #ffaaaa; -webkit-box-shadow: 0 0 0.5em #ffaaaa; box-shadow: 0 0 0.5em #ffaaaa; } /* TABLES */ table { border-top: 1px solid #DFDFDF; border-collapse: collapse; width: 100%; margin-bottom: 1em; } tr { border: 0; } tr > td:first-child, tr > th:first-child { padding-left: 1.25em; } tr > td:last-child, tr > th:last-child { padding-right: 1.25em; } td, th { line-height: 1.5em; padding: 0.5em 0.6em; text-align: left; vertical-align: top; } th { background-color: #efefef; background-image: -moz-linear-gradient(top, #ffffff, #eaeaea); background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #ffffff), color-stop(1, #eaeaea)); filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#eaeaea'); -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#eaeaea')"; color: #666666; font-weight: bold; line-height: 1.7em; padding: 0.2em 0.6em; } thead th { white-space: nowrap; } th a { display: block; text-decoration: none; } th a:link, th a:visited { color: #666666; } th a:hover, th a:focus { color: #333333; } th.sortable a { background-position: right; background-repeat: no-repeat; padding-right: 1.1em; } th.asc a { background-image: url(../images/skin/sorted_asc.gif); } th.desc a { background-image: url(../images/skin/sorted_desc.gif); } .odd { background: #f7f7f7; } .even { background: #ffffff; } th:hover, tr:hover { background: #E1F2B6; } /* PAGINATION */ .pagination { border-top: 0; margin: 0; padding: 0.3em 0.2em; text-align: center; -moz-box-shadow: 0 0 3px 1px #AAAAAA; -webkit-box-shadow: 0 0 3px 1px #AAAAAA; box-shadow: 0 0 3px 1px #AAAAAA; background-color: #EFEFEF; } .pagination a, .pagination .currentStep { color: #666666; display: inline-block; margin: 0 0.1em; padding: 0.25em 0.7em; text-decoration: none; -moz-border-radius: 0.3em; -webkit-border-radius: 0.3em; border-radius: 0.3em; } .pagination a:hover, .pagination a:focus, .pagination .currentStep { background-color: #999999; color: #ffffff; outline: none; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.8); } .no-borderradius .pagination a:hover, .no-borderradius .pagination a:focus, .no-borderradius .pagination .currentStep { background-color: transparent; color: #444444; text-decoration: underline; } /* ACTION BUTTONS */ .buttons { background-color: #efefef; overflow: hidden; padding: 0.3em; -moz-box-shadow: 0 0 3px 1px #aaaaaa; -webkit-box-shadow: 0 0 3px 1px #aaaaaa; box-shadow: 0 0 3px 1px #aaaaaa; margin: 0.1em 0 0 0; border: none; } .buttons input, .buttons a { background-color: transparent; border: 0; color: #666666; cursor: pointer; display: inline-block; margin: 0 0.25em 0; overflow: visible; padding: 0.25em 0.7em; text-decoration: none; -moz-border-radius: 0.3em; -webkit-border-radius: 0.3em; border-radius: 0.3em; } .buttons input:hover, .buttons input:focus, .buttons a:hover, .buttons a:focus { background-color: #999999; color: #ffffff; outline: none; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.8); -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } .no-borderradius .buttons input:hover, .no-borderradius .buttons input:focus, .no-borderradius .buttons a:hover, .no-borderradius .buttons a:focus { background-color: transparent; color: #444444; text-decoration: underline; } .buttons .delete, .buttons .edit, .buttons .save { background-position: 0.7em center; background-repeat: no-repeat; text-indent: 25px; } .ie6 .buttons input.delete, .ie6 .buttons input.edit, .ie6 .buttons input.save, .ie7 .buttons input.delete, .ie7 .buttons input.edit, .ie7 .buttons input.save { padding-left: 36px; } .buttons .delete { background-image: url(../images/skin/database_delete.png); } .buttons .edit { background-image: url(../images/skin/database_edit.png); } .buttons .save { background-image: url(../images/skin/database_save.png); } a.skip { position: absolute; left: -9999px; }
adioss/GrailsStarterTestSuite
grails-app/assets/stylesheets/main.css
CSS
apache-2.0
11,908
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.snapshots; /** * Represent shard snapshot status */ public class IndexShardSnapshotStatus { /** * Snapshot stage */ public static enum Stage { /** * Snapshot hasn't started yet */ INIT, /** * Index files are being copied */ STARTED, /** * Snapshot metadata is being written */ FINALIZE, /** * Snapshot completed successfully */ DONE, /** * Snapshot failed */ FAILURE } private Stage stage = Stage.INIT; private long startTime; private long time; private int numberOfFiles; private long totalSize; private long indexVersion; private boolean aborted; /** * Returns current snapshot stage * * @return current snapshot stage */ public Stage stage() { return this.stage; } /** * Sets new snapshot stage * * @param stage new snapshot stage */ public void updateStage(Stage stage) { this.stage = stage; } /** * Returns snapshot start time * * @return snapshot start time */ public long startTime() { return this.startTime; } /** * Sets snapshot start time * * @param startTime snapshot start time */ public void startTime(long startTime) { this.startTime = startTime; } /** * Returns snapshot processing time * * @return processing time */ public long time() { return this.time; } /** * Sets snapshot processing time * * @param time snapshot processing time */ public void time(long time) { this.time = time; } /** * Returns true if snapshot process was aborted * * @return true if snapshot process was aborted */ public boolean aborted() { return this.aborted; } /** * Marks snapshot as aborted */ public void abort() { this.aborted = true; } /** * Sets files stats * * @param numberOfFiles number of files in this snapshot * @param totalSize total size of files in this snapshot */ public void files(int numberOfFiles, long totalSize) { this.numberOfFiles = numberOfFiles; this.totalSize = totalSize; } /** * Number of files * * @return number of files */ public int numberOfFiles() { return numberOfFiles; } /** * Total snapshot size * * @return snapshot size */ public long totalSize() { return totalSize; } /** * Sets index version * * @param indexVersion index version */ public void indexVersion(long indexVersion) { this.indexVersion = indexVersion; } /** * Returns index version * * @return index version */ public long indexVersion() { return indexVersion; } }
alexksikes/elasticsearch
src/main/java/org/elasticsearch/index/snapshots/IndexShardSnapshotStatus.java
Java
apache-2.0
3,857
/* Copyright 2011-2013 Frederic Langlet Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. you may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kanzi.util; // A tree based collection of sorted integers allowing log n time for add/remove // and fast access to minimum and maximum values (usually constant time, else log n time). // Not thread safe. public final class IntBTree { private static final byte MAX_DIRTY = 1; private static final byte MIN_DIRTY = 2; private static final int LOG_NODE_BUFFER_SIZE = 4; private static final int NODE_BUFFER_SIZE = 1 << LOG_NODE_BUFFER_SIZE; private static final int MASK_NODE_BUFFER = NODE_BUFFER_SIZE - 1; private IntBTNode root; private int size; private byte flags; private int min; private int max; public IntBTree() { } public int size() { return this.size; } public void add(int val) { if (this.root == null) { this.root = new IntBTNode(val); this.min = val; this.max = val; } else { addValue(this.root, val); if (val < this.min) this.min = val; if (val > this.max) this.max = val; } this.size++; } // Add existing node private static void addNode(IntBTNode parent, IntBTNode node) { final int value = node.base; while (true) { if (value < parent.base) { if (parent.left == null) { parent.left = node; return; } parent = parent.left; } else if (value >= parent.base + NODE_BUFFER_SIZE) { if (parent.right == null) { parent.right = node; return; } parent = parent.right; } else break; } parent.counts[value&MASK_NODE_BUFFER]++; } // Same as addNode but node is created lazily private static void addValue(IntBTNode parent, int value) { while (parent != null) { if (value < parent.base) { if (parent.left == null) { parent.left = new IntBTNode(value); break; } parent = parent.left; } else if (value >= parent.base + NODE_BUFFER_SIZE) { if (parent.right == null) { parent.right = new IntBTNode(value); break; } parent = parent.right; } else { parent.counts[value&MASK_NODE_BUFFER]++; break; } } } // Return the number of matches public int contains(int value) { IntBTNode res = findNode(this.root, value); return (res == null) ? 0 : res.counts[value&MASK_NODE_BUFFER]; } private static IntBTNode findNode(IntBTNode current, int value) { while (current != null) { if (value < current.base) current = current.left; else if (value >= current.base + NODE_BUFFER_SIZE) current = current.right; else break; } return current; } public boolean remove(int value) { if (this.root == null) return false; if (this.removeNode(value) == null) return false; this.size--; // Force recomputation of cached fields if (this.min == value) this.flags |= MIN_DIRTY; if (this.max == value) this.flags |= MAX_DIRTY; return true; } private IntBTNode removeNode(int value) { IntBTNode current = this.root; IntBTNode prev = null; while (true) { if (value < current.base) { if (current.left == null) return null; prev = current; current = current.left; } else if (value >= current.base + NODE_BUFFER_SIZE) { if (current.right == null) return null; prev = current; current = current.right; } else break; } // Found target current.counts[value&MASK_NODE_BUFFER]--; if (current.counts[value&MASK_NODE_BUFFER] != 0) return current; for (int i=0; i<NODE_BUFFER_SIZE; i++) { if (current.counts[i] != 0) return current; } if (current == this.root) { // First, try easy substitutions of root if (current.right == null) this.root = current.left; else if (current.left == null) this.root = current.right; else if ((value & 1) == 0) // random choice or left or right { this.root = current.right; // Re-insert left branch addNode(this.root, current.left); } else { this.root = current.left; // Re-insert right branch addNode(this.root, current.right); } } if (prev != null) { // Remove current node from previous node if (prev.right == current) { if (current.left != null) { prev.right = current.left; // Re-insert right branch if (current.right != null) addNode(prev, current.right); } else prev.right = current.right; } else { prev.left = current.left; // Re-insert right branch if (current.right != null) addNode(prev, current.right); } } return current; } public int rank(int value) { if (this.root == null) return -1; if (this.min() == value) return 0; int rank = findRank(this.root, value, 0); return (rank == this.size) ? -1 : -rank; } private static int findRank(IntBTNode current, int value, int rank) { if ((rank >= 0) && (current.left != null)) rank = findRank(current.left, value, rank); for (int i=0; i<NODE_BUFFER_SIZE; i++) { if (value == current.base + i) return -rank; if (rank >= 0) rank += current.counts[i]; } if ((rank >= 0) && (current.right != null)) rank = findRank(current.right, value, rank); return rank; } public int[] scan(Callback cb, boolean reverse) { if ((cb == null) || (this.root == null)) return null; int[] res = new int[this.size]; scanAndCall(this.root, res, 0, cb, reverse); // visitor pattern return res; } private static int scanAndCall(IntBTNode current, int[] array, int index, Callback cb, boolean reverse) { if (reverse == false) { if (current.left != null) index = scanAndCall(current.left, array, index, cb, false); index = cb.call(current, array, index, reverse); if (current.right != null) index = scanAndCall(current.right, array, index, cb, false); } else { if (current.right != null) index = scanAndCall(current.right, array, index, cb, true); index = cb.call(current, array, index, reverse); if (current.left != null) index = scanAndCall(current.left, array, index, cb, true); } return index; } public void clear() { this.root = null; this.size = 0; } public int min() { if (this.root == null) throw new IllegalStateException("Tree is empty"); if ((this.flags & MIN_DIRTY) != 0) { // Dynamically scan tree to leftmost position IntBTNode node = this.root; while (node.left != null) node = node.left; for (int i=0; i<NODE_BUFFER_SIZE; i++) { if (node.counts[i] > 0) { this.min = node.base + i; break; } } this.flags &= ~MIN_DIRTY; } return this.min; } public int max() { if (this.root == null) throw new IllegalStateException("Tree is empty"); if ((this.flags & MAX_DIRTY) != 0) { // Dynamically scan tree to rightmost position IntBTNode node = this.root; while (node.right != null) node = node.right; for (int i=NODE_BUFFER_SIZE-1; i>=0; i--) { if (node.counts[i] > 0) { this.max = node.base + i; break; } } this.flags &= ~MAX_DIRTY; } return this.max; } public int[] toArray(int[] array) { if (this.root == null) return new int[0]; if ((array == null) || (array.length < this.size)) array = new int[this.size]; final int[] res = array; Callback cb = new Callback() { @Override public int call(IntBTNode node, int[] values, int idx, boolean reverse) { return node.values(values, idx, reverse); } }; scanAndCall(this.root, res, 0, cb, false); return res; } @Override public String toString() { if (this.size() == 0) return "[]"; int[] res = new int[this.size()]; Callback cb = new Callback() { @Override public int call(IntBTNode node, int[] values, int idx, boolean reverse) { return node.values(values, idx, reverse); } }; scanAndCall(this.root, res, 0, cb, false); StringBuilder sb = new StringBuilder(res.length*5); sb.append('['); if (res.length > 0) { sb.append(res[0]); for (int i=1; i<res.length; i++) sb.append(',').append(res[i]); } sb.append(']'); return sb.toString(); } // Interface to implement visitor pattern. Must return the node value public interface Callback { public int call(IntBTNode node, int[] values, int idx, boolean reverse); } // A node containing a range of integers public static class IntBTNode { protected int base; // range base protected int[] counts; protected IntBTNode left; protected IntBTNode right; IntBTNode(int val) { this.base = val & -NODE_BUFFER_SIZE; this.counts = new int[NODE_BUFFER_SIZE]; this.counts[val&MASK_NODE_BUFFER]++; } public int values(int[] values, int idx, boolean reverse) { if (reverse == true) { for (int i=NODE_BUFFER_SIZE-1; i>=0; i--) { for (int j=this.counts[i]; j>0; j--) values[idx++] = this.base + i; } } else { for (int i=0; i<NODE_BUFFER_SIZE; i++) { for (int j=this.counts[i]; j>0; j--) values[idx++] = this.base + i; } } return idx; } } }
Sputuks3/kanzi
java/src/kanzi/util/IntBTree.java
Java
apache-2.0
12,295
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.userSkeletons; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileSystemItem; import com.jetbrains.python.codeInsight.PyCustomMember; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyFile; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.types.PyModuleMembersProvider; import com.jetbrains.python.psi.types.TypeEvalContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author vlan */ public class PyUserSkeletonsModuleMembersProvider extends PyModuleMembersProvider { @Nullable @Override public PsiElement resolveMember(@NotNull PyFile module, @NotNull String name, @NotNull PyResolveContext resolveContext) { final PyFile moduleSkeleton = PyUserSkeletonsUtil.getUserSkeleton(module); if (moduleSkeleton != null) { return moduleSkeleton.getElementNamed(name); } return null; } @Override protected Collection<PyCustomMember> getMembersByQName(PyFile module, String qName) { // This method will be removed in 2018.2 return getMembersByQName(module, qName, TypeEvalContext.codeInsightFallback(module.getProject())); } @Override @NotNull protected Collection<PyCustomMember> getMembersByQName(@NotNull PyFile module, @NotNull String qName, @NotNull TypeEvalContext context) { final PyFile moduleSkeleton = PyUserSkeletonsUtil.getUserSkeletonForModuleQName(qName, module); if (moduleSkeleton != null) { final List<PyCustomMember> results = new ArrayList<>(); for (PyElement element : moduleSkeleton.iterateNames()) { if (element instanceof PsiFileSystemItem) { continue; } final String name = element.getName(); if (name != null) { results.add(new PyCustomMember(name, element)); } } return results; } return Collections.emptyList(); } }
ThiagoGarciaAlves/intellij-community
python/src/com/jetbrains/python/codeInsight/userSkeletons/PyUserSkeletonsModuleMembersProvider.java
Java
apache-2.0
2,215
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Resources; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public partial class DiagnosticLocalizationTests { [Fact, WorkItem(1006, "https://github.com/dotnet/roslyn/issues/1006")] public void TestDiagnosticLocalization() { var resourceManager = GetTestResourceManagerInstance(); var arCulture = CultureInfo.CreateSpecificCulture("ar-SA"); var defaultCultureResourceSet = resourceManager.GetResourceSet(CustomResourceManager.DefaultCulture, false, false); var arResourceSet = resourceManager.GetResourceSet(arCulture, false, false); var nameOfResource1 = @"Resource1"; var nameOfResource2 = @"Resource2"; var nameOfResource3 = @"Resource3"; var fixedTitle = defaultCultureResourceSet.GetString(nameOfResource1); var fixedMessageFormat = defaultCultureResourceSet.GetString(nameOfResource2); var fixedDescription = defaultCultureResourceSet.GetString(nameOfResource3); var localizedTitle = arResourceSet.GetString(nameOfResource1); var localizedMessageFormat = arResourceSet.GetString(nameOfResource2); var localizedDescription = arResourceSet.GetString(nameOfResource3); // Test descriptor localization. // Test non-localizable title, description and message. var descriptor = new DiagnosticDescriptor( "Id", fixedTitle, fixedMessageFormat, "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: fixedDescription); Assert.Equal(fixedTitle, descriptor.Title.ToString(arCulture)); Assert.Equal(fixedMessageFormat, descriptor.MessageFormat.ToString(arCulture)); Assert.Equal(fixedDescription, descriptor.Description.ToString(arCulture)); // Test localizable title, description and message. var localizableTitle = new LocalizableResourceString(nameOfResource1, resourceManager, typeof(CustomResourceManager)); var localizableMessageFormat = new LocalizableResourceString(nameOfResource2, resourceManager, typeof(CustomResourceManager)); var localizableDescription = new LocalizableResourceString(nameOfResource3, resourceManager, typeof(CustomResourceManager)); descriptor = new DiagnosticDescriptor( "Id", localizableTitle, localizableMessageFormat, "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: localizableDescription); if (EnsureEnglishUICulture.PreferredOrNull == null) { Assert.Equal<string>(fixedTitle, descriptor.Title.ToString()); Assert.Equal<string>(fixedMessageFormat, descriptor.MessageFormat.ToString()); Assert.Equal<string>(fixedDescription, descriptor.Description.ToString()); } Assert.Equal<string>(fixedTitle, descriptor.Title.ToString(CustomResourceManager.DefaultCulture)); Assert.Equal<string>(fixedMessageFormat, descriptor.MessageFormat.ToString(CustomResourceManager.DefaultCulture)); Assert.Equal<string>(fixedDescription, descriptor.Description.ToString(CustomResourceManager.DefaultCulture)); Assert.Equal(localizedTitle, descriptor.Title.ToString(arCulture)); Assert.Equal(localizedMessageFormat, descriptor.MessageFormat.ToString(arCulture)); Assert.Equal(localizedDescription, descriptor.Description.ToString(arCulture)); // Test diagnostic localization. var localizableDiagnostic = Diagnostic.Create(descriptor, Location.None); if (EnsureEnglishUICulture.PreferredOrNull == null) { // Test non-localized title, description and message. Assert.Equal(fixedTitle, localizableDiagnostic.Descriptor.Title.ToString()); Assert.Equal(fixedMessageFormat, localizableDiagnostic.GetMessage()); Assert.Equal(fixedDescription, localizableDiagnostic.Descriptor.Description.ToString()); } Assert.Equal(fixedTitle, localizableDiagnostic.Descriptor.Title.ToString(CustomResourceManager.DefaultCulture)); Assert.Equal(fixedMessageFormat, localizableDiagnostic.GetMessage(CustomResourceManager.DefaultCulture)); Assert.Equal(fixedDescription, localizableDiagnostic.Descriptor.Description.ToString(CustomResourceManager.DefaultCulture)); // Test localized title, description and message. Assert.Equal(localizedTitle, localizableDiagnostic.Descriptor.Title.ToString(arCulture)); Assert.Equal(localizedMessageFormat, localizableDiagnostic.GetMessage(arCulture)); Assert.Equal(localizedDescription, localizableDiagnostic.Descriptor.Description.ToString(arCulture)); // Test argument formatting for localized string var nameOfResourceWithArguments = @"ResourceWithArguments"; var argument = "formatted"; var localizableResource = new LocalizableResourceString(nameOfResourceWithArguments, resourceManager, typeof(CustomResourceManager), argument); // Verify without culture var defaultCultureLocalizedStringWithArguments = defaultCultureResourceSet.GetString(nameOfResourceWithArguments); var expected = string.Format(defaultCultureLocalizedStringWithArguments, argument); if (EnsureEnglishUICulture.PreferredOrNull == null) { Assert.Equal(expected, localizableResource.ToString()); } Assert.Equal(expected, localizableResource.ToString(CustomResourceManager.DefaultCulture)); // Verify with loc culture var arLocalizedStringWithArguments = arResourceSet.GetString(nameOfResourceWithArguments); expected = string.Format(arLocalizedStringWithArguments, argument); Assert.Equal(expected, localizableResource.ToString(arCulture)); } private static CustomResourceManager GetTestResourceManagerInstance() { var defaultCultureResources = new Dictionary<string, string>() { { "Resource1", "My Resource 1 DefaultCulture string" }, { "Resource2", "My Resource 2 DefaultCulture string" }, { "Resource3", "My Resource 3 DefaultCulture string" }, { "ResourceWithArguments", "My Resource DefaultCulture string {0}" } }; var arResources = new Dictionary<string, string>() { { "Resource1", "ARABIC string for My Resource 1" }, { "Resource2", "ARABIC string for My Resource 2" }, { "Resource3", "ARABIC string for My Resource 3" }, { "ResourceWithArguments", "{0} ARABIC string for My Resource" } }; var resourceSetMap = new Dictionary<string, Dictionary<string, string>>() { { CustomResourceManager.DefaultCulture.Name, defaultCultureResources }, { "ar-SA", arResources } }; return new CustomResourceManager(resourceSetMap); } private class CustomResourceManager : ResourceManager { private readonly Dictionary<string, CustomResourceSet> _resourceSetMap; public CustomResourceManager(Dictionary<string, CustomResourceSet> resourceSetMap) { _resourceSetMap = resourceSetMap; } public CustomResourceManager(Dictionary<string, Dictionary<string, string>> resourceSetMap) { _resourceSetMap = new Dictionary<string, CustomResourceSet>(); foreach (var kvp in resourceSetMap) { var resourceSet = new CustomResourceSet(kvp.Value); _resourceSetMap.Add(kvp.Key, resourceSet); } } public static CultureInfo DefaultCulture => CultureInfo.CurrentUICulture; public void VerifyResourceValue(string resourceName, string cultureName, string expectedResourceValue) { var actual = this.GetString(resourceName, CultureInfo.CreateSpecificCulture(cultureName)); Assert.Equal(expectedResourceValue, actual); } public override string GetString(string name, CultureInfo culture) { return GetResourceSet(culture, false, false).GetString(name); } public override ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { return _resourceSetMap[culture.Name]; } public override string GetString(string name) { return GetString(name, CultureInfo.InvariantCulture); } public override object GetObject(string name) { return GetString(name); } public override object GetObject(string name, CultureInfo culture) { return GetString(name, culture); } public class CustomResourceSet : ResourceSet { private readonly Dictionary<string, string> _resourcesMap; public CustomResourceSet(Dictionary<string, string> resourcesMap) { _resourcesMap = resourcesMap; } public override string GetString(string name) { return _resourcesMap[name]; } public override string GetString(string name, bool ignoreCase) { throw new NotImplementedException(); } public override object GetObject(string name) { return GetString(name); } public override object GetObject(string name, bool ignoreCase) { throw new NotImplementedException(); } } } [Fact, WorkItem(887)] public void TestDescriptorIsExceptionSafe() { // Test descriptor with LocalizableResourceString fields that can throw. var descriptor1 = GetDescriptorWithLocalizableResourceStringsThatThrow(); TestDescriptorIsExceptionSafeCore(descriptor1); // Test descriptor with Custom implemented LocalizableString fields that can throw. var descriptor2 = GetDescriptorWithCustomLocalizableStringsThatThrow(); TestDescriptorIsExceptionSafeCore(descriptor2); // Also verify exceptions from Equals and GetHashCode don't go unhandled. var unused1 = descriptor2.Title.GetHashCode(); var unused2 = descriptor2.Equals(descriptor1); } private static void TestDescriptorIsExceptionSafeCore(DiagnosticDescriptor descriptor) { var localizableTitle = descriptor.Title; var localizableMessage = descriptor.MessageFormat; var localizableDescription = descriptor.Description; // Verify exceptions from LocalizableResourceString don't go unhandled. var title = localizableTitle.ToString(); var message = localizableMessage.ToString(); var description = localizableDescription.ToString(); // Verify exceptions from LocalizableResourceString are raised if OnException is set. var exceptions = new List<Exception>(); var handler = new EventHandler<Exception>((sender, ex) => exceptions.Add(ex)); localizableTitle.OnException += handler; localizableMessage.OnException += handler; localizableDescription.OnException += handler; // Access and evaluate localizable fields. var unused1 = localizableTitle.ToString(); var unused2 = localizableMessage.ToString(); var unused3 = localizableDescription.ToString(); Assert.Equal(3, exceptions.Count); // Verify DiagnosticAnalyzer.SupportedDiagnostics is also exception safe. var analyzer = new MyAnalyzer(descriptor); var exceptionDiagnostics = new List<Diagnostic>(); Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = (ex, a, diag) => exceptionDiagnostics.Add(diag); var analyzerExecutor = AnalyzerExecutor.CreateForSupportedDiagnostics(onAnalyzerException, AnalyzerManager.Instance, CancellationToken.None); var descriptors = AnalyzerManager.Instance.GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor); Assert.Equal(1, descriptors.Length); Assert.Equal(descriptor.Id, descriptors[0].Id); // Access and evaluate localizable fields. unused1 = descriptors[0].Title.ToString(); unused2 = descriptors[0].MessageFormat.ToString(); unused3 = descriptors[0].Description.ToString(); // Verify logged analyzer exception diagnostics. Assert.Equal(3, exceptionDiagnostics.Count); Assert.True(exceptionDiagnostics.TrueForAll(AnalyzerExecutor.IsAnalyzerExceptionDiagnostic)); } private static DiagnosticDescriptor GetDescriptorWithLocalizableResourceStringsThatThrow() { var resourceManager = GetTestResourceManagerInstance(); // Test localizable title that throws. var localizableTitle = new LocalizableResourceString("NonExistentTitleResourceName", resourceManager, typeof(CustomResourceManager)); var localizableMessage = new LocalizableResourceString("NonExistentMessageResourceName", resourceManager, typeof(CustomResourceManager)); var localizableDescription = new LocalizableResourceString("NonExistentDescriptionResourceName", resourceManager, typeof(CustomResourceManager)); return new DiagnosticDescriptor( "Id", localizableTitle, localizableMessage, "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: localizableDescription); } private static DiagnosticDescriptor GetDescriptorWithCustomLocalizableStringsThatThrow() { // Test localizable title that throws. var localizableTitle = new ThrowingLocalizableString(); var localizableMessage = new ThrowingLocalizableString(); var localizableDescription = new ThrowingLocalizableString(); return new DiagnosticDescriptor( "Id", localizableTitle, localizableMessage, "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: localizableDescription); } private class MyAnalyzer : DiagnosticAnalyzer { private readonly DiagnosticDescriptor _descriptor; public MyAnalyzer(DiagnosticDescriptor descriptor) { _descriptor = descriptor; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) { } } private class ThrowingLocalizableString : LocalizableString { protected override bool AreEqual(object other) { throw new NotImplementedException(); } protected override int GetHash() { throw new NotImplementedException(); } protected override string GetText(IFormatProvider formatProvider) { throw new NotImplementedException(); } } } }
paladique/roslyn
src/Compilers/Core/CodeAnalysisTest/Diagnostics/DiagnosticLocalizationTests.cs
C#
apache-2.0
16,869
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.test.api.mgmt; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.UUID; import org.activiti.engine.impl.cmd.CancelJobsCmd; import org.activiti.engine.impl.interceptor.Command; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.interceptor.CommandExecutor; import org.activiti.engine.impl.persistence.entity.JobEntity; import org.activiti.engine.impl.persistence.entity.JobEntityManager; import org.activiti.engine.impl.persistence.entity.TimerJobEntity; import org.activiti.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.common.api.FlowableException; import org.flowable.engine.common.api.FlowableIllegalArgumentException; import org.flowable.engine.common.runtime.Clock; import org.flowable.engine.repository.DeploymentProperties; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.Deployment; import org.flowable.job.api.Job; import org.flowable.job.api.TimerJobQuery; /** * @author Joram Barrez * @author Tijs Rademakers */ public class JobQueryTest extends PluggableFlowableTestCase { private String deploymentId; private String messageId; private CommandExecutor commandExecutor; private JobEntity jobEntity; private Date testStartTime; private Date timerOneFireTime; private Date timerTwoFireTime; private Date timerThreeFireTime; private String processInstanceIdOne; private String processInstanceIdTwo; private String processInstanceIdThree; private static final long ONE_HOUR = 60L * 60L * 1000L; private static final long ONE_SECOND = 1000L; private static final String EXCEPTION_MESSAGE = "problem evaluating script: javax.script.ScriptException: java.lang.RuntimeException: This is an exception thrown from scriptTask"; /** * Setup will create - 3 process instances, each with one timer, each firing at t1/t2/t3 + 1 hour (see process) - 1 message */ protected void setUp() throws Exception { super.setUp(); Clock clock = processEngineConfiguration.getClock(); this.commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor(); deploymentId = repositoryService.createDeployment() .addClasspathResource("org/activiti/engine/test/api/mgmt/timerOnTask.bpmn20.xml") .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE) .deploy() .getId(); // Create proc inst that has timer that will fire on t1 + 1 hour Calendar startTime = Calendar.getInstance(); startTime.set(Calendar.MILLISECOND, 0); Date t1 = startTime.getTime(); clock.setCurrentTime(t1); processEngineConfiguration.setClock(clock); processInstanceIdOne = runtimeService.startProcessInstanceByKey("timerOnTask").getId(); testStartTime = t1; timerOneFireTime = new Date(t1.getTime() + ONE_HOUR); // Create proc inst that has timer that will fire on t2 + 1 hour startTime.add(Calendar.HOUR_OF_DAY, 1); Date t2 = startTime.getTime(); // t2 = t1 + 1 hour clock.setCurrentTime(t2); processEngineConfiguration.setClock(clock); processInstanceIdTwo = runtimeService.startProcessInstanceByKey("timerOnTask").getId(); timerTwoFireTime = new Date(t2.getTime() + ONE_HOUR); // Create proc inst that has timer that will fire on t3 + 1 hour startTime.add(Calendar.HOUR_OF_DAY, 1); Date t3 = startTime.getTime(); // t3 = t2 + 1 hour clock.setCurrentTime(t3); processEngineConfiguration.setClock(clock); processInstanceIdThree = runtimeService.startProcessInstanceByKey("timerOnTask").getId(); timerThreeFireTime = new Date(t3.getTime() + ONE_HOUR); } @Override protected void tearDown() throws Exception { repositoryService.deleteDeployment(deploymentId, true); commandExecutor.execute(new CancelJobsCmd(messageId)); processEngineConfiguration.resetClock(); super.tearDown(); } public void testQueryByNoCriteria() { TimerJobQuery query = managementService.createTimerJobQuery(); verifyQueryResults(query, 3); } public void testQueryByProcessInstanceId() { TimerJobQuery query = managementService.createTimerJobQuery().processInstanceId(processInstanceIdOne); verifyQueryResults(query, 1); } public void testQueryByInvalidProcessInstanceId() { TimerJobQuery query = managementService.createTimerJobQuery().processInstanceId("invalid"); verifyQueryResults(query, 0); try { managementService.createJobQuery().processInstanceId(null); fail(); } catch (FlowableIllegalArgumentException e) { } } public void testQueryByExecutionId() { Job job = managementService.createTimerJobQuery().processInstanceId(processInstanceIdOne).singleResult(); TimerJobQuery query = managementService.createTimerJobQuery().executionId(job.getExecutionId()); assertEquals(query.singleResult().getId(), job.getId()); verifyQueryResults(query, 1); } public void testQueryByInvalidExecutionId() { TimerJobQuery query = managementService.createTimerJobQuery().executionId("invalid"); verifyQueryResults(query, 0); try { managementService.createTimerJobQuery().executionId(null).list(); fail(); } catch (FlowableIllegalArgumentException e) { } } public void testQueryByRetriesLeft() { TimerJobQuery query = managementService.createTimerJobQuery(); verifyQueryResults(query, 3); final Job job = managementService.createTimerJobQuery().processInstanceId(processInstanceIdOne).singleResult(); managementService.setTimerJobRetries(job.getId(), 0); managementService.moveJobToDeadLetterJob(job.getId()); // Re-running the query should give only 3 jobs now, since one job has retries=0 verifyQueryResults(query, 2); } public void testQueryByExecutable() { processEngineConfiguration.getClock().setCurrentTime(new Date(timerThreeFireTime.getTime() + ONE_SECOND)); // all jobs should be executable at t3 + 1hour.1second TimerJobQuery query = managementService.createTimerJobQuery().executable(); verifyQueryResults(query, 3); // Setting retries of one job to 0, makes it non-executable final Job job = managementService.createTimerJobQuery().processInstanceId(processInstanceIdOne).singleResult(); managementService.setTimerJobRetries(job.getId(), 0); managementService.moveJobToDeadLetterJob(job.getId()); verifyQueryResults(query, 2); // Setting the clock before the start of the process instance, makes none of the jobs executable processEngineConfiguration.getClock().setCurrentTime(testStartTime); verifyQueryResults(query, 0); } public void testQueryByOnlyTimers() { TimerJobQuery query = managementService.createTimerJobQuery().timers(); verifyQueryResults(query, 3); } public void testInvalidOnlyTimersUsage() { try { managementService.createJobQuery().timers().messages().list(); fail(); } catch (FlowableIllegalArgumentException e) { assertTextPresent("Cannot combine onlyTimers() with onlyMessages() in the same query", e.getMessage()); } } public void testQueryByDuedateLowerThan() { TimerJobQuery query = managementService.createTimerJobQuery().duedateLowerThan(testStartTime); verifyQueryResults(query, 0); query = managementService.createTimerJobQuery().duedateLowerThan(new Date(timerOneFireTime.getTime() + ONE_SECOND)); verifyQueryResults(query, 1); query = managementService.createTimerJobQuery().duedateLowerThan(new Date(timerTwoFireTime.getTime() + ONE_SECOND)); verifyQueryResults(query, 2); query = managementService.createTimerJobQuery().duedateLowerThan(new Date(timerThreeFireTime.getTime() + ONE_SECOND)); verifyQueryResults(query, 3); } public void testQueryByDuedateHigherThan() { TimerJobQuery query = managementService.createTimerJobQuery().duedateHigherThan(testStartTime); verifyQueryResults(query, 3); query = managementService.createTimerJobQuery().duedateHigherThan(timerOneFireTime); verifyQueryResults(query, 2); query = managementService.createTimerJobQuery().duedateHigherThan(timerTwoFireTime); verifyQueryResults(query, 1); query = managementService.createTimerJobQuery().duedateHigherThan(timerThreeFireTime); verifyQueryResults(query, 0); } @Deployment(resources = { "org/activiti/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml" }) public void testQueryByException() { TimerJobQuery query = managementService.createTimerJobQuery().withException(); verifyQueryResults(query, 0); ProcessInstance processInstance = startProcessInstanceWithFailingJob(); query = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).withException(); verifyFailedJob(query, processInstance); } @Deployment(resources = { "org/activiti/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml" }) public void testQueryByExceptionMessage() { TimerJobQuery query = managementService.createTimerJobQuery().exceptionMessage(EXCEPTION_MESSAGE); verifyQueryResults(query, 0); ProcessInstance processInstance = startProcessInstanceWithFailingJob(); query = managementService.createTimerJobQuery().exceptionMessage(EXCEPTION_MESSAGE); verifyFailedJob(query, processInstance); } @Deployment(resources = { "org/activiti/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml" }) public void testQueryByExceptionMessageEmpty() { TimerJobQuery query = managementService.createTimerJobQuery().exceptionMessage(""); verifyQueryResults(query, 0); startProcessInstanceWithFailingJob(); query = managementService.createTimerJobQuery().exceptionMessage(""); verifyQueryResults(query, 0); } public void testQueryByExceptionMessageNull() { try { managementService.createJobQuery().exceptionMessage(null); fail("ActivitiException expected"); } catch (FlowableIllegalArgumentException e) { assertEquals("Provided exception message is null", e.getMessage()); } } public void testJobQueryWithExceptions() throws Throwable { createJobWithoutExceptionMsg(); Job job = managementService.createJobQuery().jobId(jobEntity.getId()).singleResult(); assertNotNull(job); List<Job> list = managementService.createJobQuery().withException().list(); assertEquals(1, list.size()); deleteJobInDatabase(); createJobWithoutExceptionStacktrace(); job = managementService.createJobQuery().jobId(jobEntity.getId()).singleResult(); assertNotNull(job); list = managementService.createJobQuery().withException().list(); assertEquals(1, list.size()); deleteJobInDatabase(); } // sorting ////////////////////////////////////////// public void testQuerySorting() { // asc assertEquals(3, managementService.createTimerJobQuery().orderByJobId().asc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByJobDuedate().asc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByExecutionId().asc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByProcessInstanceId().asc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByJobRetries().asc().count()); // desc assertEquals(3, managementService.createTimerJobQuery().orderByJobId().desc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByJobDuedate().desc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByExecutionId().desc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByProcessInstanceId().desc().count()); assertEquals(3, managementService.createTimerJobQuery().orderByJobRetries().desc().count()); // sorting on multiple fields final Job job = managementService.createTimerJobQuery().processInstanceId(processInstanceIdTwo).singleResult(); managementService.setTimerJobRetries(job.getId(), 2); processEngineConfiguration.getClock().setCurrentTime(new Date(timerThreeFireTime.getTime() + ONE_SECOND)); // make sure all timers can fire TimerJobQuery query = managementService.createTimerJobQuery() .timers() .orderByJobRetries() .asc() .orderByJobDuedate() .desc(); List<Job> jobs = query.list(); assertEquals(3, jobs.size()); assertEquals(2, jobs.get(0).getRetries()); assertEquals(3, jobs.get(1).getRetries()); assertEquals(3, jobs.get(2).getRetries()); assertEquals(processInstanceIdTwo, jobs.get(0).getProcessInstanceId()); assertEquals(processInstanceIdThree, jobs.get(1).getProcessInstanceId()); assertEquals(processInstanceIdOne, jobs.get(2).getProcessInstanceId()); } public void testQueryInvalidSortingUsage() { try { managementService.createJobQuery().orderByJobId().list(); fail(); } catch (FlowableIllegalArgumentException e) { assertTextPresent("call asc() or desc() after using orderByXX()", e.getMessage()); } try { managementService.createJobQuery().asc(); fail(); } catch (FlowableIllegalArgumentException e) { assertTextPresent("You should call any of the orderBy methods first before specifying a direction", e.getMessage()); } } // helper //////////////////////////////////////////////////////////// private void setRetries(final String processInstanceId, final int retries) { final Job job = managementService.createTimerJobQuery().processInstanceId(processInstanceId).singleResult(); commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { TimerJobEntity timer = commandContext.getDbSqlSession().selectById(TimerJobEntity.class, job.getId()); timer.setRetries(retries); return null; } }); } private ProcessInstance startProcessInstanceWithFailingJob() { // start a process with a failing job ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution"); // The execution is waiting in the first usertask. This contains a boundary // timer event which we will execute manual for testing purposes. Job timerJob = managementService.createTimerJobQuery() .processInstanceId(processInstance.getId()) .singleResult(); assertNotNull("No job found for process instance", timerJob); try { managementService.moveTimerToExecutableJob(timerJob.getId()); managementService.executeJob(timerJob.getId()); fail("RuntimeException from within the script task expected"); } catch (RuntimeException re) { assertTextPresent(EXCEPTION_MESSAGE, re.getCause().getMessage()); } return processInstance; } private void verifyFailedJob(TimerJobQuery query, ProcessInstance processInstance) { verifyQueryResults(query, 1); Job failedJob = query.singleResult(); assertNotNull(failedJob); assertEquals(processInstance.getId(), failedJob.getProcessInstanceId()); assertNotNull(failedJob.getExceptionMessage()); assertTextPresent(EXCEPTION_MESSAGE, failedJob.getExceptionMessage()); } private void verifyQueryResults(TimerJobQuery query, int countExpected) { assertEquals(countExpected, query.list().size()); assertEquals(countExpected, query.count()); if (countExpected == 1) { assertNotNull(query.singleResult()); } else if (countExpected > 1) { verifySingleResultFails(query); } else if (countExpected == 0) { assertNull(query.singleResult()); } } private void verifySingleResultFails(TimerJobQuery query) { try { query.singleResult(); fail(); } catch (FlowableException e) { } } private void createJobWithoutExceptionMsg() { CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor(); commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { JobEntityManager jobManager = commandContext.getJobEntityManager(); jobEntity = new JobEntity(); jobEntity.setJobType(Job.JOB_TYPE_MESSAGE); jobEntity.setRevision(1); jobEntity.setLockOwner(UUID.randomUUID().toString()); jobEntity.setRetries(0); StringWriter stringWriter = new StringWriter(); NullPointerException exception = new NullPointerException(); exception.printStackTrace(new PrintWriter(stringWriter)); jobEntity.setExceptionStacktrace(stringWriter.toString()); jobManager.insert(jobEntity); assertNotNull(jobEntity.getId()); return null; } }); } private void createJobWithoutExceptionStacktrace() { CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor(); commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { JobEntityManager jobManager = commandContext.getJobEntityManager(); jobEntity = new JobEntity(); jobEntity.setJobType(Job.JOB_TYPE_MESSAGE); jobEntity.setRevision(1); jobEntity.setLockOwner(UUID.randomUUID().toString()); jobEntity.setRetries(0); jobEntity.setExceptionMessage("I'm supposed to fail"); jobManager.insert(jobEntity); assertNotNull(jobEntity.getId()); return null; } }); } private void deleteJobInDatabase() { CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor(); commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { jobEntity.delete(); return null; } }); } }
zwets/flowable-engine
modules/flowable5-test/src/test/java/org/activiti/engine/test/api/mgmt/JobQueryTest.java
Java
apache-2.0
20,129
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.query.aggregation.last; import org.apache.druid.collections.SerializablePair; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.Pair; import org.apache.druid.query.aggregation.Aggregator; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.BufferAggregator; import org.apache.druid.query.aggregation.TestFloatColumnSelector; import org.apache.druid.query.aggregation.TestLongColumnSelector; import org.apache.druid.query.aggregation.TestObjectColumnSelector; import org.apache.druid.segment.ColumnSelectorFactory; import org.apache.druid.segment.column.ColumnHolder; import org.apache.druid.testing.InitializedNullHandlingTest; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.nio.ByteBuffer; import java.util.Comparator; public class FloatLastAggregationTest extends InitializedNullHandlingTest { private FloatLastAggregatorFactory floatLastAggregatorFactory; private FloatLastAggregatorFactory combiningAggFactory; private ColumnSelectorFactory colSelectorFactory; private TestLongColumnSelector timeSelector; private TestLongColumnSelector customTimeSelector; private TestFloatColumnSelector valueSelector; private TestObjectColumnSelector objectSelector; private float[] floats = {1.1897f, 0.001f, 86.23f, 166.228f}; private long[] times = {8224, 6879, 2436, 7888}; private long[] customTimes = {1, 4, 3, 2}; private SerializablePair[] pairs = { new SerializablePair<>(52782L, 134.3f), new SerializablePair<>(65492L, 1232.212f), new SerializablePair<>(69134L, 18.1233f), new SerializablePair<>(11111L, 233.5232f) }; @Before public void setup() { floatLastAggregatorFactory = new FloatLastAggregatorFactory("billy", "nilly", null); combiningAggFactory = (FloatLastAggregatorFactory) floatLastAggregatorFactory.getCombiningFactory(); timeSelector = new TestLongColumnSelector(times); customTimeSelector = new TestLongColumnSelector(customTimes); valueSelector = new TestFloatColumnSelector(floats); objectSelector = new TestObjectColumnSelector<>(pairs); colSelectorFactory = EasyMock.createMock(ColumnSelectorFactory.class); EasyMock.expect(colSelectorFactory.makeColumnValueSelector(ColumnHolder.TIME_COLUMN_NAME)).andReturn(timeSelector); EasyMock.expect(colSelectorFactory.makeColumnValueSelector("customTime")).andReturn(customTimeSelector); EasyMock.expect(colSelectorFactory.makeColumnValueSelector("nilly")).andReturn(valueSelector); EasyMock.expect(colSelectorFactory.makeColumnValueSelector("billy")).andReturn(objectSelector); EasyMock.replay(colSelectorFactory); } @Test public void testFloatLastAggregator() { Aggregator agg = floatLastAggregatorFactory.factorize(colSelectorFactory); aggregate(agg); aggregate(agg); aggregate(agg); aggregate(agg); Pair<Long, Float> result = (Pair<Long, Float>) agg.get(); Assert.assertEquals(times[0], result.lhs.longValue()); Assert.assertEquals(floats[0], result.rhs, 0.0001); Assert.assertEquals((long) floats[0], agg.getLong()); Assert.assertEquals(floats[0], agg.getFloat(), 0.0001); } @Test public void testFloatLastAggregatorWithTimeColumn() { Aggregator agg = new FloatLastAggregatorFactory("billy", "nilly", "customTime").factorize(colSelectorFactory); aggregate(agg); aggregate(agg); aggregate(agg); aggregate(agg); Pair<Long, Float> result = (Pair<Long, Float>) agg.get(); Assert.assertEquals(customTimes[1], result.lhs.longValue()); Assert.assertEquals(floats[1], result.rhs, 0.0001); Assert.assertEquals((long) floats[1], agg.getLong()); Assert.assertEquals(floats[1], agg.getFloat(), 0.0001); } @Test public void testFloatLastBufferAggregator() { BufferAggregator agg = floatLastAggregatorFactory.factorizeBuffered( colSelectorFactory); ByteBuffer buffer = ByteBuffer.wrap(new byte[floatLastAggregatorFactory.getMaxIntermediateSizeWithNulls()]); agg.init(buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); Pair<Long, Float> result = (Pair<Long, Float>) agg.get(buffer, 0); Assert.assertEquals(times[0], result.lhs.longValue()); Assert.assertEquals(floats[0], result.rhs, 0.0001); Assert.assertEquals((long) floats[0], agg.getLong(buffer, 0)); Assert.assertEquals(floats[0], agg.getFloat(buffer, 0), 0.0001); } @Test public void testFloatLastBufferAggregatorWithTimeColumn() { BufferAggregator agg = new FloatLastAggregatorFactory("billy", "nilly", "customTime").factorizeBuffered( colSelectorFactory); ByteBuffer buffer = ByteBuffer.wrap(new byte[floatLastAggregatorFactory.getMaxIntermediateSizeWithNulls()]); agg.init(buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); Pair<Long, Float> result = (Pair<Long, Float>) agg.get(buffer, 0); Assert.assertEquals(customTimes[1], result.lhs.longValue()); Assert.assertEquals(floats[1], result.rhs, 0.0001); Assert.assertEquals((long) floats[1], agg.getLong(buffer, 0)); Assert.assertEquals(floats[1], agg.getFloat(buffer, 0), 0.0001); } @Test public void testCombine() { SerializablePair pair1 = new SerializablePair<>(1467225000L, 3.621f); SerializablePair pair2 = new SerializablePair<>(1467240000L, 785.4f); Assert.assertEquals(pair2, floatLastAggregatorFactory.combine(pair1, pair2)); } @Test public void testComparatorWithNulls() { SerializablePair pair1 = new SerializablePair<>(1467225000L, 3.621f); SerializablePair pair2 = new SerializablePair<>(1467240000L, null); Comparator comparator = floatLastAggregatorFactory.getComparator(); Assert.assertEquals(1, comparator.compare(pair1, pair2)); Assert.assertEquals(0, comparator.compare(pair1, pair1)); Assert.assertEquals(0, comparator.compare(pair2, pair2)); Assert.assertEquals(-1, comparator.compare(pair2, pair1)); } @Test public void testFloatLastCombiningAggregator() { Aggregator agg = combiningAggFactory.factorize(colSelectorFactory); aggregate(agg); aggregate(agg); aggregate(agg); aggregate(agg); Pair<Long, Float> result = (Pair<Long, Float>) agg.get(); Pair<Long, Float> expected = (Pair<Long, Float>) pairs[2]; Assert.assertEquals(expected.lhs, result.lhs); Assert.assertEquals(expected.rhs, result.rhs, 0.0001); Assert.assertEquals(expected.rhs.longValue(), agg.getLong()); Assert.assertEquals(expected.rhs, agg.getFloat(), 0.0001); } @Test public void testFloatLastCombiningBufferAggregator() { BufferAggregator agg = combiningAggFactory.factorizeBuffered( colSelectorFactory); ByteBuffer buffer = ByteBuffer.wrap(new byte[floatLastAggregatorFactory.getMaxIntermediateSizeWithNulls()]); agg.init(buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); aggregate(agg, buffer, 0); Pair<Long, Float> result = (Pair<Long, Float>) agg.get(buffer, 0); Pair<Long, Float> expected = (Pair<Long, Float>) pairs[2]; Assert.assertEquals(expected.lhs, result.lhs); Assert.assertEquals(expected.rhs, result.rhs, 0.0001); Assert.assertEquals(expected.rhs.longValue(), agg.getLong(buffer, 0)); Assert.assertEquals(expected.rhs, agg.getFloat(buffer, 0), 0.0001); } @Test public void testSerde() throws Exception { DefaultObjectMapper mapper = new DefaultObjectMapper(); String floatSpecJson = "{\"type\":\"floatLast\",\"name\":\"billy\",\"fieldName\":\"nilly\"}"; AggregatorFactory deserialized = mapper.readValue(floatSpecJson, AggregatorFactory.class); Assert.assertEquals(floatLastAggregatorFactory, deserialized); Assert.assertArrayEquals(floatLastAggregatorFactory.getCacheKey(), deserialized.getCacheKey()); } private void aggregate( Aggregator agg ) { agg.aggregate(); timeSelector.increment(); customTimeSelector.increment(); valueSelector.increment(); objectSelector.increment(); } private void aggregate( BufferAggregator agg, ByteBuffer buff, int position ) { agg.aggregate(buff, position); timeSelector.increment(); customTimeSelector.increment(); valueSelector.increment(); objectSelector.increment(); } }
nishantmonu51/druid
processing/src/test/java/org/apache/druid/query/aggregation/last/FloatLastAggregationTest.java
Java
apache-2.0
9,403
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.olingo.server.core.uri.queryoption; import org.apache.olingo.server.api.uri.queryoption.FilterOption; import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; import org.apache.olingo.server.api.uri.queryoption.expression.Expression; public class FilterOptionImpl extends SystemQueryOptionImpl implements FilterOption { private Expression expression; public FilterOptionImpl() { setKind(SystemQueryOptionKind.FILTER); } public FilterOptionImpl setExpression(final Expression expression) { this.expression = expression; return this; } @Override public Expression getExpression() { return expression; } }
apache/olingo-odata4
lib/server-core/src/main/java/org/apache/olingo/server/core/uri/queryoption/FilterOptionImpl.java
Java
apache-2.0
1,481
{% extends 'pages/base.html' %} {% block maintitle %} Fractions {% endblock maintitle %} {% block navbar_breadcrumb %} <ul class="nav navbar-nav oppia-navbar-breadcrumb"> <li> <span class="oppia-navbar-breadcrumb-separator"></span> <span>Fractions</span> </li> </ul> {% endblock navbar_breadcrumb %} {% block content %} <div ng-controller="Fractions" class="section" style="font-family: 'Capriola', 'Roboto', Arial, sans-serif; height: 100vh; background-color: #afd2eb;"> <div class="container"> <div class="row" style="margin-top: 50px;"> <div class="col-xs-4"> <img ng-src="<[getStaticImageUrl('/general/about_page_mascot.png')]>" style="position: relative; margin-bottom: -30px; z-index: 999;" height="220" width="227" class="pull-right"> </div> <div class="col-xs-4"> <div class="oppia-fractions-landing-page-bubble"> <strong>Great!</strong>&nbsp;You've come to the right place if you want to learn about fractions! <div class="oppia-fractions-landing-page-pointer"></div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="jumbotron" style="background: white;"> <h1 style="color: #024340;">Free lessons for fractions</h1> <p class="fraction-faqs-answer">Fractions represent numbers "between" the counting numbers. For example, if I cut a cake into four equal pieces, and eat one of them (yum!), I need a number between 0 and 1 to represent how much I've eaten. <a href="/explore/ereONiVLp-VE">Start the first lesson</a> to learn more.</p> <a class="btn btn-primary btn-lg first-lesson-btn" href="/explore/ereONiVLp-VE">Continue to the first lesson</a> </div> </div> </div> </div> </div> <style> h1, h2, h3, h4 h5, h6 { margin-bottom: 10px; margin-top: 20px; } .fraction-faqs-answers { font-size: 21px; font-weight: 200; margin-bottom: 15px; padding: 10px; } .first-lesson-btn { background-color: rgba(0, 150, 136, 0.85); } .first-lesson-btn:hover { background-color: #286090; border-color: #204d74; color: #fff; } </style> {% endblock %} {% block footer_js %} {{ super() }} <script src="{{TEMPLATE_DIR_PREFIX}}/pages/landing/fractions/Fractions.js"></script> {% endblock footer_js %}
himanshu-dixit/oppia
core/templates/dev/head/pages/landing/fractions/landing_page_c.html
HTML
apache-2.0
2,443
/** * Copyright (C) 2004-2009 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.util; import org.dom4j.Element; import org.dom4j.Node; import java.util.*; /** * <p>We use a simple * naming convention of meta-data key names: data is stored * heirarchically separated by dots. The last name may contain * a colon ':' character that is read as name:attribute. * For example setting X.Y.Z to someValue, would map to an XML snippet of:</p> * <pre> * &lt;X&gt; * &lt;Y&gt; * &lt;Z&gt;someValue&lt;/Z&gt; * &lt;/Y&gt; * &lt;/X&gt; * </pre> * <p>And X.Y.Z:key to anotherValue as:</p> * <pre> * &lt;X&gt; * &lt;Y&gt; * &lt;Z key="anotherValue" /&gt; * &lt;/Y&gt; * &lt;/X&gt; * </pre> * <p>Some XML cannot be built or accessed using this naming * convention (e.g. a typical Roster reset packet). More complex XML * packet should be represented using the XMPPDOMFragment. The * Element class is designed to provide 80% of XML * manipulation capabilities with the simplest 20% of code and API size * making it convenient for meta-data, simple IQ packets, etc.</p> */ public class ElementUtil { private ElementUtil() { } /** * Returns the value of the specified property. A <tt>null</tt> answer does not necessarily mean * that the property does not exist. * * @param name the name of the property to get. * @return the value of the specified property. */ public static String getProperty(Element element, String name) { String value = null; String[] propName = parsePropertyName(name); // Grab the attribute if there is one String lastName = propName[propName.length - 1]; String attName = null; int attributeIndex = lastName.indexOf(':'); if (attributeIndex >= 0) { propName[propName.length - 1] = lastName.substring(0, attributeIndex); attName = lastName.substring(attributeIndex + 1); } // Search for this property by traversing down the XML hierarchy. int i = propName[0].equals(element.getName()) ? 1 : 0; for (; i < propName.length; i++) { element = element.element(propName[i]); if (element == null) { break; } } if (element != null) { if (attName == null) { value = element.getTextTrim(); } else { value = element.attributeValue(attName); } } return value; } /** * Returns true if the specified property is included in the XML hierarchy. A property could * have a value associated or not. If the property has an associated value then * * @param name the name of the property to find out. * @return true if the specified property is included in the XML hierarchy. */ public static boolean includesProperty(Element element, String name) { String[] propName = parsePropertyName(name); // Grab the attribute if there is one String lastName = propName[propName.length - 1]; String attName = null; int attributeIndex = lastName.indexOf(':'); if (attributeIndex >= 0) { propName[propName.length - 1] = lastName.substring(0, attributeIndex); attName = lastName.substring(attributeIndex + 1); } // Search for this property by traversing down the XML hierarchy. int i = propName[0].equals(element.getName()) ? 1 : 0; for (; i < propName.length; i++) { element = element.element(propName[i]); if (element == null) { break; } } if (element != null) { if (attName == null){ // The property exists so return true return true; } else { // The property exists if the attribute exists in the element return element.attribute(attName) != null; } } else { // The property does not exist so return false return false; } } /** * Return all values who's path matches the given property name as a String array, * or an empty array if the if there are no children. You MAY NOT use the atttribute * markup (using a ':' in the last element name) with this call. * <p> * getProperties() allows you to retrieve several values with the same property name. * For example, consider the XML file entry:</p> * <pre> * &lt;foo&gt; * &lt;bar&gt; * &lt;prop&gt;some value&lt;/prop&gt; * &lt;prop&gt;other value&lt;/prop&gt; * &lt;prop&gt;last value&lt;/prop&gt; * &lt;/bar&gt; * &lt;/foo&gt; * </pre> * If you call getProperties("foo.bar.prop") will return a string array containing * {"some value", "other value", "last value"}. * * @param name the name of the property to retrieve * @return all child property values for the given node name. */ public String[] getProperties(Element element, String name) { String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy, stopping one short. int i = propName[0].equals(element.getName()) ? 1 : 0; for (; i < propName.length - 1; i++) { element = element.element(propName[i]); if (element == null) { // This node doesn't match this part of the property name which // indicates this property doesn't exist so return empty array. return new String[]{}; } } // We found matching property, return names of children. Iterator iter = element.elementIterator(propName[propName.length - 1]); ArrayList<String> props = new ArrayList<>(); while (iter.hasNext()) { Element e = (Element) iter.next(); props.add(e.getName()); } String[] childrenNames = new String[props.size()]; return props.toArray(childrenNames); } /** * Sets a property to an array of values. You MAY NOT use the atttribute * markup (using a ':' in the last element name) with this call. Multiple values matching the * same property is mapped to an XML file as multiple elements containing each value. * For example, using the name "foo.bar.prop", and the value string array containing * {"some value", "other value", "last value"} would produce the following XML: * <pre> * &lt;foo&gt; * &lt;bar&gt; * &lt;prop&gt;some value&lt;/prop&gt; * &lt;prop&gt;other value&lt;/prop&gt; * &lt;prop&gt;last value&lt;/prop&gt; * &lt;/bar&gt; * &lt;/foo&gt; * </pre> * * @param name the name of the property. * @param values The array of values for the property (can be empty but not null) */ public static void setProperties(Element element, String name, String[] values) { String[] propName = parsePropertyName(name); setProperty(element, name, values[0]); // Search for this property by traversing down the XML heirarchy, stopping one short. int i = propName[0].equals(element.getName()) ? 1 : 0; for (; i < propName.length - 1; i++) { element = element.element(propName[i]); if (element == null) { // This node doesn't match this part of the property name which // indicates this property doesn't exist so return empty array. return; } } String childName = propName[propName.length - 1]; // We found matching property, clear all children. Iterator iter = element.elementIterator(childName); while (iter.hasNext()) { ((Node) iter.next()).detach(); } for (int j = 0; i < values.length; i++) { if (values[j] != null) { element.addElement(childName).setText(values[j]); } } } /** * Return all children property names of a parent property as a String array, * or an empty array if the if there are no children. You MAY NOT use the atttribute * markup (using a ':' in the last element name) with this call. * For example, given the properties <tt>X.Y.A</tt>, <tt>X.Y.B</tt>, and <tt>X.Y.C</tt>, then * the child properties of <tt>X.Y</tt> are <tt>A</tt>, <tt>B</tt>, and * <tt>C</tt>. * * @param parent the name of the parent property. * @return all child property values for the given parent. */ public static String[] getChildrenProperties(Element element, String parent) { String[] propName = parsePropertyName(parent); // Search for this property by traversing down the XML heirarchy. int i = propName[0].equals(element.getName()) ? 1 : 0; for (; i < propName.length; i++) { element = element.element(propName[i]); if (element == null) { // This node doesn't match this part of the property name which // indicates this property doesn't exist so return empty array. return new String[]{}; } } // We found matching property, return names of children. List children = element.elements(); int childCount = children.size(); String[] childrenNames = new String[childCount]; for (int j = 0; i < childCount; i++) { childrenNames[j] = ((Element) children.get(j)).getName(); } return childrenNames; } /** * Returns all recursive children of the given parent property or an empty string array * if no children exist. The list of children is depth-first so the array is optimized * for easy displaying. * * @param parent the parent property. * @return all recursive children of the given property in depth-first order or an empty * string array if no children exist. */ public static String[] getRecursiveChildrenProperties(Element element, String parent) { String[] properties = getChildrenProperties(element, parent); if (properties.length == 0) { return properties; } else { List<String> list = new ArrayList<>(15); for (int i = 0; i < properties.length; i++) { String propName = parent + "." + properties[i]; list.add(propName); list.addAll(Arrays.asList(getRecursiveChildrenProperties(element, propName))); } return list.toArray(new String[]{}); } } /** * Sets the value of the specified property. If the property doesn't * currently exist, it will be automatically created. * * @param name the name of the property to set. * @param value the new value for the property. */ public static void setProperty(Element element, String name, String value) { if (name == null || name.length() == 0) return; if (value == null) value = ""; String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy. int i = propName[0].equals(element.getName()) ? 1 : 0; for (; i < propName.length - 1; i++) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(propName[i]) == null) { element.addElement(propName[i]); } element = element.element(propName[i]); } String lastName = propName[propName.length - 1]; int attributeIndex = lastName.indexOf(':'); if (attributeIndex >= 0) { String eleName = lastName.substring(0, attributeIndex); String attName = lastName.substring(attributeIndex + 1); // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(eleName) == null) { element.addElement(eleName); } element.element(eleName).addAttribute(attName, value); } else { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(lastName) == null) { element.addElement(lastName); } // Set the value of the property in this node. element.element(lastName).setText(value); } } /** * <p>Deletes the specified property.</p> * <p>You MAY NOT use the atttribute * markup (using a ':' in the last element name) with this call. * deleteProperty() removes both the containing text, and the element itself along with * any attributes associated with that element.</p> * * @param name the property to delete. */ public static void deleteProperty(Element element, String name) { // Remove property from cache. String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy. for (int i = 0; i < propName.length - 1; i++) { element = element.element(propName[i]); // Can't find the property so return. if (element == null) { return; } } // Found the correct element to remove, so remove it... element.remove(element.element(propName[propName.length - 1])); } /** * Returns an array representation of the given Jive property. Jive * properties are always in the format "prop.name.is.this" which would be * represented as an array of four Strings. * * @param name the name of the Jive property. * @return an array representation of the given Jive property. */ private static String[] parsePropertyName(String name) { List<String> propName = new ArrayList<>(5); // Use a StringTokenizer to tokenize the property name. StringTokenizer tokenizer = new StringTokenizer(name, "."); while (tokenizer.hasMoreTokens()) { propName.add(tokenizer.nextToken()); } return propName.toArray(new String[propName.size()]); } }
zhouluoyang/openfire
src/java/org/jivesoftware/util/ElementUtil.java
Java
apache-2.0
15,070
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.persistent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.TimeValue; import org.elasticsearch.tasks.CancellableTask; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.tasks.TaskManager; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; /** * Represents a executor node operation that corresponds to a persistent task */ public class AllocatedPersistentTask extends CancellableTask { private static final Logger logger = LogManager.getLogger(AllocatedPersistentTask.class); private final AtomicReference<State> state; private volatile String persistentTaskId; private volatile long allocationId; private volatile @Nullable Exception failure; private volatile PersistentTasksService persistentTasksService; private volatile TaskManager taskManager; public AllocatedPersistentTask(long id, String type, String action, String description, TaskId parentTask, Map<String, String> headers) { super(id, type, action, description, parentTask, headers); this.state = new AtomicReference<>(State.STARTED); } @Override public Status getStatus() { return new PersistentTasksNodeService.Status(state.get()); } /** * Updates the persistent state for the corresponding persistent task. * <p> * This doesn't affect the status of this allocated task. */ public void updatePersistentTaskState(final PersistentTaskState state, final ActionListener<PersistentTasksCustomMetadata.PersistentTask<?>> listener) { persistentTasksService.sendUpdateStateRequest(persistentTaskId, allocationId, state, listener); } public String getPersistentTaskId() { return persistentTaskId; } protected void init(PersistentTasksService persistentTasksService, TaskManager taskManager, String persistentTaskId, long allocationId) { this.persistentTasksService = persistentTasksService; this.taskManager = taskManager; this.persistentTaskId = persistentTaskId; this.allocationId = allocationId; } public Exception getFailure() { return failure; } public long getAllocationId() { return allocationId; } /** * Waits for a given persistent task to comply with a given predicate, then call back the listener accordingly. * * @param predicate the persistent task predicate to evaluate * @param timeout a timeout for waiting * @param listener the callback listener */ public void waitForPersistentTask(final Predicate<PersistentTasksCustomMetadata.PersistentTask<?>> predicate, final @Nullable TimeValue timeout, final PersistentTasksService.WaitForPersistentTaskListener<?> listener) { persistentTasksService.waitForPersistentTaskCondition(persistentTaskId, predicate, timeout, listener); } /** * For external purposes, locally aborted and completed are the same. * @return Is this task completed on the current node? */ protected final boolean isCompleted() { return state.get() == State.COMPLETED || state.get() == State.LOCAL_ABORTED; } protected boolean markAsCancelled() { return state.compareAndSet(State.STARTED, State.PENDING_CANCEL); } public void markAsCompleted() { completeAndNotifyIfNeeded(null, null); } public void markAsFailed(Exception e) { if (CancelTasksRequest.DEFAULT_REASON.equals(getReasonCancelled())) { completeAndNotifyIfNeeded(null, null); } else { completeAndNotifyIfNeeded(e, null); } } /** * Indicates that this persistent task is no longer going to run on the local node. * This will cause the local task to be terminated, and the associated persistent * task to be reassigned by the master node. The persistent task <em>may</em> be * reassigned to the same node unless separate measures have been taken to prevent * this. The task should complete any graceful shutdown actions before calling this * method. * @param localAbortReason Reason for the task being aborted on this node. This * will be recorded as the reason for unassignment of the * persistent task. */ public void markAsLocallyAborted(String localAbortReason) { completeAndNotifyIfNeeded(null, Objects.requireNonNull(localAbortReason)); } private void completeAndNotifyIfNeeded(@Nullable Exception failure, @Nullable String localAbortReason) { assert failure == null || localAbortReason == null : "completion notification has both exception " + failure + " and local abort reason " + localAbortReason; final State desiredState = (localAbortReason == null) ? State.COMPLETED : State.LOCAL_ABORTED; final State prevState = state.getAndUpdate( currentState -> (currentState != State.COMPLETED && currentState != State.LOCAL_ABORTED) ? desiredState : currentState); if (prevState == State.COMPLETED || prevState == State.LOCAL_ABORTED) { // To preserve old behaviour completing a task twice is not an error. // However, any combination of local abort with completion or failure // is an error, as is issuing two local aborts for the same task. if (desiredState == State.COMPLETED) { if (prevState == State.COMPLETED) { logger.warn("attempt to complete task [{}] with id [{}] in the [{}] state", getAction(), getPersistentTaskId(), prevState); } else { throw new IllegalStateException("attempt to " + (failure != null ? "fail" : "complete") + " task [" + getAction() + "] with id [" + getPersistentTaskId() + "] which has been locally aborted"); } } else { throw new IllegalStateException("attempt to locally abort task [" + getAction() + "] with id [" + getPersistentTaskId() + "] which has already been " + (prevState == State.COMPLETED ? "completed" : "locally aborted")); } } else { if (failure != null) { logger.warn(() -> new ParameterizedMessage("task [{}] failed with an exception", getPersistentTaskId()), failure); } else if (localAbortReason != null) { logger.debug("task [{}] aborted locally: [{}]", getPersistentTaskId(), localAbortReason); } try { this.failure = failure; if (prevState == State.STARTED) { logger.trace("sending notification for completed task [{}] with id [{}]", getAction(), getPersistentTaskId()); persistentTasksService.sendCompletionRequest(getPersistentTaskId(), getAllocationId(), failure, localAbortReason, new ActionListener<PersistentTasksCustomMetadata.PersistentTask<?>>() { @Override public void onResponse(PersistentTasksCustomMetadata.PersistentTask<?> persistentTask) { logger.trace("notification for task [{}] with id [{}] was successful", getAction(), getPersistentTaskId()); } @Override public void onFailure(Exception e) { logger.warn(() -> new ParameterizedMessage( "notification for task [{}] with id [{}] failed", getAction(), getPersistentTaskId()), e); } }); } } finally { taskManager.unregister(this); } } } public enum State { STARTED, // the task is currently running PENDING_CANCEL, // the task is cancelled on master, cancelling it locally COMPLETED, // the task is done running and trying to notify caller LOCAL_ABORTED // the task is aborted on the local node - master should reassign } }
ern/elasticsearch
server/src/main/java/org/elasticsearch/persistent/AllocatedPersistentTask.java
Java
apache-2.0
9,177
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfAndXwtViewer { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private LibRdlCrossPlatformViewer.ReportViewer rv; // TODO: add a way that parameters can be entered by an end user. private string parameters = ""; public MainWindow() { InitializeComponent(); // Before using any xwt code you must initialize its engine as wpf // See https://groups.google.com/forum/?fromgroups=#!topic/xwt-list/9d2kb4cf5GU Xwt.Application.Initialize(Xwt.ToolkitType.Wpf); Xwt.Engine.Toolkit.ExitUserCode(null); rv = new LibRdlCrossPlatformViewer.ReportViewer(); rv.DefaultBackend = LibRdlCrossPlatformViewer.Backend.XwtWinforms; // Since this is an example I just hard code the report path. // In your own application you will want to provice a method to select reports. #if DEBUG if (System.Environment.MachineName == "GILL-PC") { rv.LoadReport(new Uri(@"C:\Users\Peter\Projects\My-FyiReporting\Examples\SqliteExamples\SimpleTest1.rdl")); } else if (System.Environment.MachineName == "gill-desktop") { rv.LoadReport(new Uri(@"/home/peter/projects/My-FyiReporting/Examples/SqliteExamples/SimpleTest1.rdl")); } #endif // Here we convert the xwt VBox to a WPF Panel Panel w = (Panel)Xwt.Engine.WidgetRegistry.GetNativeWidget(rv); this.Content = w; } } }
majorsilence/My-FyiReporting
Examples/SampleWpfAndXwtViewer/WpfAndXwtViewer/MainWindow.xaml.cs
C#
apache-2.0
2,029
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.3-4-214 description: > Object.getOwnPropertyDescriptor returns accessor desc for accessors on built-ins (RegExp.prototype.ignoreCase) ---*/ var desc = Object.getOwnPropertyDescriptor(RegExp.prototype, "ignoreCase"); assert.sameValue(desc.hasOwnProperty('writable'), false, 'desc.hasOwnProperty("writable")'); assert.sameValue(desc.enumerable, false, 'desc.enumerable'); assert.sameValue(desc.configurable, true, 'desc.configurable'); assert.sameValue(typeof desc.get, 'function', 'typeof desc.get'); assert.sameValue(desc.set, undefined, 'desc.set');
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-214.js
JavaScript
bsd-2-clause
717
'use strict'; angular.module('ontimeApp') .controller('LocationController', function ($scope, $state, Location) { $scope.locations = []; $scope.loadAll = function() { Location.query(function(result) { $scope.locations = result; }); }; $scope.loadAll(); $scope.refresh = function () { $scope.loadAll(); $scope.clear(); }; $scope.clear = function () { $scope.location = { name: null, address: null, id: null }; }; });
sandor-balazs/nosql-java
oracle/src/main/webapp/scripts/app/entities/location/location.controller.js
JavaScript
bsd-2-clause
628
<?php /* * Bluethrust Clan Scripts v4 * Copyright 2014 * * Author: Bluethrust Web Development * E-mail: support@bluethrust.com * Website: http://www.bluethrust.com * * License: http://www.bluethrust.com/license.php * */ if(!isset($member) || !isset($tournamentObj) || substr($_SERVER['PHP_SELF'], -strlen("managetournament.php")) != "managetournament.php") { exit(); } else { // This is a little repeatative, but for security. $memberInfo = $member->get_info(); $consoleObj->select($cID); $tournamentObj->select($tID); if(!$member->hasAccess($consoleObj)) { exit(); } } echo " <script type='text/javascript'> $(document).ready(function() { $('#breadCrumbTitle').html(\"Set Tournament Managers\"); $('#breadCrumb').html(\"<a href='".$MAIN_ROOT."'>Home</a> > <a href='".$MAIN_ROOT."members'>My Account</a> > <a href='".$MAIN_ROOT."members/console.php?cID=".$cID."&select=".$tournamentInfo['tournament_id']."'>".$consoleTitle."</a> > <b>".$tournamentInfo['name'].":</b> Set Tournament Managers\"); }); </script> "; ?> <div class='formDiv'> Use the form below to add and remove tournament managers. A tournament manager will have all privileges in managing the tournament except for deleting the tournament and adding new tournament managers. <p><b><u>NOTE:</u></b> In order to be a manager, the user must have access to the <a href='<?php echo $MAIN_ROOT; ?>members/console.php?cID=<?php echo $cID; ?>'>Manage Tournaments</a> console option. <div class='manageTournamentTeams'> <div class='mttLeftColumn'> <div class='dottedLine' style='padding-bottom: 3px'><b>Current Managers:</b></div> <div class='loadingSpiral' id='loadingSpiral'> <p align='center'> <img src='<?php echo $MAIN_ROOT; ?>themes/<?php echo $THEME; ?>/images/loading-spiral.gif'><br>Loading </p> </div> <div id='managerList'> <?php define("SHOW_MANAGERLIST", true); include("include/managerlist.php"); ?> </div> </div> <div class='mttRightColumn'> <div class='dottedLine' style='padding-bottom: 3px'><b>Assign Managers:</b></div> <p><b>Enter Username:</b></p> <input type='text' class='textBox' id='newManager'> <p><i>- OR -</i></p> <p><b>Select from player list:</b></p> <select id='newManagerSelect' class='textBox'> <option value=''>Select</option> <?php $tournamentConsoleCheck = new ConsoleOption($mysqli); $tournamentConsoleCheck->select($cID); $result = $mysqli->query("SELECT ".$dbprefix."tournamentplayers.member_id FROM ".$dbprefix."tournamentplayers, ".$dbprefix."members, ".$dbprefix."ranks WHERE ".$dbprefix."members.member_id = ".$dbprefix."tournamentplayers.member_id AND ".$dbprefix."members.rank_id = ".$dbprefix."ranks.rank_id AND ".$dbprefix."tournamentplayers.tournament_id = '".$tID."' AND ".$dbprefix."tournamentplayers.member_id != '0' ORDER BY ".$dbprefix."ranks.ordernum DESC"); while($row = $result->fetch_assoc()) { $member->select($row['member_id']); if($member->hasAccess($tournamentConsoleCheck)) { echo "<option value='".$row['member_id']."'>".$member->getMemberLink()."</option>"; } } $member->select($memberInfo['member_id']); ?> </select> <br><br> <p align='center'> <input type='button' class='submitButton' value='Add Manager' id='btnAddManager'> </p> </div> </div> </div> <input type='hidden' id='newManagerID'> <?php // Get auto-complete list $arrMembers = array(); $result = $mysqli->query("SELECT ".$dbprefix."members.member_id, ".$dbprefix."members.username FROM ".$dbprefix."members, ".$dbprefix."ranks WHERE ".$dbprefix."members.rank_id = ".$dbprefix.".ranks.rank_id AND ".$dbprefix."members.disabled = '0' ORDER BY ".$dbprefix."ranks.ordernum DESC"); while($row = $result->fetch_assoc()) { $member->select($row['member_id']); if($member->hasAccess($tournamentConsoleCheck)) { $arrMembers[] = array("id" => $row['member_id'], "value" => filterText($row['username'])); } } $member->select($memberInfo['member_id']); $arrJSONMembers = json_encode($arrMembers); ?> <script type='text/javascript'> $(document).ready(function() { var arrMemberList = <?php echo $arrJSONMembers; ?>; $('#newManager').autocomplete({ source: arrMemberList, minLength: 3, select: function(event, ui) { $('#newManagerID').val(ui.item.id); $('#newManagerSelect').val(""); } }); $('#newManagerSelect').change(function() { if($('#newManagerSelect').val() != "") { $('#newManagerID').val($(this).val()); $('#newManager').val(""); } }); $('#btnAddManager').click(function() { $('#loadingSpiral').show(); $('#managerList').hide(); $.post('<?php echo $MAIN_ROOT; ?>members/tournaments/include/addmanager.php', { tournamentID: '<?php echo $tID; ?>', managerID: $('#newManagerID').val() }, function(data) { $('#managerList').html(data); $('#loadingSpiral').hide(); $('#managerList').fadeIn(250); $('#newManagerID').val(""); $('#newManager').val(""); $('#newManagerSelect').val(""); }); }); }); function deleteManager(mID) { $(document).ready(function() { $('#loadingSpiral').show(); $('#managerList').hide(); $.post('<?php echo $MAIN_ROOT; ?>members/tournaments/include/deletemanager.php', { tournamentID: '<?php echo $tID; ?>', managerID: mID }, function(data) { $('#managerList').html(data); $('#loadingSpiral').hide(); $('#managerList').fadeIn(250); }); }); } </script>
bluethrust/clanscriptsv4
members/tournaments/setmanagers.php
PHP
bsd-2-clause
5,534
class Pngcheck < Formula desc "Print info and check PNG, JNG, and MNG files" homepage "http://www.libpng.org/pub/png/apps/pngcheck.html" url "http://www.libpng.org/pub/png/src/pngcheck-3.0.3.tar.gz" sha256 "c36a4491634af751f7798ea421321642f9590faa032eccb0dd5fb4533609dee6" license all_of: ["MIT", "GPL-2.0-or-later"] livecheck do url :homepage regex(/href=.*?pngcheck[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "a009523aaa8a5c8eb879fda99829ce1007b682b2caa2413af78112aa94ee741c" sha256 cellar: :any_skip_relocation, big_sur: "8a025005cde9e8423606279cea498d921810f2334fe17a7bf23a1eba6ee54aef" sha256 cellar: :any_skip_relocation, catalina: "a4256bacc1a8025fa298b35d93af3ecf213449ab9118106530cdd29455293ead" sha256 cellar: :any_skip_relocation, mojave: "6423830817d3166ce48ea9cb88f3a83f1f7e381d8a1039c4db153e465450d5c5" sha256 cellar: :any_skip_relocation, x86_64_linux: "bee1eb579044cbdf33c6e4f045a800debb49b2f9ca4d3517d718956872a58a97" end uses_from_macos "zlib" def install system "make", "-f", "Makefile.unx", "ZINC=", "ZLIB=-lz" bin.install %w[pngcheck pngsplit png-fix-IDAT-windowsize] end test do system bin/"pngcheck", test_fixtures("test.png") end end
zyedidia/homebrew-core
Formula/pngcheck.rb
Ruby
bsd-2-clause
1,301
cask "micro-snitch" do version "1.5.1" sha256 "0751ee61be154d2efbe9c39ad496544f53944b4d880aefa1ef487b35755cc952" url "https://www.obdev.at/downloads/MicroSnitch/MicroSnitch-#{version}.dmg" name "Micro Snitch" desc "Monitors and reports any microphone and camera activity" homepage "https://www.obdev.at/products/microsnitch/index.html" livecheck do url "https://www.obdev.at/products/microsnitch/download.html" regex(%r{href=.*?/MicroSnitch[._-]v?(\d+(?:\.\d+)+)\.dmg}i) end auto_updates true depends_on macos: ">= :el_capitan" app "Micro Snitch.app" uninstall quit: "at.obdev.MicroSnitch", launchctl: "at.obdev.MicroSnitchOpenAtLoginHelper" zap trash: [ "~/Library/Application Support/at.obdev.MicroSnitchOpenAtLoginHelper", "~/Library/Application Support/Micro Snitch", "~/Library/Caches/at.obdev.MicroSnitch", "~/Library/Containers/at.obdev.MicroSnitchOpenAtLoginHelper", "~/Library/Logs/Micro Snitch.log", "~/Library/Preferences/at.obdev.MicroSnitch.plist", ] end
nrlquaker/homebrew-cask
Casks/micro-snitch.rb
Ruby
bsd-2-clause
1,051
// Copyright 2016 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. #ifndef MOJO_PUBLIC_CPP_SYSTEM_WATCHER_H_ #define MOJO_PUBLIC_CPP_SYSTEM_WATCHER_H_ #include <memory> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_checker.h" #include "base/threading/thread_task_runner_handle.h" #include "mojo/public/c/system/types.h" #include "mojo/public/cpp/system/handle.h" #include "mojo/public/cpp/system/system_export.h" namespace mojo { // A Watcher watches a single Mojo handle for signal state changes. // // NOTE: Watchers may only be used on threads which have a running MessageLoop. class MOJO_CPP_SYSTEM_EXPORT Watcher { public: // A callback to be called any time a watched handle changes state in some // interesting way. The |result| argument indicates one of the following // conditions depending on its value: // // |MOJO_RESULT_OK|: One or more of the signals being watched is satisfied. // // |MOJO_RESULT_FAILED_PRECONDITION|: None of the signals being watched can // ever be satisfied again. // // |MOJO_RESULT_CANCELLED|: The handle has been closed and the watch has // been cancelled implicitly. // // |MOJO_RESULT_ABORTED|: Notifications can no longer be delivered for this // watcher for some unspecified reason, e.g., the watching thread may // be shutting down soon. Note that it is still necessary to explicitly // Cancel() the watch in this case. using ReadyCallback = base::Callback<void(MojoResult result)>; explicit Watcher(scoped_refptr<base::SingleThreadTaskRunner> runner = base::ThreadTaskRunnerHandle::Get()); // NOTE: This destructor automatically calls |Cancel()| if the Watcher is // still active. ~Watcher(); // Indicates if the Watcher is currently watching a handle. bool IsWatching() const; // Starts watching |handle|. A Watcher may only watch one handle at a time, // but it is safe to call this more than once as long as the previous watch // has been cancelled (i.e. |is_watching()| returns |false|.) // // If no signals in |signals| can ever be satisfied for |handle|, this returns // |MOJO_RESULT_FAILED_PRECONDITION|. // // If |handle| is not a valid watchable (message or data pipe) handle, this // returns |MOJO_RESULT_INVALID_ARGUMENT|. // // Otherwise |MOJO_RESULT_OK| is returned and the handle will be watched until // closure or cancellation. // // Once the watch is started, |callback| may be called at any time on the // current thread until |Cancel()| is called or the handle is closed. // // Destroying the Watcher implicitly calls |Cancel()|. MojoResult Start(Handle handle, MojoHandleSignals signals, const ReadyCallback& callback); // Cancels the current watch. Once this returns, the callback previously // passed to |Start()| will never be called again for this Watcher. void Cancel(); Handle handle() const { return handle_; } ReadyCallback ready_callback() const { return callback_; } private: class MessageLoopObserver; friend class MessageLoopObserver; void OnHandleReady(MojoResult result); static void CallOnHandleReady(uintptr_t context, MojoResult result, MojoHandleSignalsState signals_state, MojoWatchNotificationFlags flags); base::ThreadChecker thread_checker_; // The TaskRunner of this Watcher's owning thread. This field is safe to // access from any thread. const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Whether |task_runner_| is the same as base::ThreadTaskRunnerHandle::Get() // for the thread. const bool is_default_task_runner_; std::unique_ptr<MessageLoopObserver> message_loop_observer_; // A persistent weak reference to this Watcher which can be passed to the // Dispatcher any time this object should be signalled. Safe to access (but // not to dereference!) from any thread. base::WeakPtr<Watcher> weak_self_; // Fields below must only be accessed on the Watcher's owning thread. // The handle currently under watch. Not owned. Handle handle_; // The callback to call when the handle is signaled. ReadyCallback callback_; base::WeakPtrFactory<Watcher> weak_factory_; DISALLOW_COPY_AND_ASSIGN(Watcher); }; } // namespace mojo #endif // MOJO_PUBLIC_CPP_SYSTEM_WATCHER_H_
ssaroha/node-webrtc
third_party/webrtc/include/chromium/src/mojo/public/cpp/system/watcher.h
C
bsd-2-clause
4,683
/* * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS 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. */ #ifndef DatabaseTask_h #define DatabaseTask_h #include "modules/webdatabase/Database.h" #include "modules/webdatabase/DatabaseBasicTypes.h" #include "modules/webdatabase/DatabaseError.h" #include "modules/webdatabase/SQLTransactionBackend.h" #include "platform/WaitableEvent.h" #include "platform/heap/Handle.h" #include "wtf/PtrUtil.h" #include "wtf/Threading.h" #include "wtf/Vector.h" #include "wtf/text/WTFString.h" #include <memory> namespace blink { class DatabaseTask { WTF_MAKE_NONCOPYABLE(DatabaseTask); USING_FAST_MALLOC(DatabaseTask); public: virtual ~DatabaseTask(); void run(); Database* database() const { return m_database.get(); } protected: DatabaseTask(Database*, WaitableEvent* completeEvent); private: virtual void doPerformTask() = 0; virtual void taskCancelled() {} CrossThreadPersistent<Database> m_database; WaitableEvent* m_completeEvent; #if DCHECK_IS_ON() virtual const char* debugTaskName() const = 0; bool m_complete; #endif }; class Database::DatabaseOpenTask final : public DatabaseTask { public: static std::unique_ptr<DatabaseOpenTask> create(Database* db, bool setVersionInNewDatabase, WaitableEvent* completeEvent, DatabaseError& error, String& errorMessage, bool& success) { return wrapUnique(new DatabaseOpenTask(db, setVersionInNewDatabase, completeEvent, error, errorMessage, success)); } private: DatabaseOpenTask(Database*, bool setVersionInNewDatabase, WaitableEvent*, DatabaseError&, String& errorMessage, bool& success); void doPerformTask() override; #if DCHECK_IS_ON() const char* debugTaskName() const override; #endif bool m_setVersionInNewDatabase; DatabaseError& m_error; String& m_errorMessage; bool& m_success; }; class Database::DatabaseCloseTask final : public DatabaseTask { public: static std::unique_ptr<DatabaseCloseTask> create( Database* db, WaitableEvent* synchronizer) { return wrapUnique(new DatabaseCloseTask(db, synchronizer)); } private: DatabaseCloseTask(Database*, WaitableEvent*); void doPerformTask() override; #if DCHECK_IS_ON() const char* debugTaskName() const override; #endif }; class Database::DatabaseTransactionTask final : public DatabaseTask { public: ~DatabaseTransactionTask() override; // Transaction task is never synchronous, so no 'synchronizer' parameter. static std::unique_ptr<DatabaseTransactionTask> create( SQLTransactionBackend* transaction) { return wrapUnique(new DatabaseTransactionTask(transaction)); } SQLTransactionBackend* transaction() const { return m_transaction.get(); } private: explicit DatabaseTransactionTask(SQLTransactionBackend*); void doPerformTask() override; void taskCancelled() override; #if DCHECK_IS_ON() const char* debugTaskName() const override; #endif CrossThreadPersistent<SQLTransactionBackend> m_transaction; }; class Database::DatabaseTableNamesTask final : public DatabaseTask { public: static std::unique_ptr<DatabaseTableNamesTask> create(Database* db, WaitableEvent* synchronizer, Vector<String>& names) { return wrapUnique(new DatabaseTableNamesTask(db, synchronizer, names)); } private: DatabaseTableNamesTask(Database*, WaitableEvent*, Vector<String>& names); void doPerformTask() override; #if DCHECK_IS_ON() const char* debugTaskName() const override; #endif Vector<String>& m_tableNames; }; } // namespace blink #endif // DatabaseTask_h
ssaroha/node-webrtc
third_party/webrtc/include/chromium/src/third_party/WebKit/Source/modules/webdatabase/DatabaseTask.h
C
bsd-2-clause
5,446
class Yank < Formula desc "Copy terminal output to clipboard" homepage "https://github.com/mptre/yank" url "https://github.com/mptre/yank/archive/v1.2.0.tar.gz" sha256 "c4a2f854f9e49e1df61491d3fab29ea595c7e3307394acb15f32b6d415840bce" license "MIT" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "518e0acdc9c56266b1666b5d4ef54367a8c9cd104826f0499b414d4158c540c9" sha256 cellar: :any_skip_relocation, big_sur: "df2425ac44c54c3e55aaf835a40d2ac74663193550ea32a09f88f23490e1f7d9" sha256 cellar: :any_skip_relocation, catalina: "ef4da54ce9a56a1767b44dd88df6616c147730d74f390d5a661910dddf8785a7" sha256 cellar: :any_skip_relocation, mojave: "60431f02c576c640597975986ce62f9d157c49f160d7d6e23f917dc321ca8bac" sha256 cellar: :any_skip_relocation, high_sierra: "b87461e809f0bebd615d4da69c31509109de8f86d07d280dab07326293cc851f" sha256 cellar: :any_skip_relocation, sierra: "70a5de45249c1656653733fea8d7a92c2496b9ba8e7540eef86b3f805d0e933a" end def install system "make", "install", "PREFIX=#{prefix}", "YANKCMD=pbcopy" end test do (testpath/"test.exp").write <<~EOS spawn sh set timeout 1 send "echo key=value | #{bin}/yank -d = | cat" send "\r" send "\016" send "\r" expect { "value" { send "exit\r"; exit 0 } timeout { send "exit\r"; exit 1 } } EOS system "expect", "-f", "test.exp" end end
spaam/homebrew-core
Formula/yank.rb
Ruby
bsd-2-clause
1,463
# Copyright (c) 2014, Ruslan Baratov # All rights reserved. if(DEFINED POLLY_UTILITIES_POLLY_INIT_CMAKE_) return() else() set(POLLY_UTILITIES_POLLY_INIT_CMAKE_ 1) endif() include("${CMAKE_CURRENT_LIST_DIR}/polly_fatal_error.cmake") macro(polly_init name generator) set(POLLY_TOOLCHAIN_NAME "${name}") get_filename_component( POLLY_TOOLCHAIN_TAG "${CMAKE_CURRENT_LIST_FILE}" NAME_WE ) string(COMPARE EQUAL "${CMAKE_GENERATOR}" "${generator}" _polly_correct) if(NOT _polly_correct) polly_fatal_error( "Please change generator to: ${generator}\n" "(Current generator: ${CMAKE_GENERATOR})" ) endif() set(HUNTER_CMAKE_GENERATOR "${generator}") endmacro()
idscan/polly
utilities/polly_init.cmake
CMake
bsd-2-clause
702
// //Copyright (c) 2014, Priologic Software Inc. //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE //ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE //LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR //CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF //SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS //INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN //CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) //ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //POSSIBILITY OF SUCH DAMAGE. // var selfEasyrtcid = ""; var waitingForRoomList = true; var isConnected = false; function initApp() { document.getElementById("main").className = "notconnected"; } function addToConversation(who, msgType, content, targeting) { // Escape html special characters, then add linefeeds. if( !content) { content = "**no body**"; } content = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); content = content.replace(/\n/g, '<br />'); var targetingStr = ""; if (targeting) { if (targeting.targetEasyrtcid) { targetingStr += "user=" + targeting.targetEasyrtcid; } if (targeting.targetRoom) { targetingStr += " room=" + targeting.targetRoom; } if (targeting.targetGroup) { targetingStr += " group=" + targeting.targetGroup; } } document.getElementById('conversation').innerHTML += "<b>" + who + " sent " + targetingStr + ":</b>&nbsp;" + content + "<br />"; } function genRoomDivName(roomName) { return "roomblock_" + roomName; } function genRoomOccupantName(roomName) { return "roomOccupant_" + roomName; } function setCredential(event, value) { if (event.keyCode === 13) { easyrtc.setCredential(value); } } function addRoom(roomName, parmString, userAdded) { if (!roomName) { roomName = document.getElementById("roomToAdd").value; parmString = document.getElementById("optRoomParms").value; } var roomid = genRoomDivName(roomName); if (document.getElementById(roomid)) { return; } function addRoomButton() { var roomButtonHolder = document.getElementById('rooms'); var roomdiv = document.createElement("div"); roomdiv.id = roomid; roomdiv.className = "roomDiv"; var roomButton = document.createElement("button"); roomButton.onclick = function() { sendMessage(null, roomName); }; var roomLabel = (document.createTextNode(roomName)); roomButton.appendChild(roomLabel); roomdiv.appendChild(roomButton); roomButtonHolder.appendChild(roomdiv); var roomOccupants = document.createElement("div"); roomOccupants.id = genRoomOccupantName(roomName); roomOccupants.className = "roomOccupants"; roomdiv.appendChild(roomOccupants); $(roomdiv).append(" -<a href=\"javascript:\leaveRoom('" + roomName + "')\">leave</a>"); } var roomParms = null; if (parmString && parmString !== "") { try { roomParms = JSON.parse(parmString); } catch (error) { roomParms = null; easyrtc.showError(easyrtc.errCodes.DEVELOPER_ERR, "Room Parameters must be an object containing key/value pairs. eg: {\"fruit\":\"banana\",\"color\":\"yellow\"}"); return; } } if (!isConnected || !userAdded) { addRoomButton(); console.log("adding gui for room " + roomName); } else { console.log("not adding gui for room " + roomName + " because already connected and it's a user action"); } if (userAdded) { console.log("calling joinRoom(" + roomName + ") because it was a user action "); easyrtc.joinRoom(roomName, roomParms, function() { /* we'll geta room entry event for the room we were actually added to */ }, function(errorCode, errorText, roomName) { easyrtc.showError(errorCode, errorText + ": room name was(" + roomName + ")"); }); } } function leaveRoom(roomName) { if (!roomName) { roomName = document.getElementById("roomToAdd").value; } var entry = document.getElementById(genRoomDivName(roomName)); var roomButtonHolder = document.getElementById('rooms'); easyrtc.leaveRoom(roomName, null); roomButtonHolder.removeChild(entry); } function roomEntryListener(entered, roomName) { if (entered) { // entered a room console.log("saw add of room " + roomName); addRoom(roomName, null, false); } else { var roomNode = document.getElementById(genRoomDivName(roomName)); if (roomNode) { document.getElementById('#rooms').removeChildNode(roomNode); } } refreshRoomList(); } function refreshRoomList() { if( isConnected) { easyrtc.getRoomList(addQuickJoinButtons, null); } } function peerListener(who, msgType, content, targeting) { addToConversation(who, msgType, content, targeting); } function connect() { easyrtc.setPeerListener(peerListener); easyrtc.setRoomOccupantListener(occupantListener); easyrtc.setRoomEntryListener(roomEntryListener); easyrtc.setDisconnectListener(function() { jQuery('#rooms').empty(); document.getElementById("main").className = "notconnected"; console.log("disconnect listener fired"); }); updatePresence(); var username = document.getElementById("userNameField").value; var password = document.getElementById("credentialField").value; if (username) { easyrtc.setUsername(username); } if (password) { easyrtc.setCredential({password: password}); } easyrtc.connect("easyrtc.instantMessaging", loginSuccess, loginFailure); } function disconnect() { easyrtc.disconnect(); } function addQuickJoinButtons(roomList) { var quickJoinBlock = document.getElementById("quickJoinBlock"); var n = quickJoinBlock.childNodes.length; for (var i = n - 1; i >= 0; i--) { quickJoinBlock.removeChild(quickJoinBlock.childNodes[i]); } function addQuickJoinButton(roomname, numberClients) { var checkid = "roomblock_" + roomname; if (document.getElementById(checkid)) { return; // already present so don't add again } var id = "quickjoin_" + roomname; var div = document.createElement("div"); div.id = id; div.className = "quickJoin"; var parmsField = document.getElementById("optRoomParms"); var button = document.createElement("button"); button.onclick = function() { addRoom(roomname, parmsField.value, true); refreshRoomList(); }; button.appendChild(document.createTextNode("Join " + roomname + "(" + numberClients + ")")); div.appendChild(button); quickJoinBlock.appendChild(div); } if( !roomList["room1"]) { roomList["room1"] = { numberClients:0}; } if( !roomList["room2"]) { roomList["room2"] = { numberClients:0}; } if( !roomList["room3"]) { roomList["room3"] = { numberClients:0}; } for (var roomName in roomList) { addQuickJoinButton(roomName, roomList[roomName].numberClients); } } function occupantListener(roomName, occupants, isPrimary) { if (roomName === null) { return; } var roomId = genRoomOccupantName(roomName); var roomDiv = document.getElementById(roomId); if (!roomDiv) { addRoom(roomName, "", false); roomDiv = document.getElementById(roomId); } else { jQuery(roomDiv).empty(); } for (var easyrtcid in occupants) { var button = document.createElement("button"); button.onclick = (function(roomname, easyrtcid) { return function() { sendMessage(easyrtcid, roomName); }; })(roomName, easyrtcid); var presenceText = ""; if (occupants[easyrtcid].presence) { presenceText += "("; if (occupants[easyrtcid].presence.show) { presenceText += "show=" + occupants[easyrtcid].presence.show + " "; } if (occupants[easyrtcid].presence.status) { presenceText += "status=" + occupants[easyrtcid].presence.status; } presenceText += ")"; } var label = document.createTextNode(easyrtc.idToName(easyrtcid) + presenceText); button.appendChild(label); roomDiv.appendChild(button); } refreshRoomList(); } function getGroupId() { return null; } function sendMessage(destTargetId, destRoom) { var text = document.getElementById('sendMessageText').value; if (text.replace(/\s/g, "").length === 0) { // Don't send just whitespace return; } var dest; var destGroup = getGroupId(); if (destRoom || destGroup) { dest = {}; if (destRoom) { dest.targetRoom = destRoom; } if (destGroup) { dest.targetGroup = destGroup; } if (destTargetId) { dest.targetEasyrtcid = destTargetId; } } else if (destTargetId) { dest = destTargetId; } else { easyrtc.showError("user error", "no destination selected"); return; } if( text === "empty") { easyrtc.sendPeerMessage(dest, "message"); } else { easyrtc.sendDataWS(dest, "message", text, function(reply) { if (reply.msgType === "error") { easyrtc.showError(reply.msgData.errorCode, reply.msgData.errorText); } }); } addToConversation("Me", "message", text); document.getElementById('sendMessageText').value = ""; } function loginSuccess(easyrtcid) { selfEasyrtcid = easyrtcid; document.getElementById("iam").innerHTML = "I am " + easyrtcid; refreshRoomList(); isConnected = true; displayFields(); document.getElementById("main").className = "connected"; } function displayFields() { var outstr = "Application fields<div style='margin-left:1em'>"; outstr += JSON.stringify(easyrtc.getApplicationFields()); outstr += "</div><br>"; outstr += "Session fields<div style='margin-left:1em'>"; outstr += JSON.stringify(easyrtc.getSessionFields()); outstr += "</div><br>"; outstr += "Connection fields<div style='margin-left:1em'>"; outstr += JSON.stringify(easyrtc.getConnectionFields()); outstr += "</div><br>"; var roomlist = easyrtc.getRoomsJoined(); for (var roomname in roomlist) { var roomfields = easyrtc.getRoomFields(roomname); if (roomfields != null) { outstr += "Room " + roomname + " fields<div style='margin-left:1em'>"; outstr += JSON.stringify(roomfields); outstr += "</div><br>"; } } document.getElementById('fields').innerHTML = outstr; } function loginFailure(errorCode, message) { easyrtc.showError("LOGIN-FAILURE", message); document.getElementById('connectButton').disabled = false; jQuery('#rooms').empty(); } var currentShowState = 'chat'; var currentShowText = ''; function setPresence(value) { currentShowState = value; updatePresence(); } function updatePresenceStatus(value) { currentShowText = value; updatePresence(); } function updatePresence() { easyrtc.updatePresence(currentShowState, currentShowText); } function addApiField() { var roomName = document.getElementById("apiroomname").value; var fieldname = document.getElementById("apifieldname").value; var fieldvaluetext = document.getElementById("apifieldvalue").value; var fieldvalue; if(fieldvaluetext.indexOf("{") >= 0) { fieldvalue = JSON.parse(fieldvaluetext); } else { fieldvalue = fieldvaluetext; } easyrtc.setRoomApiField(roomName, fieldname, fieldvalue); } function getIdsOfName() { var name = document.getElementById("targetName").value; var ids = easyrtc.usernameToIds(name); document.getElementById("foundIds").innerHTML = JSON.stringify(ids); }
xirsys/easyrtc
demos/js/demo_instant_messaging_rooms.js
JavaScript
bsd-2-clause
13,522
cask 'toggl' do version '7.4.68' sha256 '02ca17e1d4655a9076173eab8b04b64d768c8cc9ed5fa9e771ee1eea044b3f92' # github.com/toggl/toggldesktop was verified as official when first introduced to the cask url "https://github.com/toggl/toggldesktop/releases/download/v#{version}/TogglDesktop-#{version.dots_to_underscores}.dmg" appcast 'https://assets.toggl.com/installers/darwin_stable_appcast.xml', checkpoint: '4b7a1222c778d10db0cf1aedd6d27249fc7df625663228fc28207a2510b50dd8' name 'TogglDesktop' homepage 'https://www.toggl.com/' conflicts_with cask: [ 'toggl-beta', 'toggl-dev', ] app 'TogglDesktop.app' end
nathancahill/homebrew-cask
Casks/toggl.rb
Ruby
bsd-2-clause
709
cask "navicat-data-modeler-essentials" do version "3.0.19" sha256 :no_check url "https://download3.navicat.com/updater/modeler0#{version.major_minor.no_dots}_ess_mac_en.zip" name "Navicat Data Modeler Essentials" desc "Database design tool" homepage "https://www.navicat.com/products/navicat-data-modeler" livecheck do url "https://updater.navicat.com/mac/navicat_updates.php?appName=Navicat%20Data%20Modeler%20Essentials&appLang=en" strategy :sparkle end depends_on macos: ">= :yosemite" app "Navicat Data Modeler Essentials.app" end
scottsuch/homebrew-cask
Casks/navicat-data-modeler-essentials.rb
Ruby
bsd-2-clause
567
#include "Iop_Stdio.h" #include "Iop_Ioman.h" #include <boost/lexical_cast.hpp> #include "lexical_cast_ex.h" #include "../Log.h" #define LOG_NAME "iop_stdio" #define FUNCTION_PRINTF "printf" using namespace Iop; CStdio::CStdio(uint8* ram, CIoman& ioman) : m_ram(ram) , m_ioman(ioman) { } CStdio::~CStdio() { } std::string CStdio::GetId() const { return "stdio"; } std::string CStdio::GetFunctionName(unsigned int functionId) const { switch(functionId) { case 4: return FUNCTION_PRINTF; break; default: return "unknown"; break; } } void CStdio::Invoke(CMIPS& context, unsigned int functionId) { switch(functionId) { case 4: __printf(context); break; default: CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called. PC = (%0.8X).", functionId, context.m_State.nPC); break; } } std::string CStdio::PrintFormatted(CArgumentIterator& args) { std::string output; const char* format = reinterpret_cast<const char*>(&m_ram[args.GetNext()]); while(*format != 0) { char character = *(format++); if(character == '%') { bool paramDone = false; bool inPrecision = false; char fillChar = ' '; std::string precision; while(!paramDone && *format != 0) { char type = *(format++); if(type == '%') { output += type; paramDone = true; } else if(type == 's') { const char* text = reinterpret_cast<const char*>(&m_ram[args.GetNext()]); output += text; paramDone = true; } else if(type == 'c') { char character = static_cast<char>(args.GetNext()); output += character; paramDone = true; } else if(type == 'd' || type == 'i') { int number = args.GetNext(); unsigned int precisionValue = precision.length() ? boost::lexical_cast<unsigned int>(precision) : 1; output += lexical_cast_int<std::string>(number, precisionValue, fillChar); paramDone = true; } else if(type == 'u') { unsigned int number = args.GetNext(); unsigned int precisionValue = precision.length() ? boost::lexical_cast<unsigned int>(precision) : 1; output += lexical_cast_uint<std::string>(number, precisionValue); paramDone = true; } else if(type == 'x' || type == 'X' || type == 'p') { uint32 number = args.GetNext(); unsigned int precisionValue = precision.length() ? boost::lexical_cast<unsigned int>(precision) : 0; output += lexical_cast_hex<std::string>(number, precisionValue); paramDone = true; } else if(type == 'l') { //Length specifier, don't bother about it. } else if(type == '.') { inPrecision = true; } else { assert(isdigit(type)); if(inPrecision) { precision += type; } else { fillChar = type; inPrecision = true; } } } } else { output += character; } } return output; } void CStdio::__printf(CMIPS& context) { CArgumentIterator args(context); auto output = PrintFormatted(args); m_ioman.Write(CIoman::FID_STDOUT, output.length(), output.c_str()); }
Alloyed/Play-
Source/iop/Iop_Stdio.cpp
C++
bsd-2-clause
3,237
cask 'vmware-remote-console' do version '10.0.6,14247266' sha256 '8f1537e40b9e7a7b08015f41cdeaf537e0e07e027872e83349d6781ce6e2c84f' url "https://softwareupdate.vmware.com/cds/vmw-desktop/vmrc/#{version.before_comma}/#{version.after_comma}/macos/com.vmware.vmrc.zip.tar" appcast 'https://softwareupdate.vmware.com/cds/vmw-desktop/vmrc-macos.xml' name 'VMware Remote Console for Mac' homepage 'https://www.vmware.com/support/pubs/vmrc_pubs.html' auto_updates true container nested: 'com.vmware.vmrc.zip' app 'payload/VMware Remote Console.app' postflight do system_command "#{appdir}/VMware Remote Console.app/Contents/Library/Initialize VMRC.tool", args: ['set'], sudo: true end uninstall_preflight do set_ownership "#{appdir}/VMware Remote Console.app" end uninstall quit: 'com.vmware.vmrc' zap trash: '/Library/Logs/VMRC Services.log' end
winkelsdorf/homebrew-cask
Casks/vmware-remote-console.rb
Ruby
bsd-2-clause
923
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <sparse_helpers.hpp> #include <ArrayInfo.hpp> #include <Array.hpp> #include <backend.hpp> #include <vector> #include <cstddef> namespace common { // SparseArray Arrayementation Info class // This class is the base class to all SparseArray objects. The purpose of this class // was to have a way to retrieve basic information of an Array object without // specifying what type the object is at compile time. // // Early declaration using namespace detail; template<typename T> class SparseArray; //////////////////////////////////////////////////////////////////////////// // Sparse Array Base Class // No templates // Contains all data except values array //////////////////////////////////////////////////////////////////////////// class SparseArrayBase { private: ArrayInfo info; // This must be the first element of SparseArray<T>. af::storage stype; // Storage format: CSR, CSC, COO Array<int> rowIdx; // Linear array containing row indices Array<int> colIdx; // Linear array containing col indices public: SparseArrayBase(af::dim4 _dims, dim_t _nNZ, af::storage _storage, af_dtype _type); SparseArrayBase(af::dim4 _dims, dim_t _nNZ, const int * const _rowIdx, const int * const _colIdx, const af::storage _storage, af_dtype _type, bool _is_device = false, bool _copy_device = false); SparseArrayBase(af::dim4 _dims, const Array<int> &_rowIdx, const Array<int> &_colIdx, const af::storage _storage, af_dtype _type, bool _copy = false); ~SparseArrayBase(); //////////////////////////////////////////////////////////////////////////// // Functions that call ArrayInfo object's functions //////////////////////////////////////////////////////////////////////////// #define INSTANTIATE_INFO(return_type, func) \ return_type func() const { return info.func(); } INSTANTIATE_INFO(const af_dtype&, getType ) INSTANTIATE_INFO(size_t , elements ) INSTANTIATE_INFO(size_t , ndims ) INSTANTIATE_INFO(const af::dim4&, dims ) INSTANTIATE_INFO(size_t , total ) INSTANTIATE_INFO(int , getDevId ) INSTANTIATE_INFO(af_backend , getBackendId ) INSTANTIATE_INFO(bool , isEmpty ) INSTANTIATE_INFO(bool , isScalar ) INSTANTIATE_INFO(bool , isRow ) INSTANTIATE_INFO(bool , isColumn ) INSTANTIATE_INFO(bool , isVector ) INSTANTIATE_INFO(bool , isComplex ) INSTANTIATE_INFO(bool , isReal ) INSTANTIATE_INFO(bool , isDouble ) INSTANTIATE_INFO(bool , isSingle ) INSTANTIATE_INFO(bool , isRealFloating) INSTANTIATE_INFO(bool , isFloating ) INSTANTIATE_INFO(bool , isInteger ) INSTANTIATE_INFO(bool , isBool ) INSTANTIATE_INFO(bool , isLinear ) INSTANTIATE_INFO(bool , isSparse ) #undef INSTANTIATE_INFO // setId of info, values, rowIdx, colIdx void setId(int id) { info.setId(id); rowIdx.setId(id); colIdx.setId(id); } //////////////////////////////////////////////////////////////////////////// // Specialized functions for SparseArray //////////////////////////////////////////////////////////////////////////// // Get the internal arrays Array<int>& getRowIdx() { return rowIdx; } Array<int>& getColIdx() { return colIdx; } const Array<int>& getRowIdx() const { return rowIdx; } const Array<int>& getColIdx() const { return colIdx; } // Dims, types etc dim_t getNNZ() const; af::storage getStorage() const { return stype; } }; #if __cplusplus > 199711L static_assert(std::is_standard_layout<SparseArrayBase>::value, "SparseArrayBase must be a standard layout type"); #endif //////////////////////////////////////////////////////////////////////////// // Sparse Array Class //////////////////////////////////////////////////////////////////////////// template<typename T> class SparseArray { private: SparseArrayBase base; // This must be the first element of SparseArray<T>. Array<T> values; // Linear array containing actual values SparseArray(af::dim4 _dims, dim_t _nNZ, af::storage stype); explicit SparseArray(af::dim4 _dims, dim_t _nNZ, const T * const _values, const int * const _rowIdx, const int * const _colIdx, const af::storage _storage, bool _is_device = false, bool _copy_device = false); SparseArray(af::dim4 _dims, const Array<T> &_values, const Array<int> &_rowIdx, const Array<int> &_colIdx, const af::storage _storage, bool _copy = false); public: ~SparseArray(); //////////////////////////////////////////////////////////////////////////// // Functions that call ArrayInfo object's functions //////////////////////////////////////////////////////////////////////////// #define INSTANTIATE_INFO(return_type, func) \ return_type func() const { return base.func(); } INSTANTIATE_INFO(const af_dtype&, getType ) INSTANTIATE_INFO(size_t , elements ) INSTANTIATE_INFO(size_t , ndims ) INSTANTIATE_INFO(const af::dim4&, dims ) INSTANTIATE_INFO(size_t , total ) INSTANTIATE_INFO(int , getDevId ) INSTANTIATE_INFO(af_backend , getBackendId ) INSTANTIATE_INFO(bool , isEmpty ) INSTANTIATE_INFO(bool , isScalar ) INSTANTIATE_INFO(bool , isRow ) INSTANTIATE_INFO(bool , isColumn ) INSTANTIATE_INFO(bool , isVector ) INSTANTIATE_INFO(bool , isComplex ) INSTANTIATE_INFO(bool , isReal ) INSTANTIATE_INFO(bool , isDouble ) INSTANTIATE_INFO(bool , isSingle ) INSTANTIATE_INFO(bool , isRealFloating) INSTANTIATE_INFO(bool , isFloating ) INSTANTIATE_INFO(bool , isInteger ) INSTANTIATE_INFO(bool , isBool ) INSTANTIATE_INFO(bool , isLinear ) INSTANTIATE_INFO(bool , isSparse ) // Function from Base but not in ArrayInfo INSTANTIATE_INFO(dim_t , getNNZ ) INSTANTIATE_INFO(af::storage , getStorage) Array<int>& getRowIdx() { return base.getRowIdx(); } Array<int>& getColIdx() { return base.getColIdx(); } const Array<int>& getRowIdx() const { return base.getRowIdx(); } const Array<int>& getColIdx() const { return base.getColIdx(); } #undef INSTANTIATE_INFO void setId(int id) { base.setId(id); values.setId(id); } // Return the values array Array<T>& getValues() { return values; } const Array<T>& getValues() const { return values; } void eval() const { getValues().eval(); getRowIdx().eval(); getColIdx().eval(); } //////////////////////////////////////////////////////////////////////////// // Friend functions for Sparse Array Creation //////////////////////////////////////////////////////////////////////////// friend SparseArray<T> createEmptySparseArray<T>( const af::dim4 &_dims, dim_t _nNZ, const af::storage _storage); friend SparseArray<T> createHostDataSparseArray<T>( const af::dim4 &_dims, const dim_t nNZ, const T * const _values, const int * const _rowIdx, const int * const _colIdx, const af::storage _storage); friend SparseArray<T> createDeviceDataSparseArray<T>( const af::dim4 &_dims, const dim_t nNZ, const T * const _values, const int * const _rowIdx, const int * const _colIdx, const af::storage _storage); friend SparseArray<T> createArrayDataSparseArray<T>( const af::dim4 &_dims, const Array<T> &_values, const Array<int> &_rowIdx, const Array<int> &_colIdx, const af::storage _storage); friend SparseArray<T> *initSparseArray<T>(); friend void destroySparseArray<T>(SparseArray<T> *sparse); }; } // namespace common
marbre/arrayfire
src/backend/SparseArray.hpp
C++
bsd-3-clause
9,104
import numpy as np import pytest from numpy.testing import assert_allclose try: import scipy except ImportError: HAS_SCIPY = False else: HAS_SCIPY = True import astropy.units as u from astropy.timeseries.periodograms.lombscargle import LombScargle from astropy.timeseries.periodograms.lombscargle._statistics import (fap_single, inv_fap_single, METHODS) from astropy.timeseries.periodograms.lombscargle.utils import convert_normalization, compute_chi2_ref METHOD_KWDS = dict(bootstrap={'n_bootstraps': 20, 'random_seed': 42}) NORMALIZATIONS = ['standard', 'psd', 'log', 'model'] def make_data(N=100, period=1, theta=[10, 2, 3], dy=1, rseed=0, units=False): """Generate some data for testing""" rng = np.random.RandomState(rseed) t = 5 * period * rng.rand(N) omega = 2 * np.pi / period y = theta[0] + theta[1] * np.sin(omega * t) + theta[2] * np.cos(omega * t) dy = dy * (0.5 + rng.rand(N)) y += dy * rng.randn(N) fmax = 5 if units: return t * u.day, y * u.mag, dy * u.mag, fmax / u.day else: return t, y, dy, fmax def null_data(N=1000, dy=1, rseed=0, units=False): """Generate null hypothesis data""" rng = np.random.RandomState(rseed) t = 100 * rng.rand(N) dy = 0.5 * dy * (1 + rng.rand(N)) y = dy * rng.randn(N) fmax = 40 if units: return t * u.day, y * u.mag, dy * u.mag, fmax / u.day else: return t, y, dy, fmax @pytest.mark.parametrize('normalization', NORMALIZATIONS) @pytest.mark.parametrize('with_errors', [True, False]) @pytest.mark.parametrize('units', [False, True]) def test_distribution(normalization, with_errors, units): t, y, dy, fmax = null_data(units=units) if not with_errors: dy = None ls = LombScargle(t, y, dy, normalization=normalization) freq, power = ls.autopower(maximum_frequency=fmax) z = np.linspace(0, power.max(), 1000) # Test that pdf and cdf are consistent dz = z[1] - z[0] z_mid = z[:-1] + 0.5 * dz pdf = ls.distribution(z_mid) cdf = ls.distribution(z, cumulative=True) if isinstance(dz, u.Quantity): dz = dz.value assert_allclose(pdf, np.diff(cdf) / dz, rtol=1E-5, atol=1E-8) # psd normalization without specified errors produces bad results if not (normalization == 'psd' and not with_errors): # Test that observed power is distributed according to the theoretical pdf hist, bins = np.histogram(power, 30, density=True) midpoints = 0.5 * (bins[1:] + bins[:-1]) pdf = ls.distribution(midpoints) assert_allclose(hist, pdf, rtol=0.05, atol=0.05 * pdf[0]) @pytest.mark.parametrize('N', [10, 100, 1000]) @pytest.mark.parametrize('normalization', NORMALIZATIONS) def test_inverse_single(N, normalization): fap = np.linspace(0, 1, 11) z = inv_fap_single(fap, N, normalization) fap_out = fap_single(z, N, normalization) assert_allclose(fap, fap_out) @pytest.mark.parametrize('normalization', NORMALIZATIONS) @pytest.mark.parametrize('use_errs', [True, False]) @pytest.mark.parametrize('units', [False, True]) def test_inverse_bootstrap(normalization, use_errs, units): t, y, dy, fmax = null_data(units=units) if not use_errs: dy = None fap = np.linspace(0, 1, 11) method = 'bootstrap' method_kwds = METHOD_KWDS['bootstrap'] ls = LombScargle(t, y, dy, normalization=normalization) z = ls.false_alarm_level(fap, maximum_frequency=fmax, method=method, method_kwds=method_kwds) fap_out = ls.false_alarm_probability(z, maximum_frequency=fmax, method=method, method_kwds=method_kwds) # atol = 1 / n_bootstraps assert_allclose(fap, fap_out, atol=0.05) @pytest.mark.parametrize('method', sorted(set(METHODS) - {'bootstrap'})) @pytest.mark.parametrize('normalization', NORMALIZATIONS) @pytest.mark.parametrize('use_errs', [True, False]) @pytest.mark.parametrize('N', [10, 100, 1000]) @pytest.mark.parametrize('units', [False, True]) def test_inverses(method, normalization, use_errs, N, units, T=5): if not HAS_SCIPY and method in ['baluev', 'davies']: pytest.skip("SciPy required") t, y, dy, fmax = make_data(N, rseed=543, units=units) if not use_errs: dy = None method_kwds = METHOD_KWDS.get(method, None) fap = np.logspace(-10, 0, 11) ls = LombScargle(t, y, dy, normalization=normalization) z = ls.false_alarm_level(fap, maximum_frequency=fmax, method=method, method_kwds=method_kwds) fap_out = ls.false_alarm_probability(z, maximum_frequency=fmax, method=method, method_kwds=method_kwds) assert_allclose(fap, fap_out) @pytest.mark.parametrize('method', sorted(METHODS)) @pytest.mark.parametrize('normalization', NORMALIZATIONS) @pytest.mark.parametrize('units', [False, True]) def test_false_alarm_smoketest(method, normalization, units): if not HAS_SCIPY and method in ['baluev', 'davies']: pytest.skip("SciPy required") kwds = METHOD_KWDS.get(method, None) t, y, dy, fmax = make_data(units=units) ls = LombScargle(t, y, dy, normalization=normalization) freq, power = ls.autopower(maximum_frequency=fmax) Z = np.linspace(power.min(), power.max(), 30) fap = ls.false_alarm_probability(Z, maximum_frequency=fmax, method=method, method_kwds=kwds) assert len(fap) == len(Z) if method != 'davies': assert np.all(fap <= 1) assert np.all(fap[:-1] >= fap[1:]) # monotonically decreasing @pytest.mark.parametrize('method', sorted(METHODS)) @pytest.mark.parametrize('use_errs', [True, False]) @pytest.mark.parametrize('normalization', sorted(set(NORMALIZATIONS) - {'psd'})) @pytest.mark.parametrize('units', [False, True]) def test_false_alarm_equivalence(method, normalization, use_errs, units): # Note: the PSD normalization is not equivalent to the others, in that it # depends on the absolute errors rather than relative errors. Because the # scaling contributes to the distribution, it cannot be converted directly # from any of the three normalized versions. if not HAS_SCIPY and method in ['baluev', 'davies']: pytest.skip("SciPy required") kwds = METHOD_KWDS.get(method, None) t, y, dy, fmax = make_data(units=units) if not use_errs: dy = None ls = LombScargle(t, y, dy, normalization=normalization) freq, power = ls.autopower(maximum_frequency=fmax) Z = np.linspace(power.min(), power.max(), 30) fap = ls.false_alarm_probability(Z, maximum_frequency=fmax, method=method, method_kwds=kwds) # Compute the equivalent Z values in the standard normalization # and check that the FAP is consistent Z_std = convert_normalization(Z, len(t), from_normalization=normalization, to_normalization='standard', chi2_ref=compute_chi2_ref(y, dy)) ls = LombScargle(t, y, dy, normalization='standard') fap_std = ls.false_alarm_probability(Z_std, maximum_frequency=fmax, method=method, method_kwds=kwds) assert_allclose(fap, fap_std, rtol=0.1)
MSeifert04/astropy
astropy/timeseries/periodograms/lombscargle/tests/test_statistics.py
Python
bsd-3-clause
7,519
module Graphics.UI.Gtk.Layout.EitherWidget where import Control.Monad import Data.IORef import Graphics.UI.Gtk import System.Glib.Types data EitherWidget a b = EitherWidget Notebook (IORef EitherWidgetParams) type EitherWidgetParams = Bool instance WidgetClass (EitherWidget a b) instance ObjectClass (EitherWidget a b) instance GObjectClass (EitherWidget a b) where toGObject (EitherWidget nb _) = toGObject nb unsafeCastGObject o = EitherWidget (unsafeCastGObject o) undefined eitherWidgetNew :: (WidgetClass a, WidgetClass b) => a -> b -> IO (EitherWidget a b) eitherWidgetNew wL wR = do nb <- notebookNew _ <- notebookAppendPage nb wL "" _ <- notebookAppendPage nb wR "" notebookSetShowTabs nb False params <- newIORef True return $ EitherWidget nb params eitherWidgetLeftActivated :: Attr (EitherWidget a b) Bool eitherWidgetLeftActivated = newAttr getter setter where getter (EitherWidget _ paramsR) = readIORef paramsR setter (EitherWidget nb paramsR) v = do params <- readIORef paramsR when (v /= params) $ do let upd = if v then 0 else 1 notebookSetCurrentPage nb upd writeIORef paramsR v eitherWidgetRightActivated :: Attr (EitherWidget a b) Bool eitherWidgetRightActivated = newAttr getter setter where getter w = fmap not $ get w eitherWidgetLeftActivated setter w v = set w [ eitherWidgetLeftActivated := not v ] eitherWidgetToggle :: EitherWidget a b -> IO() eitherWidgetToggle w = set w [ eitherWidgetLeftActivated :~ not ]
keera-studios/gtk-helpers
gtk3/src/Graphics/UI/Gtk/Layout/EitherWidget.hs
Haskell
bsd-3-clause
1,612
<!DOCTYPE html> <!-- Copyright 2019 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/value/diagnostics/date_range.html"> <link rel="import" href="/tracing/value/histogram_serializer.html"> <script> 'use strict'; tr.b.unittest.testSuite(function() { test('deserialize', function() { let dr = tr.v.d.DateRange.deserialize(1496693746123); assert.strictEqual(dr.minTimestamp, 1496693746123); assert.strictEqual(dr.maxTimestamp, 1496693746123); dr = tr.v.d.DateRange.deserialize([1496693746000, 1496693746123]); assert.strictEqual(dr.minTimestamp, 1496693746000); assert.strictEqual(dr.maxTimestamp, 1496693746123); }); test('serialize', function() { const dr = new tr.v.d.DateRange(123); assert.strictEqual(dr.serialize(), 123); dr.addDiagnostic(new tr.v.d.DateRange(100)); assert.deepEqual(dr.serialize(), [100, 123]); }); }); </script>
catapult-project/catapult
tracing/tracing/value/diagnostics/date_range_test.html
HTML
bsd-3-clause
1,074
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="../../../../../tools/svgweb/src/svg.js" data-path="../../../../../tools/svgweb/src"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/> <meta name="description" content="W3C SVG 1.1 2nd Edition SVGWeb Test Suite"/> <title> SVG 1.1 2nd Edition Test (svgweb): text-altglyph-01-b.svg </title> <style type="text/css"> <!-- .bodytext { font-family:verdana, helvetica, sans-serif; font-size: 12pt; line-height: 125%; text-align: Left; margin-top: 0; margin-bottom: 0 } .pageTitle { line-height: 150%; font-size: 20pt; font-weight : 900; margin-bottom: 20pt } .pageSubTitle { color : blue; line-height: 100%; font-size: 24pt; font-weight : 900 } .openChapter { color : blue; line-height: 125%; font-weight : 900 } .openSection { color : blue; line-height: 125%; font-weight : 900 } .info { color : black; line-height: 110%; font-size: 10pt; font-weight : 100 } p { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } blockquote { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } .opscript { margin-left: 3%; margin-right: 3%; } .opscript p { margin-top: 0.7em } .navbar { background: black; color: white; font-weight: bold } .warning { color: red; text-align: Center;} a,a:visited { color: blue } --> </style> <link rel="prev" href="text-align-08-b.html" /> <link rel="index" href="index.html" /> <link rel="next" href="text-altglyph-02-b.html" /> <script src="../resources/testharnessreport.js"></script> </head> <body class="bodytext"> <div class="linkbar"> <p>Specification link: <a target="spec" href="http://www.w3.org/TR/SVG11/text.html#AlternateGlyphs">10.14 Alternate glyphs</a></p> <p> <a href="text-align-08-b.html" rel="prev">text-align-08-b ←</a> <a href="index.html" rel="index">index</a> <a href="text-altglyph-02-b.html" rel="next">→ text-altglyph-02-b</a> </p> </div> <div> <br /> <p class="warning"> Tests that contain the draft-watermark are under development and may be incorrectly testing a feature. </p> </div> <table align="center" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center" colspan="3"> <table border="0" cellpadding="8"> <tr> <td align="center" colspan="2" class="pageTitle"> <h1>text-altglyph-01-b.svg</h1> </td> </tr> <tr class="navbar"> <td align="center"> SVG Image </td> <td align="center"> PNG Image </td> </tr> <tr> <td align="right"> <!--[if IE]> <object src="../../svg/text-altglyph-01-b.svg" width="480" height="360" classid="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p> <![endif]--> <!--[if !IE]>--> <object data="../../svg/text-altglyph-01-b.svg" width="480" height="360" type="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p> <!--<![endif]--> </object> </td> <td align="left"> <img alt="raster image of text-altglyph-01-b.svg" src="../../png/text-altglyph-01-b.png" width="480" height="360"/> </td> </tr> </table> </td> </tr> </table> <div class="opscript"> <h2 id="operatorscript"> Operator Script </h2> <div> <p> Run the test. No interaction required. </p><p> This test requires some support for SVG fonts. </p> </div> <h2 id="passcriteria"> Pass Criteria </h2> <div> <p> Three text strings show: the word "HAPPY" in pink, the word "SAD" in green and the word "SASSY" in blue. </p><p> The "HAPPY" and "SAD" strings test the 'altGlyph' facility and the ability to map multiple glyphs to a single character. All characters except the "D" are bracketed by 'altGlyph' elements to use two different glyphs to render each character. For "HAPPY", the horizontal stroke through the center of the characters is a smile stroke. For "SAD", the horizontal stroke through the center of the characters is a frown stroke. </p><p> The "SASSY" string tests a single glyph representing multiple characters (a ligature). The SVG font in the test case contains an "SS" ligature so that the "SS" in "SASSY" is rendered with a single glyph, where the two parts of the "SS" are connected. </p> </div> <h2 id="testdescription"> Test Description </h2> <div> <p> Test 'altGlyph' facilities and many-to-many chars to glyphs. </p> </div> </div> <br/> <div class="linkbar"> <p> <a href="text-align-08-b.html" rel="prev">text-align-08-b ←</a> <a href="index.html" rel="index">index</a> <a href="text-altglyph-02-b.html" rel="next">→ text-altglyph-02-b</a> </p> </div> </body> </html>
frivoal/presto-testo
SVG/Testsuites/W3C-1_1F2/harness/htmlSVGWeb/text-altglyph-01-b.html
HTML
bsd-3-clause
5,458
--- title: 100 doors localeTitle: 100 portas --- ## 100 portas Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/100-doors/index.md) . [Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .
otavioarc/freeCodeCamp
guide/portuguese/certifications/coding-interview-prep/rosetta-code/100-doors/index.md
Markdown
bsd-3-clause
418
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import time import unittest import node LEADER = 1 ROUTER1 = 2 ROUTER2 = 3 ED = 4 SED = 5 MTDS = [ED, SED] class Cert_5_6_9_NetworkDataForwarding(unittest.TestCase): def setUp(self): self.nodes = {} for i in range(1,6): self.nodes[i] = node.Node(i, (i in MTDS)) self.nodes[LEADER].set_panid(0xface) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64()) self.nodes[LEADER].enable_whitelist() self.nodes[ROUTER1].set_panid(0xface) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[ED].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[SED].get_addr64()) self.nodes[ROUTER1].enable_whitelist() self.nodes[ROUTER1].set_router_selection_jitter(1) self.nodes[ROUTER2].set_panid(0xface) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) self.nodes[ED].set_panid(0xface) self.nodes[ED].set_mode('rsn') self.nodes[ED].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[ED].enable_whitelist() self.nodes[SED].set_panid(0xface) self.nodes[SED].set_mode('s') self.nodes[SED].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[SED].enable_whitelist() self.nodes[SED].set_timeout(3) def tearDown(self): for node in list(self.nodes.values()): node.stop() del self.nodes def test(self): self.nodes[LEADER].start() self.nodes[LEADER].set_state('leader') self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[ROUTER1].start() time.sleep(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') self.nodes[ROUTER2].start() time.sleep(5) self.assertEqual(self.nodes[ROUTER2].get_state(), 'router') self.nodes[ED].start() time.sleep(5) self.assertEqual(self.nodes[ED].get_state(), 'child') self.nodes[SED].start() time.sleep(5) self.assertEqual(self.nodes[SED].get_state(), 'child') self.nodes[LEADER].add_prefix('2001:2:0:1::/64', 'paros', 'med') self.nodes[LEADER].add_route('2001:2:0:2::/64', 'med') self.nodes[LEADER].register_netdata() time.sleep(10) self.nodes[ROUTER2].add_prefix('2001:2:0:1::/64', 'paros', 'low') self.nodes[ROUTER2].add_route('2001:2:0:2::/64', 'high') self.nodes[ROUTER2].register_netdata() time.sleep(10) self.assertFalse(self.nodes[SED].ping('2001:2:0:2::1')) self.assertFalse(self.nodes[SED].ping('2007::1')) self.nodes[ROUTER2].remove_prefix('2001:2:0:1::/64') self.nodes[ROUTER2].add_prefix('2001:2:0:1::/64', 'paros', 'high') self.nodes[ROUTER2].register_netdata() time.sleep(10) self.assertFalse(self.nodes[SED].ping('2007::1')) self.nodes[ROUTER2].remove_prefix('2001:2:0:1::/64') self.nodes[ROUTER2].add_prefix('2001:2:0:1::/64', 'paros', 'med') self.nodes[ROUTER2].register_netdata() time.sleep(10) self.assertFalse(self.nodes[SED].ping('2007::1')) if __name__ == '__main__': unittest.main()
vaas-krish/openthread
tests/scripts/thread-cert/Cert_5_6_09_NetworkDataForwarding.py
Python
bsd-3-clause
5,202
{% load url from future %} {% load reviews_tags %} {% load i18n %} <article class="review"> <header> <h3 class="star-rating {{ review.score|as_stars }}"> <span> <i class="icon-star"></i> <i class="icon-star"></i> <i class="icon-star"></i> <i class="icon-star"></i> <i class="icon-star"></i> </span> <a href="{{ review.get_absolute_url }}">{{ review.title }}</a> </h3> </header> <p>{{ review.body|striptags }}</p> <p> <small> {% if review.user == user %} {% blocktrans with review_date=review.date_created %} Reviewed by you on {{ review_date }} {% endblocktrans %} {% else %} {% blocktrans with name=review.reviewer_name review_date=review.date_created %} Reviewed by <strong>{{ name }}</strong> on {{ review_date }} {% endblocktrans %} {% endif %} | <a href="{% url 'catalogue:reviews-detail' product_slug=product.slug product_pk=product.pk pk=review.pk %}">{% trans 'Permalink' %}</a> </small> </p> {% if review|may_vote:user %} <small>{% trans "Is this review helpful?" %}</small> <form action="{% url 'catalogue:reviews-vote' product_slug=product.slug product_pk=product.pk pk=review.pk %}" method="post" class="vote_agree" > {% csrf_token %} <input type="hidden" name="delta" value="1"/> <button type="submit" class="btn btn-success btn-mini">{% trans "Yes" %}</button> </form> <form action="{% url 'catalogue:reviews-vote' product_slug=product.slug product_pk=product.pk pk=review.pk %}" method="post"> {% csrf_token %} <input type="hidden" name="delta" value="-1"/> <button type="submit" class="btn btn-danger btn-mini">{% trans "No" %}</button> </form> {% endif %} <p> <small> {% if review.has_votes %} {% blocktrans with num_up_votes=review.num_up_votes count num_votes=review.total_votes %} <strong>{{ num_up_votes }}</strong> of 1 customer found this useful {% plural %} <strong>{{ num_up_votes }}</strong> of {{ num_votes }} customers found this useful {% endblocktrans %} {% else %} This review has no votes. {% endif %} </small> </p> </article>
Giftingnation/GN-Oscar-Custom
oscar/templates/oscar/catalogue/partials/review.html
HTML
bsd-3-clause
2,537
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPERSISTABLE_H #define BERRYIPERSISTABLE_H #include <org_blueberry_ui_qt_Export.h> #include <berrySmartPointer.h> namespace berry { struct IMemento; /** * Objects implementing this interface are capable of saving their * state in an {@link IMemento}. */ struct BERRY_UI_QT IPersistable { virtual ~IPersistable(); /** * Saves the state of the object in the given memento. * * @param memento the storage area for object's state */ virtual void SaveState(const SmartPointer<IMemento>& memento) const = 0; }; } #endif // BERRYIPERSISTABLE_H
ireicht/MITK-CSI
Plugins/org.blueberry.ui.qt/src/berryIPersistable.h
C
bsd-3-clause
1,052
<?php // Version: 1.1; Modlog $txt['modlog_date'] = 'Date'; $txt['modlog_member'] = 'Member'; $txt['modlog_position'] = 'Position'; $txt['modlog_action'] = 'Action'; $txt['modlog_ip'] = 'IP'; $txt['modlog_search_result'] = 'Search Results'; $txt['modlog_total_entries'] = 'Total Entries'; $txt['modlog_ac_approve_topic'] = 'Approved topic &quot;{topic}&quot; by &quot;{member}&quot;'; $txt['modlog_ac_unapprove_topic'] = 'Unapproved topic &quot;{topic}&quot; by &quot;{member}&quot;'; $txt['modlog_ac_approve'] = 'Approved message &quot;{subject}&quot; in &quot;{topic}&quot; by &quot;{member}&quot;'; $txt['modlog_ac_unapprove'] = 'Unapproved message &quot;{subject}&quot; in &quot;{topic}&quot; by &quot;{member}&quot;'; $txt['modlog_ac_lock'] = 'Locked &quot;{topic}&quot;'; $txt['modlog_ac_warning'] = 'Warned {member} for &quot;{message}&quot;'; $txt['modlog_ac_unlock'] = 'Unlocked &quot;{topic}&quot;'; $txt['modlog_ac_sticky'] = 'Pinned &quot;{topic}&quot;'; $txt['modlog_ac_unsticky'] = 'Unpinned &quot;{topic}&quot;'; $txt['modlog_ac_delete'] = 'Deleted &quot;{subject}&quot; by &quot;{member}&quot; from &quot;{topic}&quot;'; $txt['modlog_ac_delete_member'] = 'Deleted member &quot;{name}&quot;'; $txt['modlog_ac_remove'] = 'Removed topic &quot;{topic}&quot; from &quot;{board}&quot;'; $txt['modlog_ac_modify'] = 'Edited &quot;{message}&quot; by &quot;{member}&quot;'; $txt['modlog_ac_merge'] = 'Merged topics to create &quot;{topic}&quot;'; $txt['modlog_ac_split'] = 'Split &quot;{topic}&quot; to create &quot;{new_topic}&quot;'; $txt['modlog_ac_move'] = 'Moved &quot;{topic}&quot; from &quot;{board_from}&quot; to &quot;{board_to}&quot;'; $txt['modlog_ac_profile'] = 'Edit the profile of &quot;{member}&quot;'; $txt['modlog_ac_pruned'] = 'Pruned some posts older than {days} days'; $txt['modlog_ac_news'] = 'Edited the news'; $txt['modlog_enter_comment'] = 'Enter Moderation Comment'; $txt['modlog_moderation_log'] = 'Moderation Log'; $txt['modlog_moderation_log_desc'] = 'Below is a list of all the moderation actions that have been carried out by moderators of the forum.<br /><strong>Please note:</strong> Entries cannot be removed from this log until they are at least twenty-four hours old.'; $txt['modlog_no_entries_found'] = 'There are currently no moderation log entries.'; $txt['modlog_remove'] = 'Delete Selected'; $txt['modlog_removeall'] = 'Clear Log'; $txt['modlog_remove_selected_confirm'] = 'Are you sure you want to delete the selected log entries?'; $txt['modlog_remove_all_confirm'] = 'Are you sure you want to completely clear the log?'; $txt['modlog_go'] = 'Go'; $txt['modlog_add'] = 'Add'; $txt['modlog_search'] = 'Quick Search'; $txt['modlog_by'] = 'By'; $txt['modlog_id'] = '<em>Deleted - ID:%1$d</em>'; $txt['modlog_ac_add_warn_template'] = 'Added warning template: &quot;{template}&quot;'; $txt['modlog_ac_modify_warn_template'] = 'Edited the warning template: &quot;{template}&quot;'; $txt['modlog_ac_delete_warn_template'] = 'Deleted the warning template: &quot;{template}&quot;'; $txt['modlog_ac_ban'] = 'Added ban triggers:'; $txt['modlog_ac_ban_update'] = 'Edited ban triggers:'; $txt['modlog_ac_ban_remove'] = 'Removed ban triggers:'; $txt['modlog_ac_ban_trigger_member'] = ' <em>Member:</em> {member}'; $txt['modlog_ac_ban_trigger_email'] = ' <em>Email:</em> {email}'; $txt['modlog_ac_ban_trigger_ip_range'] = ' <em>IP:</em> {ip_range}'; $txt['modlog_ac_ban_trigger_hostname'] = ' <em>Hostname:</em> {hostname}'; $txt['modlog_admin_log'] = 'Administration Log'; $txt['modlog_admin_log_desc'] = 'Below is a list of administration actions which have been logged on your forum.<br /><strong>Please note:</strong> Entries cannot be removed from this log until they are at least twenty-four hours old.'; $txt['modlog_admin_log_no_entries_found'] = 'There are currently no administration log entries.'; // Admin type strings. $txt['modlog_ac_upgrade'] = 'Upgraded the forum to version {version}'; $txt['modlog_ac_install'] = 'Installed version {version}'; $txt['modlog_ac_add_board'] = 'Added a new board: &quot;{board}&quot;'; $txt['modlog_ac_edit_board'] = 'Edited the &quot;{board}&quot; board'; $txt['modlog_ac_delete_board'] = 'Deleted the &quot;{boardname}&quot; board'; $txt['modlog_ac_add_cat'] = 'Added a new category, &quot;{catname}&quot;'; $txt['modlog_ac_edit_cat'] = 'Edited the &quot;{catname}&quot; category'; $txt['modlog_ac_delete_cat'] = 'Deleted the &quot;{catname}&quot; category'; $txt['modlog_ac_delete_group'] = 'Deleted the &quot;{group}&quot; group'; $txt['modlog_ac_add_group'] = 'Added the &quot;{group}&quot; group'; $txt['modlog_ac_edited_group'] = 'Edited the &quot;{group}&quot; group'; $txt['modlog_ac_added_to_group'] = 'Added &quot;{member}&quot; to the &quot;{group}&quot; group'; $txt['modlog_ac_removed_from_group'] = 'Removed &quot;{member}&quot; from the &quot;{group}&quot; group'; $txt['modlog_ac_removed_all_groups'] = 'Removed &quot;{member}&quot; from all groups'; $txt['modlog_ac_remind_member'] = 'Sent out a reminder to &quot;{member}&quot; to activate their account'; $txt['modlog_ac_approve_member'] = 'Approved/Activated the account of &quot;{member}&quot;'; $txt['modlog_ac_newsletter'] = 'Sent Newsletter'; $txt['modlog_ac_install_package'] = 'Installed new package: &quot;{package}&quot;, version {version}'; $txt['modlog_ac_upgrade_package'] = 'Upgraded package: &quot;{package}&quot; to version {version}'; $txt['modlog_ac_uninstall_package'] = 'Uninstalled package: &quot;{package}&quot;, version {version}'; $txt['modlog_ac_database_backup'] = 'Database backup taken by {member}.'; $txt['modlog_ac_editing_theme'] = '{member} edited a theme.'; // Restore topic. $txt['modlog_ac_restore_topic'] = 'Restored topic &quot;{topic}&quot; from &quot;{board}&quot; to &quot;{board_to}&quot;'; $txt['modlog_ac_restore_posts'] = 'Restored posts from &quot;{subject}&quot; to the topic &quot;{topic}&quot; in the &quot;{board}&quot; board.'; $txt['modlog_parameter_guest'] = '<em>Guest</em>'; $txt['modlog_ac_approve_attach'] = 'Approved &quot;{filename}&quot; in &quot;{message}&quot;'; $txt['modlog_ac_remove_attach'] = 'Removed unapproved &quot;{filename}&quot; in &quot;{message}&quot;';
nwsw/Elkarte
themes/default/languages/english/Modlog.english.php
PHP
bsd-3-clause
6,189
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <script src="../../resources/js-test.js"></script> </head> <body> <p id="description"></p> <div id="console"></div> <script> description('Tests for tooLong flag with &lt;input> elements.'); var input = document.createElement('input'); document.body.appendChild(input); debug('No maxlength and no value'); shouldBeFalse('input.validity.tooLong'); debug(''); debug('Non-dirty value'); input.setAttribute('value', 'abcde'); input.maxLength = 3; shouldBe('input.value.length', '5'); shouldBeFalse('input.validity.tooLong'); input.setAttribute('value', 'abcdef'); shouldBe('input.value.length', '6'); shouldBeFalse('input.validity.tooLong'); debug(''); debug('Dirty value and longer than maxLength'); input = document.createElement('input'); document.body.appendChild(input); input.setAttribute('value', 'abcde'); input.maxLength = 3; input.focus(); input.setSelectionRange(5, 5); // Move the cursor at the end. document.execCommand('delete'); shouldBe('input.value.length', '4'); shouldBeTrue('input.validity.tooLong'); // Make the value <=maxLength. document.execCommand('delete'); shouldBeFalse('input.validity.tooLong'); debug(''); debug('Sets a value via DOM property'); input.maxLength = 3; input.value = 'abcde'; shouldBeFalse('input.validity.tooLong'); debug(''); debug('Disabled'); input.disabled = true; shouldBeFalse('input.validity.tooLong'); input.disabled = false; debug(''); debug('Grapheme length is not greater than maxLength though character length is greater'); // fancyX should be treated as 1 grapheme. // U+0305 COMBINING OVERLINE // U+0332 COMBINING LOW LINE var fancyX = "x\u0305\u0332"; input = document.createElement('input'); document.body.appendChild(input); input.value = fancyX; // 3 characters, 1 grapheme clusters. input.maxLength = 1; shouldBeFalse('input.validity.tooLong'); debug(''); debug('Change the type with a too long value'); input.maxLength = 3; input.value = 'abcde'; input.type = 'search'; input.focus(); input.setSelectionRange(5, 5); document.execCommand('delete'); shouldBeTrue('input.validity.tooLong'); shouldBeFalse('input.type = "number"; input.validity.tooLong'); </script> </body> </html>
hgl888/blink-crosswalk-efl
LayoutTests/fast/forms/ValidityState-tooLong-input.html
HTML
bsd-3-clause
2,209
#ifndef AUDIO_DIRECT_H #define AUDIO_DIRECT_H /****************** Include Files ********************/ #include "xil_types.h" #include "xstatus.h" #define AUDIO_DIRECT_S_AXI_SLV_REG0_OFFSET 0 #define AUDIO_DIRECT_S_AXI_SLV_REG1_OFFSET 4 #define AUDIO_DIRECT_S_AXI_SLV_REG2_OFFSET 8 #define AUDIO_DIRECT_S_AXI_SLV_REG3_OFFSET 12 #define AUDIO_DIRECT_S_AXI_SLV_REG4_OFFSET 16 #define AUDIO_DIRECT_S_AXI_SLV_REG5_OFFSET 20 /**************************** Type Definitions *****************************/ /** * * Write a value to a AUDIO_DIRECT register. A 32 bit write is performed. * If the component is implemented in a smaller width, only the least * significant data is written. * * @param BaseAddress is the base address of the AUDIO_DIRECTdevice. * @param RegOffset is the register offset from the base to write to. * @param Data is the data written to the register. * * @return None. * * @note * C-style signature: * void AUDIO_DIRECT_mWriteReg(u32 BaseAddress, unsigned RegOffset, u32 Data) * */ #define AUDIO_DIRECT_mWriteReg(BaseAddress, RegOffset, Data) \ Xil_Out32((BaseAddress) + (RegOffset), (u32)(Data)) /** * * Read a value from a AUDIO_DIRECT register. A 32 bit read is performed. * If the component is implemented in a smaller width, only the least * significant data is read from the register. The most significant data * will be read as 0. * * @param BaseAddress is the base address of the AUDIO_DIRECT device. * @param RegOffset is the register offset from the base to write to. * * @return Data is the data from the register. * * @note * C-style signature: * u32 AUDIO_DIRECT_mReadReg(u32 BaseAddress, unsigned RegOffset) * */ #define AUDIO_DIRECT_mReadReg(BaseAddress, RegOffset) \ Xil_In32((BaseAddress) + (RegOffset)) /************************** Function Prototypes ****************************/ /** * * Run a self-test on the driver/device. Note this may be a destructive test if * resets of the device are performed. * * If the hardware system is not built correctly, this function may never * return to the caller. * * @param baseaddr_p is the base address of the AUDIO_DIRECT instance to be worked on. * * @return * * - XST_SUCCESS if all self-test code passed * - XST_FAILURE if any self-test code failed * * @note Caching must be turned off for this function to work. * @note Self test may fail if data memory and device are not on the same bus. * */ XStatus AUDIO_DIRECT_Reg_SelfTest(void * baseaddr_p); #endif // AUDIO_DIRECT_H
schelleg/PYNQ
boards/ip/audio_direct_1.1/drivers/audio_direct_v1_0/src/audio_direct.h
C
bsd-3-clause
2,552
from rlpy.Representations import IndependentDiscretization from rlpy.Domains import GridWorld, InfiniteTrackCartPole import numpy as np from rlpy.Tools import __rlpy_location__ import os def test_number_of_cells(): """ Ensure create appropriate # of cells (despite ``discretization``) """ mapDir = os.path.join(__rlpy_location__, "Domains", "GridWorldMaps") mapname=os.path.join(mapDir, "4x5.txt") # expect 4*5 = 20 states domain = GridWorld(mapname=mapname) rep = IndependentDiscretization(domain, discretization=100) assert rep.features_num == 9 rep = IndependentDiscretization(domain, discretization=5) assert rep.features_num == 9 def test_phi_cells(): """ Ensure correct features are activated for corresponding state """ mapDir = os.path.join(__rlpy_location__, "Domains", "GridWorldMaps") mapname=os.path.join(mapDir, "4x5.txt") # expect 4*5 = 20 states domain = GridWorld(mapname=mapname) rep = IndependentDiscretization(domain) for r in np.arange(4): for c in np.arange(5): phiVec = rep.phi(np.array([r,c]), terminal=False) assert sum(phiVec) == 2 # 1 for each dimension assert phiVec[r] == 1 # correct row activated assert phiVec[4+c] == 1 # correct col activated def test_continuous_discr(): """ Ensure correct discretization in continuous state spaces """ # NOTE - if possible, test a domain with mixed discr/continuous domain = InfiniteTrackCartPole.InfTrackCartPole() #2 continuous dims rep = IndependentDiscretization(domain, discretization=20) assert rep.features_num == 40 rep = IndependentDiscretization(domain, discretization=50) assert rep.features_num == 100
imanolarrieta/RL
tests/test_representations/test_IndependentDiscretization.py
Python
bsd-3-clause
1,739
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.Timer; /** * * @author 997robotics4 */ public class UnLatchCommand extends CommandBase { Timer myTimer = new Timer(); public UnLatchCommand() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); requires(subShooter); } // Called just before this Command runs the first time protected void initialize() { myTimer.reset(); myTimer.start(); } // Called repeatedly when this Command is scheduled to run protected void execute() { subShooter.unLatch(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return myTimer.get()>1; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Team997Coders/Cynder2014
src/edu/wpi/first/wpilibj/templates/commands/UnLatchCommand.java
Java
bsd-3-clause
1,283
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//CL//DTD XHTML 1.0 Transitional plus Embed//EN" "http://www.w3.org/Graphics/xhtml1-transitional-plus-embed.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/> <meta name="description" content="W3C SVG 1.1 2nd Edition Embedded Test Suite"/> <title> SVG 1.1 2nd Edition Test Suite &lt;embed&gt; </title> <style type="text/css"> <!-- .bodytext { font-family:verdana, helvetica, sans-serif; font-size: 12pt; line-height: 125%; text-align: Left; margin-top: 0; margin-bottom: 0 } .pageTitle { line-height: 150%; font-size: 20pt; font-weight : 900; margin-bottom: 20pt } .pageSubTitle { color : blue; line-height: 100%; font-size: 24pt; font-weight : 900 } .openChapter { color : blue; line-height: 125%; font-weight : 900 } .openSection { color : blue; line-height: 125%; font-weight : 900 } .info { color : black; line-height: 110%; font-size: 10pt; font-weight : 100 } p { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } blockquote { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } .opscript { margin-left: 3%; margin-right: 3%; } .opscript p { margin-top: 0.7em } .navbar { background: black; color: white; font-weight: bold } .warning { color: red; text-align: Center;} a,a:visited { color: blue } --> </style> </head> <body class="bodytext"> <h1 class="pageTitle">SVG 1.1 2nd Edition Test Suite &lt;embed&gt;</h1> <p>Below are the list of tests in the SVG 1.1 2nd Edition Test Suite &lt;embed&gt;. Each test has a link to different versions as well as navigation.</p> <ol> <li><a href="animate-dom-01-f.html">animate-dom-01-f.svg</a></li> <li><a href="animate-dom-02-f.html">animate-dom-02-f.svg</a></li> <li><a href="animate-elem-02-t.html">animate-elem-02-t.svg</a></li> <li><a href="animate-elem-03-t.html">animate-elem-03-t.svg</a></li> <li><a href="animate-elem-04-t.html">animate-elem-04-t.svg</a></li> <li><a href="animate-elem-05-t.html">animate-elem-05-t.svg</a></li> <li><a href="animate-elem-06-t.html">animate-elem-06-t.svg</a></li> <li><a href="animate-elem-07-t.html">animate-elem-07-t.svg</a></li> <li><a href="animate-elem-08-t.html">animate-elem-08-t.svg</a></li> <li><a href="animate-elem-09-t.html">animate-elem-09-t.svg</a></li> <li><a href="animate-elem-10-t.html">animate-elem-10-t.svg</a></li> <li><a href="animate-elem-11-t.html">animate-elem-11-t.svg</a></li> <li><a href="animate-elem-12-t.html">animate-elem-12-t.svg</a></li> <li><a href="animate-elem-13-t.html">animate-elem-13-t.svg</a></li> <li><a href="animate-elem-14-t.html">animate-elem-14-t.svg</a></li> <li><a href="animate-elem-15-t.html">animate-elem-15-t.svg</a></li> <li><a href="animate-elem-17-t.html">animate-elem-17-t.svg</a></li> <li><a href="animate-elem-19-t.html">animate-elem-19-t.svg</a></li> <li><a href="animate-elem-20-t.html">animate-elem-20-t.svg</a></li> <li><a href="animate-elem-21-t.html">animate-elem-21-t.svg</a></li> <li><a href="animate-elem-22-b.html">animate-elem-22-b.svg</a></li> <li><a href="animate-elem-23-t.html">animate-elem-23-t.svg</a></li> <li><a href="animate-elem-24-t.html">animate-elem-24-t.svg</a></li> <li><a href="animate-elem-25-t.html">animate-elem-25-t.svg</a></li> <li><a href="animate-elem-26-t.html">animate-elem-26-t.svg</a></li> <li><a href="animate-elem-27-t.html">animate-elem-27-t.svg</a></li> <li><a href="animate-elem-28-t.html">animate-elem-28-t.svg</a></li> <li><a href="animate-elem-29-b.html">animate-elem-29-b.svg</a></li> <li><a href="animate-elem-30-t.html">animate-elem-30-t.svg</a></li> <li><a href="animate-elem-31-t.html">animate-elem-31-t.svg</a></li> <li><a href="animate-elem-32-t.html">animate-elem-32-t.svg</a></li> <li><a href="animate-elem-33-t.html">animate-elem-33-t.svg</a></li> <li><a href="animate-elem-34-t.html">animate-elem-34-t.svg</a></li> <li><a href="animate-elem-35-t.html">animate-elem-35-t.svg</a></li> <li><a href="animate-elem-36-t.html">animate-elem-36-t.svg</a></li> <li><a href="animate-elem-37-t.html">animate-elem-37-t.svg</a></li> <li><a href="animate-elem-38-t.html">animate-elem-38-t.svg</a></li> <li><a href="animate-elem-39-t.html">animate-elem-39-t.svg</a></li> <li><a href="animate-elem-40-t.html">animate-elem-40-t.svg</a></li> <li><a href="animate-elem-41-t.html">animate-elem-41-t.svg</a></li> <li><a href="animate-elem-44-t.html">animate-elem-44-t.svg</a></li> <li><a href="animate-elem-46-t.html">animate-elem-46-t.svg</a></li> <li><a href="animate-elem-52-t.html">animate-elem-52-t.svg</a></li> <li><a href="animate-elem-53-t.html">animate-elem-53-t.svg</a></li> <li><a href="animate-elem-60-t.html">animate-elem-60-t.svg</a></li> <li><a href="animate-elem-61-t.html">animate-elem-61-t.svg</a></li> <li><a href="animate-elem-62-t.html">animate-elem-62-t.svg</a></li> <li><a href="animate-elem-63-t.html">animate-elem-63-t.svg</a></li> <li><a href="animate-elem-64-t.html">animate-elem-64-t.svg</a></li> <li><a href="animate-elem-65-t.html">animate-elem-65-t.svg</a></li> <li><a href="animate-elem-66-t.html">animate-elem-66-t.svg</a></li> <li><a href="animate-elem-67-t.html">animate-elem-67-t.svg</a></li> <li><a href="animate-elem-68-t.html">animate-elem-68-t.svg</a></li> <li><a href="animate-elem-69-t.html">animate-elem-69-t.svg</a></li> <li><a href="animate-elem-70-t.html">animate-elem-70-t.svg</a></li> <li><a href="animate-elem-77-t.html">animate-elem-77-t.svg</a></li> <li><a href="animate-elem-78-t.html">animate-elem-78-t.svg</a></li> <li><a href="animate-elem-80-t.html">animate-elem-80-t.svg</a></li> <li><a href="animate-elem-81-t.html">animate-elem-81-t.svg</a></li> <li><a href="animate-elem-82-t.html">animate-elem-82-t.svg</a></li> <li><a href="animate-elem-83-t.html">animate-elem-83-t.svg</a></li> <li><a href="animate-elem-84-t.html">animate-elem-84-t.svg</a></li> <li><a href="animate-elem-85-t.html">animate-elem-85-t.svg</a></li> <li><a href="animate-elem-86-t.html">animate-elem-86-t.svg</a></li> <li><a href="animate-elem-87-t.html">animate-elem-87-t.svg</a></li> <li><a href="animate-elem-88-t.html">animate-elem-88-t.svg</a></li> <li><a href="animate-elem-89-t.html">animate-elem-89-t.svg</a></li> <li><a href="animate-elem-90-b.html">animate-elem-90-b.svg</a></li> <li><a href="animate-elem-91-t.html">animate-elem-91-t.svg</a></li> <li><a href="animate-elem-92-t.html">animate-elem-92-t.svg</a></li> <li><a href="animate-interact-events-01-t.html">animate-interact-events-01-t.svg</a></li> <li><a href="animate-interact-pevents-01-t.html">animate-interact-pevents-01-t.svg</a></li> <li><a href="animate-interact-pevents-02-t.html">animate-interact-pevents-02-t.svg</a></li> <li><a href="animate-interact-pevents-03-t.html">animate-interact-pevents-03-t.svg</a></li> <li><a href="animate-interact-pevents-04-t.html">animate-interact-pevents-04-t.svg</a></li> <li><a href="animate-pservers-grad-01-b.html">animate-pservers-grad-01-b.svg</a></li> <li><a href="animate-script-elem-01-b.html">animate-script-elem-01-b.svg</a></li> <li><a href="animate-struct-dom-01-b.html">animate-struct-dom-01-b.svg</a></li> <li><a href="color-prof-01-f.html">color-prof-01-f.svg</a></li> <li><a href="color-prop-01-b.html">color-prop-01-b.svg</a></li> <li><a href="color-prop-02-f.html">color-prop-02-f.svg</a></li> <li><a href="color-prop-03-t.html">color-prop-03-t.svg</a></li> <li><a href="color-prop-04-t.html">color-prop-04-t.svg</a></li> <li><a href="color-prop-05-t.html">color-prop-05-t.svg</a></li> <li><a href="conform-viewers-01-t.html">conform-viewers-01-t.svgz</a></li> <li><a href="conform-viewers-02-f.html">conform-viewers-02-f.svg</a></li> <li><a href="conform-viewers-03-f.html">conform-viewers-03-f.svg</a></li> <li><a href="coords-coord-01-t.html">coords-coord-01-t.svg</a></li> <li><a href="coords-coord-02-t.html">coords-coord-02-t.svg</a></li> <li><a href="coords-dom-01-f.html">coords-dom-01-f.svg</a></li> <li><a href="coords-dom-02-f.html">coords-dom-02-f.svg</a></li> <li><a href="coords-dom-03-f.html">coords-dom-03-f.svg</a></li> <li><a href="coords-dom-04-f.html">coords-dom-04-f.svg</a></li> <li><a href="coords-trans-01-b.html">coords-trans-01-b.svg</a></li> <li><a href="coords-trans-02-t.html">coords-trans-02-t.svg</a></li> <li><a href="coords-trans-03-t.html">coords-trans-03-t.svg</a></li> <li><a href="coords-trans-04-t.html">coords-trans-04-t.svg</a></li> <li><a href="coords-trans-05-t.html">coords-trans-05-t.svg</a></li> <li><a href="coords-trans-06-t.html">coords-trans-06-t.svg</a></li> <li><a href="coords-trans-07-t.html">coords-trans-07-t.svg</a></li> <li><a href="coords-trans-08-t.html">coords-trans-08-t.svg</a></li> <li><a href="coords-trans-09-t.html">coords-trans-09-t.svg</a></li> <li><a href="coords-trans-10-f.html">coords-trans-10-f.svg</a></li> <li><a href="coords-trans-11-f.html">coords-trans-11-f.svg</a></li> <li><a href="coords-trans-12-f.html">coords-trans-12-f.svg</a></li> <li><a href="coords-trans-13-f.html">coords-trans-13-f.svg</a></li> <li><a href="coords-trans-14-f.html">coords-trans-14-f.svg</a></li> <li><a href="coords-transformattr-01-f.html">coords-transformattr-01-f.svg</a></li> <li><a href="coords-transformattr-02-f.html">coords-transformattr-02-f.svg</a></li> <li><a href="coords-transformattr-03-f.html">coords-transformattr-03-f.svg</a></li> <li><a href="coords-transformattr-04-f.html">coords-transformattr-04-f.svg</a></li> <li><a href="coords-transformattr-05-f.html">coords-transformattr-05-f.svg</a></li> <li><a href="coords-units-01-b.html">coords-units-01-b.svg</a></li> <li><a href="coords-units-02-b.html">coords-units-02-b.svg</a></li> <li><a href="coords-units-03-b.html">coords-units-03-b.svg</a></li> <li><a href="coords-viewattr-01-b.html">coords-viewattr-01-b.svg</a></li> <li><a href="coords-viewattr-02-b.html">coords-viewattr-02-b.svg</a></li> <li><a href="coords-viewattr-03-b.html">coords-viewattr-03-b.svg</a></li> <li><a href="coords-viewattr-04-f.html">coords-viewattr-04-f.svg</a></li> <li><a href="extend-namespace-01-f.html">extend-namespace-01-f.svg</a></li> <li><a href="filters-background-01-f.html">filters-background-01-f.svg</a></li> <li><a href="filters-blend-01-b.html">filters-blend-01-b.svg</a></li> <li><a href="filters-color-01-b.html">filters-color-01-b.svg</a></li> <li><a href="filters-color-02-b.html">filters-color-02-b.svg</a></li> <li><a href="filters-composite-02-b.html">filters-composite-02-b.svg</a></li> <li><a href="filters-composite-03-f.html">filters-composite-03-f.svg</a></li> <li><a href="filters-composite-04-f.html">filters-composite-04-f.svg</a></li> <li><a href="filters-composite-05-f.html">filters-composite-05-f.svg</a></li> <li><a href="filters-comptran-01-b.html">filters-comptran-01-b.svg</a></li> <li><a href="filters-conv-01-f.html">filters-conv-01-f.svg</a></li> <li><a href="filters-conv-02-f.html">filters-conv-02-f.svg</a></li> <li><a href="filters-conv-03-f.html">filters-conv-03-f.svg</a></li> <li><a href="filters-conv-04-f.html">filters-conv-04-f.svg</a></li> <li><a href="filters-conv-05-f.html">filters-conv-05-f.svg</a></li> <li><a href="filters-diffuse-01-f.html">filters-diffuse-01-f.svg</a></li> <li><a href="filters-displace-01-f.html">filters-displace-01-f.svg</a></li> <li><a href="filters-displace-02-f.html">filters-displace-02-f.svg</a></li> <li><a href="filters-example-01-b.html">filters-example-01-b.svg</a></li> <li><a href="filters-felem-01-b.html">filters-felem-01-b.svg</a></li> <li><a href="filters-felem-02-f.html">filters-felem-02-f.svg</a></li> <li><a href="filters-gauss-01-b.html">filters-gauss-01-b.svg</a></li> <li><a href="filters-gauss-02-f.html">filters-gauss-02-f.svg</a></li> <li><a href="filters-gauss-03-f.html">filters-gauss-03-f.svg</a></li> <li><a href="filters-image-01-b.html">filters-image-01-b.svg</a></li> <li><a href="filters-image-02-b.html">filters-image-02-b.svg</a></li> <li><a href="filters-image-03-f.html">filters-image-03-f.svg</a></li> <li><a href="filters-image-04-f.html">filters-image-04-f.svg</a></li> <li><a href="filters-image-05-f.html">filters-image-05-f.svg</a></li> <li><a href="filters-light-01-f.html">filters-light-01-f.svg</a></li> <li><a href="filters-light-02-f.html">filters-light-02-f.svg</a></li> <li><a href="filters-light-03-f.html">filters-light-03-f.svg</a></li> <li><a href="filters-light-04-f.html">filters-light-04-f.svg</a></li> <li><a href="filters-light-05-f.html">filters-light-05-f.svg</a></li> <li><a href="filters-morph-01-f.html">filters-morph-01-f.svg</a></li> <li><a href="filters-offset-01-b.html">filters-offset-01-b.svg</a></li> <li><a href="filters-offset-02-b.html">filters-offset-02-b.svg</a></li> <li><a href="filters-overview-01-b.html">filters-overview-01-b.svg</a></li> <li><a href="filters-overview-02-b.html">filters-overview-02-b.svg</a></li> <li><a href="filters-overview-03-b.html">filters-overview-03-b.svg</a></li> <li><a href="filters-specular-01-f.html">filters-specular-01-f.svg</a></li> <li><a href="filters-tile-01-b.html">filters-tile-01-b.svg</a></li> <li><a href="filters-turb-01-f.html">filters-turb-01-f.svg</a></li> <li><a href="filters-turb-02-f.html">filters-turb-02-f.svg</a></li> <li><a href="fonts-desc-01-t.html">fonts-desc-01-t.svg</a></li> <li><a href="fonts-desc-02-t.html">fonts-desc-02-t.svg</a></li> <li><a href="fonts-desc-03-t.html">fonts-desc-03-t.svg</a></li> <li><a href="fonts-desc-04-t.html">fonts-desc-04-t.svg</a></li> <li><a href="fonts-desc-05-t.html">fonts-desc-05-t.svg</a></li> <li><a href="fonts-elem-01-t.html">fonts-elem-01-t.svg</a></li> <li><a href="fonts-elem-02-t.html">fonts-elem-02-t.svg</a></li> <li><a href="fonts-elem-03-b.html">fonts-elem-03-b.svg</a></li> <li><a href="fonts-elem-04-b.html">fonts-elem-04-b.svg</a></li> <li><a href="fonts-elem-05-t.html">fonts-elem-05-t.svg</a></li> <li><a href="fonts-elem-06-t.html">fonts-elem-06-t.svg</a></li> <li><a href="fonts-elem-07-b.html">fonts-elem-07-b.svg</a></li> <li><a href="fonts-glyph-02-t.html">fonts-glyph-02-t.svg</a></li> <li><a href="fonts-glyph-03-t.html">fonts-glyph-03-t.svg</a></li> <li><a href="fonts-glyph-04-t.html">fonts-glyph-04-t.svg</a></li> <li><a href="fonts-kern-01-t.html">fonts-kern-01-t.svg</a></li> <li><a href="fonts-overview-201-t.html">fonts-overview-201-t.svg</a></li> <li><a href="imp-path-01-f.html">imp-path-01-f.svg</a></li> <li><a href="interact-cursor-01-f.html">interact-cursor-01-f.svg</a></li> <li><a href="interact-dom-01-b.html">interact-dom-01-b.svg</a></li> <li><a href="interact-events-01-b.html">interact-events-01-b.svg</a></li> <li><a href="interact-events-02-b.html">interact-events-02-b.svg</a></li> <li><a href="interact-events-202-f.html">interact-events-202-f.svg</a></li> <li><a href="interact-events-203-t.html">interact-events-203-t.svg</a></li> <li><a href="interact-order-01-b.html">interact-order-01-b.svg</a></li> <li><a href="interact-order-02-b.html">interact-order-02-b.svg</a></li> <li><a href="interact-order-03-b.html">interact-order-03-b.svg</a></li> <li><a href="interact-pevents-01-b.html">interact-pevents-01-b.svg</a></li> <li><a href="interact-pevents-03-b.html">interact-pevents-03-b.svg</a></li> <li><a href="interact-pevents-04-t.html">interact-pevents-04-t.svg</a></li> <li><a href="interact-pevents-05-b.html">interact-pevents-05-b.svg</a></li> <li><a href="interact-pevents-07-t.html">interact-pevents-07-t.svg</a></li> <li><a href="interact-pevents-08-f.html">interact-pevents-08-f.svg</a></li> <li><a href="interact-pevents-09-f.html">interact-pevents-09-f.svg</a></li> <li><a href="interact-pevents-10-f.html">interact-pevents-10-f.svg</a></li> <li><a href="interact-pointer-01-t.html">interact-pointer-01-t.svg</a></li> <li><a href="interact-pointer-02-t.html">interact-pointer-02-t.svg</a></li> <li><a href="interact-pointer-03-t.html">interact-pointer-03-t.svg</a></li> <li><a href="interact-pointer-04-f.html">interact-pointer-04-f.svg</a></li> <li><a href="interact-zoom-01-t.html">interact-zoom-01-t.svg</a></li> <li><a href="interact-zoom-02-t.html">interact-zoom-02-t.svg</a></li> <li><a href="interact-zoom-03-t.html">interact-zoom-03-t.svg</a></li> <li><a href="linking-a-01-b.html">linking-a-01-b.svg</a></li> <li><a href="linking-a-03-b.html">linking-a-03-b.svg</a></li> <li><a href="linking-a-04-t.html">linking-a-04-t.svg</a></li> <li><a href="linking-a-05-t.html">linking-a-05-t.svg</a></li> <li><a href="linking-a-07-t.html">linking-a-07-t.svg</a></li> <li><a href="linking-a-08-t.html">linking-a-08-t.svg</a></li> <li><a href="linking-a-09-b.html">linking-a-09-b.svg</a></li> <li><a href="linking-a-10-f.html">linking-a-10-f.svg</a></li> <li><a href="linking-frag-01-f.html">linking-frag-01-f.svg</a></li> <li><a href="linking-uri-01-b.html">linking-uri-01-b.svg</a></li> <li><a href="linking-uri-02-b.html">linking-uri-02-b.svg</a></li> <li><a href="linking-uri-03-t.html">linking-uri-03-t.svg</a></li> <li><a href="masking-filter-01-f.html">masking-filter-01-f.svg</a></li> <li><a href="masking-intro-01-f.html">masking-intro-01-f.svg</a></li> <li><a href="masking-mask-01-b.html">masking-mask-01-b.svg</a></li> <li><a href="masking-mask-02-f.html">masking-mask-02-f.svg</a></li> <li><a href="masking-opacity-01-b.html">masking-opacity-01-b.svg</a></li> <li><a href="masking-path-01-b.html">masking-path-01-b.svg</a></li> <li><a href="masking-path-02-b.html">masking-path-02-b.svg</a></li> <li><a href="masking-path-03-b.html">masking-path-03-b.svg</a></li> <li><a href="masking-path-04-b.html">masking-path-04-b.svg</a></li> <li><a href="masking-path-05-f.html">masking-path-05-f.svg</a></li> <li><a href="masking-path-06-b.html">masking-path-06-b.svg</a></li> <li><a href="masking-path-07-b.html">masking-path-07-b.svg</a></li> <li><a href="masking-path-08-b.html">masking-path-08-b.svg</a></li> <li><a href="masking-path-09-b.html">masking-path-09-b.svg</a></li> <li><a href="masking-path-10-b.html">masking-path-10-b.svg</a></li> <li><a href="masking-path-11-b.html">masking-path-11-b.svg</a></li> <li><a href="masking-path-12-f.html">masking-path-12-f.svg</a></li> <li><a href="masking-path-13-f.html">masking-path-13-f.svg</a></li> <li><a href="masking-path-14-f.html">masking-path-14-f.svg</a></li> <li><a href="metadata-example-01-t.html">metadata-example-01-t.svg</a></li> <li><a href="painting-control-01-f.html">painting-control-01-f.svg</a></li> <li><a href="painting-control-02-f.html">painting-control-02-f.svg</a></li> <li><a href="painting-control-03-f.html">painting-control-03-f.svg</a></li> <li><a href="painting-control-04-f.html">painting-control-04-f.svg</a></li> <li><a href="painting-control-05-f.html">painting-control-05-f.svg</a></li> <li><a href="painting-control-06-f.html">painting-control-06-f.svg</a></li> <li><a href="painting-fill-01-t.html">painting-fill-01-t.svg</a></li> <li><a href="painting-fill-02-t.html">painting-fill-02-t.svg</a></li> <li><a href="painting-fill-03-t.html">painting-fill-03-t.svg</a></li> <li><a href="painting-fill-04-t.html">painting-fill-04-t.svg</a></li> <li><a href="painting-fill-05-b.html">painting-fill-05-b.svg</a></li> <li><a href="painting-marker-01-f.html">painting-marker-01-f.svg</a></li> <li><a href="painting-marker-02-f.html">painting-marker-02-f.svg</a></li> <li><a href="painting-marker-03-f.html">painting-marker-03-f.svg</a></li> <li><a href="painting-marker-04-f.html">painting-marker-04-f.svg</a></li> <li><a href="painting-marker-05-f.html">painting-marker-05-f.svg</a></li> <li><a href="painting-marker-06-f.html">painting-marker-06-f.svg</a></li> <li><a href="painting-marker-07-f.html">painting-marker-07-f.svg</a></li> <li><a href="painting-marker-properties-01-f.html">painting-marker-properties-01-f.svg</a></li> <li><a href="painting-render-01-b.html">painting-render-01-b.svg</a></li> <li><a href="painting-render-02-b.html">painting-render-02-b.svg</a></li> <li><a href="painting-stroke-01-t.html">painting-stroke-01-t.svg</a></li> <li><a href="painting-stroke-02-t.html">painting-stroke-02-t.svg</a></li> <li><a href="painting-stroke-03-t.html">painting-stroke-03-t.svg</a></li> <li><a href="painting-stroke-04-t.html">painting-stroke-04-t.svg</a></li> <li><a href="painting-stroke-05-t.html">painting-stroke-05-t.svg</a></li> <li><a href="painting-stroke-06-t.html">painting-stroke-06-t.svg</a></li> <li><a href="painting-stroke-07-t.html">painting-stroke-07-t.svg</a></li> <li><a href="painting-stroke-08-t.html">painting-stroke-08-t.svg</a></li> <li><a href="painting-stroke-09-t.html">painting-stroke-09-t.svg</a></li> <li><a href="painting-stroke-10-t.html">painting-stroke-10-t.svg</a></li> <li><a href="paths-data-01-t.html">paths-data-01-t.svg</a></li> <li><a href="paths-data-02-t.html">paths-data-02-t.svg</a></li> <li><a href="paths-data-03-f.html">paths-data-03-f.svg</a></li> <li><a href="paths-data-04-t.html">paths-data-04-t.svg</a></li> <li><a href="paths-data-05-t.html">paths-data-05-t.svg</a></li> <li><a href="paths-data-06-t.html">paths-data-06-t.svg</a></li> <li><a href="paths-data-07-t.html">paths-data-07-t.svg</a></li> <li><a href="paths-data-08-t.html">paths-data-08-t.svg</a></li> <li><a href="paths-data-09-t.html">paths-data-09-t.svg</a></li> <li><a href="paths-data-10-t.html">paths-data-10-t.svg</a></li> <li><a href="paths-data-12-t.html">paths-data-12-t.svg</a></li> <li><a href="paths-data-13-t.html">paths-data-13-t.svg</a></li> <li><a href="paths-data-14-t.html">paths-data-14-t.svg</a></li> <li><a href="paths-data-15-t.html">paths-data-15-t.svg</a></li> <li><a href="paths-data-16-t.html">paths-data-16-t.svg</a></li> <li><a href="paths-data-17-f.html">paths-data-17-f.svg</a></li> <li><a href="paths-data-18-f.html">paths-data-18-f.svg</a></li> <li><a href="paths-data-19-f.html">paths-data-19-f.svg</a></li> <li><a href="paths-data-20-f.html">paths-data-20-f.svg</a></li> <li><a href="paths-dom-01-f.html">paths-dom-01-f.svg</a></li> <li><a href="paths-dom-02-f.html">paths-dom-02-f.svg</a></li> <li><a href="pservers-grad-01-b.html">pservers-grad-01-b.svg</a></li> <li><a href="pservers-grad-02-b.html">pservers-grad-02-b.svg</a></li> <li><a href="pservers-grad-03-b.html">pservers-grad-03-b.svg</a></li> <li><a href="pservers-grad-04-b.html">pservers-grad-04-b.svg</a></li> <li><a href="pservers-grad-05-b.html">pservers-grad-05-b.svg</a></li> <li><a href="pservers-grad-06-b.html">pservers-grad-06-b.svg</a></li> <li><a href="pservers-grad-07-b.html">pservers-grad-07-b.svg</a></li> <li><a href="pservers-grad-08-b.html">pservers-grad-08-b.svg</a></li> <li><a href="pservers-grad-09-b.html">pservers-grad-09-b.svg</a></li> <li><a href="pservers-grad-10-b.html">pservers-grad-10-b.svg</a></li> <li><a href="pservers-grad-11-b.html">pservers-grad-11-b.svg</a></li> <li><a href="pservers-grad-12-b.html">pservers-grad-12-b.svg</a></li> <li><a href="pservers-grad-13-b.html">pservers-grad-13-b.svg</a></li> <li><a href="pservers-grad-14-b.html">pservers-grad-14-b.svg</a></li> <li><a href="pservers-grad-15-b.html">pservers-grad-15-b.svg</a></li> <li><a href="pservers-grad-16-b.html">pservers-grad-16-b.svg</a></li> <li><a href="pservers-grad-17-b.html">pservers-grad-17-b.svg</a></li> <li><a href="pservers-grad-18-b.html">pservers-grad-18-b.svg</a></li> <li><a href="pservers-grad-20-b.html">pservers-grad-20-b.svg</a></li> <li><a href="pservers-grad-21-b.html">pservers-grad-21-b.svg</a></li> <li><a href="pservers-grad-22-b.html">pservers-grad-22-b.svg</a></li> <li><a href="pservers-grad-23-f.html">pservers-grad-23-f.svg</a></li> <li><a href="pservers-grad-24-f.html">pservers-grad-24-f.svg</a></li> <li><a href="pservers-grad-stops-01-f.html">pservers-grad-stops-01-f.svg</a></li> <li><a href="pservers-pattern-01-b.html">pservers-pattern-01-b.svg</a></li> <li><a href="pservers-pattern-02-f.html">pservers-pattern-02-f.svg</a></li> <li><a href="pservers-pattern-03-f.html">pservers-pattern-03-f.svg</a></li> <li><a href="pservers-pattern-04-f.html">pservers-pattern-04-f.svg</a></li> <li><a href="pservers-pattern-05-f.html">pservers-pattern-05-f.svg</a></li> <li><a href="pservers-pattern-06-f.html">pservers-pattern-06-f.svg</a></li> <li><a href="pservers-pattern-07-f.html">pservers-pattern-07-f.svg</a></li> <li><a href="pservers-pattern-08-f.html">pservers-pattern-08-f.svg</a></li> <li><a href="pservers-pattern-09-f.html">pservers-pattern-09-f.svg</a></li> <li><a href="render-elems-01-t.html">render-elems-01-t.svg</a></li> <li><a href="render-elems-02-t.html">render-elems-02-t.svg</a></li> <li><a href="render-elems-03-t.html">render-elems-03-t.svg</a></li> <li><a href="render-elems-06-t.html">render-elems-06-t.svg</a></li> <li><a href="render-elems-07-t.html">render-elems-07-t.svg</a></li> <li><a href="render-elems-08-t.html">render-elems-08-t.svg</a></li> <li><a href="render-groups-01-b.html">render-groups-01-b.svg</a></li> <li><a href="render-groups-03-t.html">render-groups-03-t.svg</a></li> <li><a href="script-handle-01-b.html">script-handle-01-b.svg</a></li> <li><a href="script-handle-02-b.html">script-handle-02-b.svg</a></li> <li><a href="script-handle-03-b.html">script-handle-03-b.svg</a></li> <li><a href="script-handle-04-b.html">script-handle-04-b.svg</a></li> <li><a href="script-specify-01-f.html">script-specify-01-f.svg</a></li> <li><a href="script-specify-02-f.html">script-specify-02-f.svg</a></li> <li><a href="shapes-circle-01-t.html">shapes-circle-01-t.svg</a></li> <li><a href="shapes-circle-02-t.html">shapes-circle-02-t.svg</a></li> <li><a href="shapes-ellipse-01-t.html">shapes-ellipse-01-t.svg</a></li> <li><a href="shapes-ellipse-02-t.html">shapes-ellipse-02-t.svg</a></li> <li><a href="shapes-ellipse-03-f.html">shapes-ellipse-03-f.svg</a></li> <li><a href="shapes-grammar-01-f.html">shapes-grammar-01-f.svg</a></li> <li><a href="shapes-intro-01-t.html">shapes-intro-01-t.svg</a></li> <li><a href="shapes-intro-02-f.html">shapes-intro-02-f.svg</a></li> <li><a href="shapes-line-01-t.html">shapes-line-01-t.svg</a></li> <li><a href="shapes-line-02-f.html">shapes-line-02-f.svg</a></li> <li><a href="shapes-polygon-01-t.html">shapes-polygon-01-t.svg</a></li> <li><a href="shapes-polygon-02-t.html">shapes-polygon-02-t.svg</a></li> <li><a href="shapes-polygon-03-t.html">shapes-polygon-03-t.svg</a></li> <li><a href="shapes-polyline-01-t.html">shapes-polyline-01-t.svg</a></li> <li><a href="shapes-polyline-02-t.html">shapes-polyline-02-t.svg</a></li> <li><a href="shapes-rect-01-t.html">shapes-rect-01-t.svg</a></li> <li><a href="shapes-rect-02-t.html">shapes-rect-02-t.svg</a></li> <li><a href="shapes-rect-03-t.html">shapes-rect-03-t.svg</a></li> <li><a href="shapes-rect-04-f.html">shapes-rect-04-f.svg</a></li> <li><a href="shapes-rect-05-f.html">shapes-rect-05-f.svg</a></li> <li><a href="shapes-rect-06-f.html">shapes-rect-06-f.svg</a></li> <li><a href="shapes-rect-07-f.html">shapes-rect-07-f.svg</a></li> <li><a href="struct-cond-01-t.html">struct-cond-01-t.svg</a></li> <li><a href="struct-cond-02-t.html">struct-cond-02-t.svg</a></li> <li><a href="struct-cond-03-t.html">struct-cond-03-t.svg</a></li> <li><a href="struct-cond-overview-02-f.html">struct-cond-overview-02-f.svg</a></li> <li><a href="struct-cond-overview-03-f.html">struct-cond-overview-03-f.svg</a></li> <li><a href="struct-cond-overview-04-f.html">struct-cond-overview-04-f.svg</a></li> <li><a href="struct-cond-overview-05-f.html">struct-cond-overview-05-f.svg</a></li> <li><a href="struct-defs-01-t.html">struct-defs-01-t.svg</a></li> <li><a href="struct-dom-01-b.html">struct-dom-01-b.svg</a></li> <li><a href="struct-dom-02-b.html">struct-dom-02-b.svg</a></li> <li><a href="struct-dom-03-b.html">struct-dom-03-b.svg</a></li> <li><a href="struct-dom-04-b.html">struct-dom-04-b.svg</a></li> <li><a href="struct-dom-05-b.html">struct-dom-05-b.svg</a></li> <li><a href="struct-dom-06-b.html">struct-dom-06-b.svg</a></li> <li><a href="struct-dom-07-f.html">struct-dom-07-f.svg</a></li> <li><a href="struct-dom-08-f.html">struct-dom-08-f.svg</a></li> <li><a href="struct-dom-11-f.html">struct-dom-11-f.svg</a></li> <li><a href="struct-dom-12-b.html">struct-dom-12-b.svg</a></li> <li><a href="struct-dom-13-f.html">struct-dom-13-f.svg</a></li> <li><a href="struct-dom-14-f.html">struct-dom-14-f.svg</a></li> <li><a href="struct-dom-15-f.html">struct-dom-15-f.svg</a></li> <li><a href="struct-dom-16-f.html">struct-dom-16-f.svg</a></li> <li><a href="struct-dom-17-f.html">struct-dom-17-f.svg</a></li> <li><a href="struct-dom-18-f.html">struct-dom-18-f.svg</a></li> <li><a href="struct-dom-19-f.html">struct-dom-19-f.svg</a></li> <li><a href="struct-dom-20-f.html">struct-dom-20-f.svg</a></li> <li><a href="struct-frag-01-t.html">struct-frag-01-t.svg</a></li> <li><a href="struct-frag-02-t.html">struct-frag-02-t.svg</a></li> <li><a href="struct-frag-03-t.html">struct-frag-03-t.svg</a></li> <li><a href="struct-frag-04-t.html">struct-frag-04-t.svg</a></li> <li><a href="struct-frag-05-t.html">struct-frag-05-t.svg</a></li> <li><a href="struct-frag-06-t.html">struct-frag-06-t.svg</a></li> <li><a href="struct-group-01-t.html">struct-group-01-t.svg</a></li> <li><a href="struct-group-02-b.html">struct-group-02-b.svg</a></li> <li><a href="struct-group-03-t.html">struct-group-03-t.svg</a></li> <li><a href="struct-image-01-t.html">struct-image-01-t.svg</a></li> <li><a href="struct-image-02-b.html">struct-image-02-b.svg</a></li> <li><a href="struct-image-03-t.html">struct-image-03-t.svg</a></li> <li><a href="struct-image-04-t.html">struct-image-04-t.svg</a></li> <li><a href="struct-image-05-b.html">struct-image-05-b.svg</a></li> <li><a href="struct-image-06-t.html">struct-image-06-t.svg</a></li> <li><a href="struct-image-07-t.html">struct-image-07-t.svg</a></li> <li><a href="struct-image-08-t.html">struct-image-08-t.svg</a></li> <li><a href="struct-image-09-t.html">struct-image-09-t.svg</a></li> <li><a href="struct-image-10-t.html">struct-image-10-t.svg</a></li> <li><a href="struct-image-11-b.html">struct-image-11-b.svg</a></li> <li><a href="struct-image-12-b.html">struct-image-12-b.svg</a></li> <li><a href="struct-image-13-f.html">struct-image-13-f.svg</a></li> <li><a href="struct-image-14-f.html">struct-image-14-f.svg</a></li> <li><a href="struct-image-15-f.html">struct-image-15-f.svg</a></li> <li><a href="struct-image-16-f.html">struct-image-16-f.svg</a></li> <li><a href="struct-image-17-b.html">struct-image-17-b.svg</a></li> <li><a href="struct-image-18-f.html">struct-image-18-f.svg</a></li> <li><a href="struct-image-19-f.html">struct-image-19-f.svg</a></li> <li><a href="struct-svg-01-f.html">struct-svg-01-f.svg</a></li> <li><a href="struct-svg-02-f.html">struct-svg-02-f.svg</a></li> <li><a href="struct-svg-03-f.html">struct-svg-03-f.svg</a></li> <li><a href="struct-symbol-01-b.html">struct-symbol-01-b.svg</a></li> <li><a href="struct-use-01-t.html">struct-use-01-t.svg</a></li> <li><a href="struct-use-03-t.html">struct-use-03-t.svg</a></li> <li><a href="struct-use-04-b.html">struct-use-04-b.svg</a></li> <li><a href="struct-use-05-b.html">struct-use-05-b.svg</a></li> <li><a href="struct-use-06-b.html">struct-use-06-b.svg</a></li> <li><a href="struct-use-07-b.html">struct-use-07-b.svg</a></li> <li><a href="struct-use-08-b.html">struct-use-08-b.svg</a></li> <li><a href="struct-use-09-b.html">struct-use-09-b.svg</a></li> <li><a href="struct-use-10-f.html">struct-use-10-f.svg</a></li> <li><a href="struct-use-11-f.html">struct-use-11-f.svg</a></li> <li><a href="struct-use-12-f.html">struct-use-12-f.svg</a></li> <li><a href="struct-use-13-f.html">struct-use-13-f.svg</a></li> <li><a href="struct-use-14-f.html">struct-use-14-f.svg</a></li> <li><a href="struct-use-15-f.html">struct-use-15-f.svg</a></li> <li><a href="styling-class-01-f.html">styling-class-01-f.svg</a></li> <li><a href="styling-css-01-b.html">styling-css-01-b.svg</a></li> <li><a href="styling-css-02-b.html">styling-css-02-b.svg</a></li> <li><a href="styling-css-03-b.html">styling-css-03-b.svg</a></li> <li><a href="styling-css-04-f.html">styling-css-04-f.svg</a></li> <li><a href="styling-css-05-b.html">styling-css-05-b.svg</a></li> <li><a href="styling-css-06-b.html">styling-css-06-b.svg</a></li> <li><a href="styling-css-07-f.html">styling-css-07-f.svg</a></li> <li><a href="styling-css-08-f.html">styling-css-08-f.svg</a></li> <li><a href="styling-css-09-f.html">styling-css-09-f.svg</a></li> <li><a href="styling-css-10-f.html">styling-css-10-f.svg</a></li> <li><a href="styling-elem-01-b.html">styling-elem-01-b.svg</a></li> <li><a href="styling-inherit-01-b.html">styling-inherit-01-b.svg</a></li> <li><a href="styling-pres-01-t.html">styling-pres-01-t.svg</a></li> <li><a href="styling-pres-02-f.html">styling-pres-02-f.svg</a></li> <li><a href="styling-pres-03-f.html">styling-pres-03-f.svg</a></li> <li><a href="styling-pres-04-f.html">styling-pres-04-f.svg</a></li> <li><a href="styling-pres-05-f.html">styling-pres-05-f.svg</a></li> <li><a href="svgdom-over-01-f.html">svgdom-over-01-f.svg</a></li> <li><a href="text-align-01-b.html">text-align-01-b.svg</a></li> <li><a href="text-align-02-b.html">text-align-02-b.svg</a></li> <li><a href="text-align-03-b.html">text-align-03-b.svg</a></li> <li><a href="text-align-04-b.html">text-align-04-b.svg</a></li> <li><a href="text-align-05-b.html">text-align-05-b.svg</a></li> <li><a href="text-align-06-b.html">text-align-06-b.svg</a></li> <li><a href="text-align-07-t.html">text-align-07-t.svg</a></li> <li><a href="text-align-08-b.html">text-align-08-b.svg</a></li> <li><a href="text-altglyph-01-b.html">text-altglyph-01-b.svg</a></li> <li><a href="text-altglyph-02-b.html">text-altglyph-02-b.svg</a></li> <li><a href="text-altglyph-03-b.html">text-altglyph-03-b.svg</a></li> <li><a href="text-bidi-01-t.html">text-bidi-01-t.svg</a></li> <li><a href="text-deco-01-b.html">text-deco-01-b.svg</a></li> <li><a href="text-dom-01-f.html">text-dom-01-f.svg</a></li> <li><a href="text-dom-02-f.html">text-dom-02-f.svg</a></li> <li><a href="text-dom-03-f.html">text-dom-03-f.svg</a></li> <li><a href="text-dom-04-f.html">text-dom-04-f.svg</a></li> <li><a href="text-dom-05-f.html">text-dom-05-f.svg</a></li> <li><a href="text-fonts-01-t.html">text-fonts-01-t.svg</a></li> <li><a href="text-fonts-02-t.html">text-fonts-02-t.svg</a></li> <li><a href="text-fonts-03-t.html">text-fonts-03-t.svg</a></li> <li><a href="text-fonts-04-t.html">text-fonts-04-t.svg</a></li> <li><a href="text-fonts-05-f.html">text-fonts-05-f.svg</a></li> <li><a href="text-fonts-202-t.html">text-fonts-202-t.svg</a></li> <li><a href="text-fonts-203-t.html">text-fonts-203-t.svg</a></li> <li><a href="text-fonts-204-t.html">text-fonts-204-t.svg</a></li> <li><a href="text-intro-01-t.html">text-intro-01-t.svg</a></li> <li><a href="text-intro-02-b.html">text-intro-02-b.svg</a></li> <li><a href="text-intro-03-b.html">text-intro-03-b.svg</a></li> <li><a href="text-intro-04-t.html">text-intro-04-t.svg</a></li> <li><a href="text-intro-05-t.html">text-intro-05-t.svg</a></li> <li><a href="text-intro-06-t.html">text-intro-06-t.svg</a></li> <li><a href="text-intro-07-t.html">text-intro-07-t.svg</a></li> <li><a href="text-intro-09-b.html">text-intro-09-b.svg</a></li> <li><a href="text-intro-10-f.html">text-intro-10-f.svg</a></li> <li><a href="text-intro-11-t.html">text-intro-11-t.svg</a></li> <li><a href="text-intro-12-t.html">text-intro-12-t.svg</a></li> <li><a href="text-path-01-b.html">text-path-01-b.svg</a></li> <li><a href="text-path-02-b.html">text-path-02-b.svg</a></li> <li><a href="text-spacing-01-b.html">text-spacing-01-b.svg</a></li> <li><a href="text-text-01-b.html">text-text-01-b.svg</a></li> <li><a href="text-text-03-b.html">text-text-03-b.svg</a></li> <li><a href="text-text-04-t.html">text-text-04-t.svg</a></li> <li><a href="text-text-05-t.html">text-text-05-t.svg</a></li> <li><a href="text-text-06-t.html">text-text-06-t.svg</a></li> <li><a href="text-text-07-t.html">text-text-07-t.svg</a></li> <li><a href="text-text-08-b.html">text-text-08-b.svg</a></li> <li><a href="text-text-09-t.html">text-text-09-t.svg</a></li> <li><a href="text-text-10-t.html">text-text-10-t.svg</a></li> <li><a href="text-text-11-t.html">text-text-11-t.svg</a></li> <li><a href="text-text-12-t.html">text-text-12-t.svg</a></li> <li><a href="text-tref-01-b.html">text-tref-01-b.svg</a></li> <li><a href="text-tref-02-b.html">text-tref-02-b.svg</a></li> <li><a href="text-tref-03-b.html">text-tref-03-b.svg</a></li> <li><a href="text-tselect-01-b.html">text-tselect-01-b.svg</a></li> <li><a href="text-tselect-02-f.html">text-tselect-02-f.svg</a></li> <li><a href="text-tselect-03-f.html">text-tselect-03-f.svg</a></li> <li><a href="text-tspan-01-b.html">text-tspan-01-b.svg</a></li> <li><a href="text-tspan-02-b.html">text-tspan-02-b.svg</a></li> <li><a href="text-ws-01-t.html">text-ws-01-t.svg</a></li> <li><a href="text-ws-02-t.html">text-ws-02-t.svg</a></li> <li><a href="text-ws-03-t.html">text-ws-03-t.svg</a></li> <li><a href="types-basic-01-f.html">types-basic-01-f.svg</a></li> <li><a href="types-basic-02-f.html">types-basic-02-f.svg</a></li> <li><a href="types-dom-01-b.html">types-dom-01-b.svg</a></li> <li><a href="types-dom-02-f.html">types-dom-02-f.svg</a></li> <li><a href="types-dom-03-b.html">types-dom-03-b.svg</a></li> <li><a href="types-dom-04-b.html">types-dom-04-b.svg</a></li> <li><a href="types-dom-05-b.html">types-dom-05-b.svg</a></li> <li><a href="types-dom-06-f.html">types-dom-06-f.svg</a></li> <li><a href="types-dom-07-f.html">types-dom-07-f.svg</a></li> <li><a href="types-dom-08-f.html">types-dom-08-f.svg</a></li> <li><a href="types-dom-svgfittoviewbox-01-f.html">types-dom-svgfittoviewbox-01-f.svg</a></li> <li><a href="types-dom-svglengthlist-01-f.html">types-dom-svglengthlist-01-f.svg</a></li> <li><a href="types-dom-svgnumberlist-01-f.html">types-dom-svgnumberlist-01-f.svg</a></li> <li><a href="types-dom-svgstringlist-01-f.html">types-dom-svgstringlist-01-f.svg</a></li> <li><a href="types-dom-svgtransformable-01-f.html">types-dom-svgtransformable-01-f.svg</a></li> </ol> </body> </html>
frivoal/presto-testo
SVG/Testsuites/W3C-1_1F2/harness/htmlEmbed/index.html
HTML
bsd-3-clause
41,376
// Copyright 2014 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. #ifndef CHROMEOS_NETWORK_PORTAL_DETECTOR_NETWORK_PORTAL_DETECTOR_STRATEGY_H_ #define CHROMEOS_NETWORK_PORTAL_DETECTOR_NETWORK_PORTAL_DETECTOR_STRATEGY_H_ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/time/tick_clock.h" #include "base/time/time.h" #include "chromeos/chromeos_export.h" #include "net/base/backoff_entry.h" namespace chromeos { class CHROMEOS_EXPORT PortalDetectorStrategy { public: enum StrategyId { STRATEGY_ID_LOGIN_SCREEN, STRATEGY_ID_ERROR_SCREEN, STRATEGY_ID_SESSION }; class Delegate : public base::TickClock { public: ~Delegate() override; // Returns number of attempts in a row with NO RESPONSE result. // If last detection attempt has different result, returns 0. virtual int NoResponseResultCount() = 0; // Returns time when current attempt was started. virtual base::TimeTicks AttemptStartTime() = 0; }; virtual ~PortalDetectorStrategy(); // Lifetime of delegate must enclose lifetime of PortalDetectorStrategy. static scoped_ptr<PortalDetectorStrategy> CreateById(StrategyId id, Delegate* delegate); // Returns delay before next detection attempt. This delay is needed // to separate detection attempts in time. base::TimeDelta GetDelayTillNextAttempt(); // Returns timeout for the next detection attempt. base::TimeDelta GetNextAttemptTimeout(); virtual StrategyId Id() const = 0; // Resets strategy to the initial state. void Reset(); const net::BackoffEntry::Policy& policy() const { return policy_; } // Resets strategy to the initial stater and sets custom policy. void SetPolicyAndReset(const net::BackoffEntry::Policy& policy); // Should be called when portal detection is completed and timeout before next // attempt should be adjusted. void OnDetectionCompleted(); protected: // Lifetime of delegate must enclose lifetime of PortalDetectorStrategy. explicit PortalDetectorStrategy(Delegate* delegate); // Interface for subclasses: virtual base::TimeDelta GetNextAttemptTimeoutImpl() = 0; Delegate* delegate_; net::BackoffEntry::Policy policy_; scoped_ptr<net::BackoffEntry> backoff_entry_; private: friend class NetworkPortalDetectorImplTest; friend class NetworkPortalDetectorImplBrowserTest; static void set_delay_till_next_attempt_for_testing( const base::TimeDelta& timeout) { delay_till_next_attempt_for_testing_ = timeout; delay_till_next_attempt_for_testing_initialized_ = true; } static void set_next_attempt_timeout_for_testing( const base::TimeDelta& timeout) { next_attempt_timeout_for_testing_ = timeout; next_attempt_timeout_for_testing_initialized_ = true; } static void reset_fields_for_testing() { delay_till_next_attempt_for_testing_initialized_ = false; next_attempt_timeout_for_testing_initialized_ = false; } // Test delay before detection attempt, used by unit tests. static base::TimeDelta delay_till_next_attempt_for_testing_; // True when |min_time_between_attempts_for_testing_| is initialized. static bool delay_till_next_attempt_for_testing_initialized_; // Test timeout for a detection attempt, used by unit tests. static base::TimeDelta next_attempt_timeout_for_testing_; // True when |next_attempt_timeout_for_testing_| is initialized. static bool next_attempt_timeout_for_testing_initialized_; DISALLOW_COPY_AND_ASSIGN(PortalDetectorStrategy); }; } // namespace chromeos #endif // CHROMEOS_NETWORK_PORTAL_DETECTOR_NETWORK_PORTAL_DETECTOR_STRATEGY_H_
CapOM/ChromiumGStreamerBackend
chromeos/network/portal_detector/network_portal_detector_strategy.h
C
bsd-3-clause
3,832
--- title: Avoid Inferring the Response MIME Type with helmet.noSniff() localeTitle: تجنب استنتاج نوع MIME الاستجابة مع helmet.noSniff () --- ## تجنب استنتاج نوع MIME الاستجابة مع helmet.noSniff () هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/information-security-and-quality-assurance/information-security-with-helmetjs/avoid-inferring-the-response-mime-type-with-helmet.nosniff/index.md) . [سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .
otavioarc/freeCodeCamp
guide/arabic/certifications/information-security-and-quality-assurance/information-security-with-helmetjs/avoid-inferring-the-response-mime-type-with-helmet.nosniff/index.md
Markdown
bsd-3-clause
704
using Irony.Parsing; using Workbench.Core.Grammars; using Workbench.Core.Nodes; namespace Workbench.Core.Parsers { public class VariableDomainExpressionParser : ExpressionParser<VariableDomainExpressionNode> { /// <summary> /// Parse a raw variable domain expression. /// </summary> /// <param name="rawExpression">Raw variable domain expression.</param> /// <returns>Parse result.</returns> public ParseResult<VariableDomainExpressionNode> Parse(string rawExpression) { var language = new LanguageData(new VariableDomainGrammar()); var parser = new Parser(language); var parseTree = parser.Parse(rawExpression); return CreateResultFrom(parseTree); } } }
digitalbricklayer/workbench
src/Workbench.Core/Parsers/VariableDomainExpressionParser.cs
C#
bsd-3-clause
807
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>Forms :: submit input : font</title> <style type="text/css"> form * { font-family: Ahem; font-size: 1em; line-height: 1em; } fieldset, div { padding: 0; margin: 10px; border: none; } </style> </head> <body> <form action=""> <fieldset> <input type="submit" value="if you see this text in english the test failed"> </fieldset> </form> <p>you should see various black rectangles and no text above</p> <h4>Ahem font required for this test</h4> </body> </html>
frivoal/presto-testo
core/standards/forms/input-submit-font.html
HTML
bsd-3-clause
541
<html> <head> <meta charset="cp864"><title>Mappings for single-byte encodings: cp864</title><style type="text/css">p#test { display: none; }</style> </head> <body> <p id="test">€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ</p> <p> <script type="text/javascript"> var passed = (document.getElementById('test').innerText == '\u00b0\u00b7\u2219\u221a\u2592\u2500\u2502\u253c\u2524\u252c\u251c\u2534\u2510\u250c\u2514\u2518\u03b2\u221e\u03c6\u00b1\u00bd\u00bc\u2248\u00ab\u00bb\ufef7\ufef8\u009b\u009c\ufefb\ufefc\u009f\u00a0\u00ad\ufe82\u00a3\u00a4\ufe84\ufe8e\ufe8f\ufe95\ufe99\u060c\ufe9d\ufea1\ufea5\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\ufed1\u061b\ufeb1\ufeb5\ufeb9\u061f\u00a2\ufe80\ufe81\ufe83\ufe85\ufeca\ufe8b\ufe8d\ufe91\ufe93\ufe97\ufe9b\ufe9f\ufea3\ufea7\ufea9\ufeab\ufead\ufeaf\ufeb3\ufeb7\ufebb\ufebf\ufec1\ufec5\ufecb\ufecf\u00a6\u00ac\u00f7\u00d7\ufec9\u0640\ufed3\ufed7\ufedb\ufedf\ufee3\ufee7\ufeeb\ufeed\ufeef\ufef3\ufebd\ufecc\ufece\ufecd\ufee1\ufe7d\u0651\ufee5\ufee9\ufeec\ufef0\ufef2\ufed0\ufed5\ufef5\ufef6\ufedd\ufed9\ufef1\u25a0') if (passed) document.write('PASS') else document.write('FAIL') try{top.opener.rr(passed);}catch(e){} </script> </p> </body> </html>
frivoal/presto-testo
core/standards/encodings/mappings/cp864.html
HTML
bsd-3-clause
1,330
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2006, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Maxim Lifantsev */ #ifndef BASE_MEMORY_REGION_MAP_H_ #define BASE_MEMORY_REGION_MAP_H_ #include <config.h> #ifdef HAVE_PTHREAD #include <pthread.h> #endif #include <stddef.h> #include <set> #include "base/stl_allocator.h" #include "base/spinlock.h" #include "base/thread_annotations.h" #include "base/low_level_alloc.h" #include "heap-profile-stats.h" // TODO(maxim): add a unittest: // execute a bunch of mmaps and compare memory map what strace logs // execute a bunch of mmap/munmup and compare memory map with // own accounting of what those mmaps generated // Thread-safe class to collect and query the map of all memory regions // in a process that have been created with mmap, munmap, mremap, sbrk. // For each memory region, we keep track of (and provide to users) // the stack trace that allocated that memory region. // The recorded stack trace depth is bounded by // a user-supplied max_stack_depth parameter of Init(). // After initialization with Init() // (which can happened even before global object constructor execution) // we collect the map by installing and monitoring MallocHook-s // to mmap, munmap, mremap, sbrk. // At any time one can query this map via provided interface. // For more details on the design of MemoryRegionMap // see the comment at the top of our .cc file. class MemoryRegionMap { private: // Max call stack recording depth supported by Init(). Set it to be // high enough for all our clients. Note: we do not define storage // for this (doing that requires special handling in windows), so // don't take the address of it! static const int kMaxStackDepth = 32; // Size of the hash table of buckets. A structure of the bucket table is // described in heap-profile-stats.h. static const int kHashTableSize = 179999; public: MemoryRegionMap(const MemoryRegionMap&) = delete; MemoryRegionMap& operator=(const MemoryRegionMap&) = delete; // interface ================================================================ // Every client of MemoryRegionMap must call Init() before first use, // and Shutdown() after last use. This allows us to reference count // this (singleton) class properly. MemoryRegionMap assumes it's the // only client of MallocHooks, so a client can only register other // MallocHooks after calling Init() and must unregister them before // calling Shutdown(). // Initialize this module to record memory allocation stack traces. // Stack traces that have more than "max_stack_depth" frames // are automatically shrunk to "max_stack_depth" when they are recorded. // Init() can be called more than once w/o harm, largest max_stack_depth // will be the effective one. // When "use_buckets" is true, then counts of mmap and munmap sizes will be // recorded with each stack trace. If Init() is called more than once, then // counting will be effective after any call contained "use_buckets" of true. // It will install mmap, munmap, mremap, sbrk hooks // and initialize arena_ and our hook and locks, hence one can use // MemoryRegionMap::Lock()/Unlock() to manage the locks. // Uses Lock/Unlock inside. static void Init(int max_stack_depth, bool use_buckets); // Try to shutdown this module undoing what Init() did. // Returns true iff could do full shutdown (or it was not attempted). // Full shutdown is attempted when the number of Shutdown() calls equals // the number of Init() calls. static bool Shutdown(); // Return true if MemoryRegionMap is initialized and recording, i.e. when // then number of Init() calls are more than the number of Shutdown() calls. static bool IsRecordingLocked(); // Locks to protect our internal data structures. // These also protect use of arena_ if our Init() has been done. // The lock is recursive. static void Lock() EXCLUSIVE_LOCK_FUNCTION(lock_); static void Unlock() UNLOCK_FUNCTION(lock_); // Returns true when the lock is held by this thread (for use in RAW_CHECK-s). static bool LockIsHeld(); // Locker object that acquires the MemoryRegionMap::Lock // for the duration of its lifetime (a C++ scope). class LockHolder { public: LockHolder() { Lock(); } LockHolder(const LockHolder&) = delete; LockHolder& operator=(const LockHolder&) = delete; ~LockHolder() { Unlock(); } }; // A memory region that we know about through malloc_hook-s. // This is essentially an interface through which MemoryRegionMap // exports the collected data to its clients. Thread-compatible. struct Region { uintptr_t start_addr; // region start address uintptr_t end_addr; // region end address int call_stack_depth; // number of caller stack frames that we saved const void* call_stack[kMaxStackDepth]; // caller address stack array // filled to call_stack_depth size bool is_stack; // does this region contain a thread's stack: // a user of MemoryRegionMap supplies this info // Convenience accessor for call_stack[0], // i.e. (the program counter of) the immediate caller // of this region's allocation function, // but it also returns NULL when call_stack_depth is 0, // i.e whe we weren't able to get the call stack. // This usually happens in recursive calls, when the stack-unwinder // calls mmap() which in turn calls the stack-unwinder. uintptr_t caller() const { return reinterpret_cast<uintptr_t>(call_stack_depth >= 1 ? call_stack[0] : NULL); } // Return true iff this region overlaps region x. bool Overlaps(const Region& x) const { return start_addr < x.end_addr && end_addr > x.start_addr; } private: // helpers for MemoryRegionMap friend class MemoryRegionMap; // The ways we create Region-s: void Create(const void* start, size_t size) { start_addr = reinterpret_cast<uintptr_t>(start); end_addr = start_addr + size; is_stack = false; // not a stack till marked such call_stack_depth = 0; AssertIsConsistent(); } void set_call_stack_depth(int depth) { RAW_DCHECK(call_stack_depth == 0, ""); // only one such set is allowed call_stack_depth = depth; AssertIsConsistent(); } // The ways we modify Region-s: void set_is_stack() { is_stack = true; } void set_start_addr(uintptr_t addr) { start_addr = addr; AssertIsConsistent(); } void set_end_addr(uintptr_t addr) { end_addr = addr; AssertIsConsistent(); } // Verifies that *this contains consistent data, crashes if not the case. void AssertIsConsistent() const { RAW_DCHECK(start_addr < end_addr, ""); RAW_DCHECK(call_stack_depth >= 0 && call_stack_depth <= kMaxStackDepth, ""); } // Post-default construction helper to make a Region suitable // for searching in RegionSet regions_. void SetRegionSetKey(uintptr_t addr) { // make sure *this has no usable data: if (DEBUG_MODE) memset(this, 0xFF, sizeof(*this)); end_addr = addr; } // Note: call_stack[kMaxStackDepth] as a member lets us make Region // a simple self-contained struct with correctly behaving bit-vise copying. // This simplifies the code of this module but wastes some memory: // in most-often use case of this module (leak checking) // only one call_stack element out of kMaxStackDepth is actually needed. // Making the storage for call_stack variable-sized, // substantially complicates memory management for the Region-s: // as they need to be created and manipulated for some time // w/o any memory allocations, yet are also given out to the users. }; // Find the region that covers addr and write its data into *result if found, // in which case *result gets filled so that it stays fully functional // even when the underlying region gets removed from MemoryRegionMap. // Returns success. Uses Lock/Unlock inside. static bool FindRegion(uintptr_t addr, Region* result); // Find the region that contains stack_top, mark that region as // a stack region, and write its data into *result if found, // in which case *result gets filled so that it stays fully functional // even when the underlying region gets removed from MemoryRegionMap. // Returns success. Uses Lock/Unlock inside. static bool FindAndMarkStackRegion(uintptr_t stack_top, Region* result); // Iterate over the buckets which store mmap and munmap counts per stack // trace. It calls "callback" for each bucket, and passes "arg" to it. template<class Type> static void IterateBuckets(void (*callback)(const HeapProfileBucket*, Type), Type arg); // Get the bucket whose caller stack trace is "key". The stack trace is // used to a depth of "depth" at most. The requested bucket is created if // needed. // The bucket table is described in heap-profile-stats.h. static HeapProfileBucket* GetBucket(int depth, const void* const key[]); private: // our internal types ============================================== // Region comparator for sorting with STL struct RegionCmp { bool operator()(const Region& x, const Region& y) const { return x.end_addr < y.end_addr; } }; // We allocate STL objects in our own arena. struct MyAllocator { static void *Allocate(size_t n) { return LowLevelAlloc::AllocWithArena(n, arena_); } static void Free(const void *p, size_t /* n */) { LowLevelAlloc::Free(const_cast<void*>(p)); } }; // Set of the memory regions typedef std::set<Region, RegionCmp, STL_Allocator<Region, MyAllocator> > RegionSet; public: // more in-depth interface ========================================== // STL iterator with values of Region typedef RegionSet::const_iterator RegionIterator; // Return the begin/end iterators to all the regions. // These need Lock/Unlock protection around their whole usage (loop). // Even when the same thread causes modifications during such a loop // (which are permitted due to recursive locking) // the loop iterator will still be valid as long as its region // has not been deleted, but EndRegionLocked should be // re-evaluated whenever the set of regions has changed. static RegionIterator BeginRegionLocked(); static RegionIterator EndRegionLocked(); // Return the accumulated sizes of mapped and unmapped regions. static int64 MapSize() { return map_size_; } static int64 UnmapSize() { return unmap_size_; } // Effectively private type from our .cc ================================= // public to let us declare global objects: union RegionSetRep; private: // representation =========================================================== // Counter of clients of this module that have called Init(). static int client_count_; // Maximal number of caller stack frames to save (>= 0). static int max_stack_depth_; // Arena used for our allocations in regions_. static LowLevelAlloc::Arena* arena_; // Set of the mmap/sbrk/mremap-ed memory regions // To be accessed *only* when Lock() is held. // Hence we protect the non-recursive lock used inside of arena_ // with our recursive Lock(). This lets a user prevent deadlocks // when threads are stopped by TCMalloc_ListAllProcessThreads at random spots // simply by acquiring our recursive Lock() before that. static RegionSet* regions_; // Lock to protect regions_ and buckets_ variables and the data behind. static SpinLock lock_; // Lock to protect the recursive lock itself. static SpinLock owner_lock_; // Recursion count for the recursive lock. static int recursion_count_; // The thread id of the thread that's inside the recursive lock. static pthread_t lock_owner_tid_; // Total size of all mapped pages so far static int64 map_size_; // Total size of all unmapped pages so far static int64 unmap_size_; // Bucket hash table which is described in heap-profile-stats.h. static HeapProfileBucket** bucket_table_ GUARDED_BY(lock_); static int num_buckets_ GUARDED_BY(lock_); // The following members are local to MemoryRegionMap::GetBucket() // and MemoryRegionMap::HandleSavedBucketsLocked() // and are file-level to ensure that they are initialized at load time. // // These are used as temporary storage to break the infinite cycle of mmap // calling our hook which (sometimes) causes mmap. It must be a static // fixed-size array. The size 20 is just an expected value for safety. // The details are described in memory_region_map.cc. // Number of unprocessed bucket inserts. static int saved_buckets_count_ GUARDED_BY(lock_); // Unprocessed inserts (must be big enough to hold all mmaps that can be // caused by a GetBucket call). // Bucket has no constructor, so that c-tor execution does not interfere // with the any-time use of the static memory behind saved_buckets. static HeapProfileBucket saved_buckets_[20] GUARDED_BY(lock_); static const void* saved_buckets_keys_[20][kMaxStackDepth] GUARDED_BY(lock_); // helpers ================================================================== // Helper for FindRegion and FindAndMarkStackRegion: // returns the region covering 'addr' or NULL; assumes our lock_ is held. static const Region* DoFindRegionLocked(uintptr_t addr); // Verifying wrapper around regions_->insert(region) // To be called to do InsertRegionLocked's work only! inline static void DoInsertRegionLocked(const Region& region); // Handle regions saved by InsertRegionLocked into a tmp static array // by calling insert_func on them. inline static void HandleSavedRegionsLocked( void (*insert_func)(const Region& region)); // Restore buckets saved in a tmp static array by GetBucket to the bucket // table where all buckets eventually should be. static void RestoreSavedBucketsLocked(); // Initialize RegionSet regions_. inline static void InitRegionSetLocked(); // Wrapper around DoInsertRegionLocked // that handles the case of recursive allocator calls. inline static void InsertRegionLocked(const Region& region); // Record addition of a memory region at address "start" of size "size" // (called from our mmap/mremap/sbrk hooks). static void RecordRegionAddition(const void* start, size_t size); // Record deletion of a memory region at address "start" of size "size" // (called from our munmap/mremap/sbrk hooks). static void RecordRegionRemoval(const void* start, size_t size); // Record deletion of a memory region of size "size" in a bucket whose // caller stack trace is "key". The stack trace is used to a depth of // "depth" at most. static void RecordRegionRemovalInBucket(int depth, const void* const key[], size_t size); // Hooks for MallocHook static void MmapHook(const void* result, const void* start, size_t size, int prot, int flags, int fd, off_t offset); static void MunmapHook(const void* ptr, size_t size); static void MremapHook(const void* result, const void* old_addr, size_t old_size, size_t new_size, int flags, const void* new_addr); static void SbrkHook(const void* result, ptrdiff_t increment); // Log all memory regions; Useful for debugging only. // Assumes Lock() is held static void LogAllLocked(); }; template <class Type> void MemoryRegionMap::IterateBuckets( void (*callback)(const HeapProfileBucket*, Type), Type callback_arg) { for (int index = 0; index < kHashTableSize; index++) { for (HeapProfileBucket* bucket = bucket_table_[index]; bucket != NULL; bucket = bucket->next) { callback(bucket, callback_arg); } } } #endif // BASE_MEMORY_REGION_MAP_H_
scheib/chromium
third_party/tcmalloc/chromium/src/memory_region_map.h
C
bsd-3-clause
17,684
<!doctype html> <!-- This file is generated by build.py. --> <title>img wide.jpg; overflow:visible; -o-object-fit:contain; -o-object-position:top right</title> <link rel="stylesheet" href="../../support/reftests.css"> <link rel='match' href='visible_contain_top_right-ref.html'> <style> #test > * { overflow:visible; -o-object-fit:contain; -o-object-position:top right } </style> <div id="test"> <img src="../../support/wide.jpg"> </div>
frivoal/presto-testo
css/image-fit/reftests/img-jpg-wide/visible_contain_top_right.html
HTML
bsd-3-clause
440
/* Copyright (C) 2014, The University of Texas at Austin This file is part of libflame and is available under the 3-Clause BSD license, which can be found in the LICENSE file at the top-level directory, or at http://opensource.org/licenses/BSD-3-Clause */ #include "FLAME.h" FLA_Error REF_Ttmm( FLA_Uplo uplo, FLA_Obj A ) { return FLA_Ttmm_blk_external( uplo, A ); }
yaowee/libflame
src/lapack/misc/ttmm/front/flamec/test/fla/REF_Ttmm.c
C
bsd-3-clause
391
/* * Copyright 2014, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc; import io.grpc.internal.ClientTransportFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import javax.annotation.Nullable; /** * The base class for channel builders. * * @param <BuilderT> The concrete type of this builder. */ public abstract class AbstractChannelBuilder<BuilderT extends AbstractChannelBuilder<BuilderT>> { @Nullable private ExecutorService executor; private final List<ClientInterceptor> interceptors = new ArrayList<ClientInterceptor>(); @Nullable private String userAgent; /** * Provides a custom executor. * * <p>It's an optional parameter. If the user has not provided an executor when the channel is * built, the builder will use a static cached thread pool. * * <p>The channel won't take ownership of the given executor. It's caller's responsibility to * shut down the executor when it's desired. */ public final BuilderT executor(ExecutorService executor) { this.executor = executor; return thisT(); } /** * Adds interceptors that will be called before the channel performs its real work. This is * functionally equivalent to using {@link ClientInterceptors#intercept(Channel, List)}, but while * still having access to the original {@code ChannelImpl}. */ public final BuilderT intercept(List<ClientInterceptor> interceptors) { this.interceptors.addAll(interceptors); return thisT(); } /** * Adds interceptors that will be called before the channel performs its real work. This is * functionally equivalent to using {@link ClientInterceptors#intercept(Channel, * ClientInterceptor...)}, but while still having access to the original {@code ChannelImpl}. */ public final BuilderT intercept(ClientInterceptor... interceptors) { return intercept(Arrays.asList(interceptors)); } private BuilderT thisT() { @SuppressWarnings("unchecked") BuilderT thisT = (BuilderT) this; return thisT; } /** * Provides a custom {@code User-Agent} for the application. * * <p>It's an optional parameter. If provided, the given agent will be prepended by the * grpc {@code User-Agent}. */ @SuppressWarnings("unchecked") public final BuilderT userAgent(String userAgent) { this.userAgent = userAgent; return (BuilderT) this; } /** * Builds a channel using the given parameters. */ public ChannelImpl build() { ClientTransportFactory transportFactory = buildTransportFactory(); return new ChannelImpl(transportFactory, executor, userAgent, interceptors); } /** * Children of AbstractChannelBuilder should override this method to provide the * {@link ClientTransportFactory} appropriate for this channel. This method is meant for * Transport implementors and should not be used by normal users. */ @Internal protected abstract ClientTransportFactory buildTransportFactory(); }
aglne/grpc-java
core/src/main/java/io/grpc/AbstractChannelBuilder.java
Java
bsd-3-clause
4,534
package org.basex.query.func.fn; import static org.basex.query.QueryError.*; import org.basex.query.*; import org.basex.query.expr.*; import org.basex.query.func.*; import org.basex.query.iter.*; import org.basex.query.value.item.*; import org.basex.query.value.type.*; import org.basex.query.var.*; import org.basex.util.*; /** * Function implementation. * * @author BaseX Team 2005-16, BSD License * @author Christian Gruen */ public final class FnExactlyOne extends StandardFunc { @Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { final Iter ir = exprs[0].iter(qc); final Item it = ir.next(); if(it == null || ir.next() != null) throw EXACTLYONE.get(info); return it; } @Override protected Expr opt(final QueryContext qc, final VarScope scp) { final Expr e = exprs[0]; final SeqType st = e.seqType(); if(st.one()) return e; seqType = SeqType.get(st.type, seqType.occ); return this; } }
drmacro/basex
basex-core/src/main/java/org/basex/query/func/fn/FnExactlyOne.java
Java
bsd-3-clause
990
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Atn { /// <summary> /// Represents a single action which can be executed following the successful /// match of a lexer rule. /// </summary> /// <remarks> /// Represents a single action which can be executed following the successful /// match of a lexer rule. Lexer actions are used for both embedded action syntax /// and ANTLR 4's new lexer command syntax. /// </remarks> /// <author>Sam Harwell</author> /// <since>4.2</since> public interface ILexerAction { /// <summary>Gets the serialization type of the lexer action.</summary> /// <remarks>Gets the serialization type of the lexer action.</remarks> /// <returns>The serialization type of the lexer action.</returns> [NotNull] LexerActionType ActionType { get; } /// <summary>Gets whether the lexer action is position-dependent.</summary> /// <remarks> /// Gets whether the lexer action is position-dependent. Position-dependent /// actions may have different semantics depending on the /// <see cref="Antlr4.Runtime.ICharStream"/> /// index at the time the action is executed. /// <p>Many lexer commands, including /// <c>type</c> /// , /// <c>skip</c> /// , and /// <c>more</c> /// , do not check the input index during their execution. /// Actions like this are position-independent, and may be stored more /// efficiently as part of the /// <see cref="ATNConfig.ActionExecutor()"/> /// .</p> /// </remarks> /// <returns> /// /// <see langword="true"/> /// if the lexer action semantics can be affected by the /// position of the input /// <see cref="Antlr4.Runtime.ICharStream"/> /// at the time it is executed; /// otherwise, /// <see langword="false"/> /// . /// </returns> bool IsPositionDependent { get; } /// <summary> /// Execute the lexer action in the context of the specified /// <see cref="Antlr4.Runtime.Lexer"/> /// . /// <p>For position-dependent actions, the input stream must already be /// positioned correctly prior to calling this method.</p> /// </summary> /// <param name="lexer">The lexer instance.</param> void Execute(Lexer lexer); } }
Pursuit92/antlr4
runtime/CSharp/runtime/CSharp/Antlr4.Runtime/Atn/ILexerAction.cs
C#
bsd-3-clause
2,812
FROM node:9.10.1 COPY ./ ./ RUN npm install ENV NODE_HANDLER sequelize-postgres CMD ["node", "app.js"]
zapov/FrameworkBenchmarks
frameworks/JavaScript/nodejs/nodejs-postgres.dockerfile
Dockerfile
bsd-3-clause
107
/** * $RCSfile$ * $Revision: 11613 $ * $Date: 2010-02-09 03:55:56 -0800 (Tue, 09 Feb 2010) $ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import org.jivesoftware.smack.packet.Message; import java.util.Set; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CopyOnWriteArraySet; /** * A chat is a series of messages sent between two users. Each chat has a unique * thread ID, which is used to track which messages are part of a particular * conversation. Some messages are sent without a thread ID, and some clients * don't send thread IDs at all. Therefore, if a message without a thread ID * arrives it is routed to the most recently created Chat with the message * sender. * * @author Matt Tucker */ public class Chat { private ChatManager chatManager; private String threadID; private String participant; private final Set<MessageListener> listeners = new CopyOnWriteArraySet<MessageListener>(); /** * Creates a new chat with the specified user and thread ID. * * @param chatManager the chatManager the chat will use. * @param participant the user to chat with. * @param threadID the thread ID to use. */ Chat(ChatManager chatManager, String participant, String threadID) { this.chatManager = chatManager; this.participant = participant; this.threadID = threadID; } /** * Returns the thread id associated with this chat, which corresponds to the * <tt>thread</tt> field of XMPP messages. This method may return <tt>null</tt> * if there is no thread ID is associated with this Chat. * * @return the thread ID of this chat. */ public String getThreadID() { return threadID; } /** * Returns the name of the user the chat is with. * * @return the name of the user the chat is occuring with. */ public String getParticipant() { return participant; } /** * Sends the specified text as a message to the other chat participant. * This is a convenience method for: * * <pre> * Message message = chat.createMessage(); * message.setBody(messageText); * chat.sendMessage(message); * </pre> * * @param text the text to send. * @throws XMPPException if sending the message fails. */ public void sendMessage(String text) throws XMPPException { Message message = new Message(participant, Message.Type.chat); message.setThread(threadID); message.setBody(text); chatManager.sendMessage(this, message); } /** * Sends a message to the other chat participant. The thread ID, recipient, * and message type of the message will automatically set to those of this chat. * * @param message the message to send. * @throws XMPPException if an error occurs sending the message. */ public void sendMessage(Message message) throws XMPPException { // Force the recipient, message type, and thread ID since the user elected // to send the message through this chat object. message.setTo(participant); message.setType(Message.Type.chat); message.setThread(threadID); chatManager.sendMessage(this, message); } /** * Adds a packet listener that will be notified of any new messages in the * chat. * * @param listener a packet listener. */ public void addMessageListener(MessageListener listener) { if(listener == null) { return; } // TODO these references should be weak. listeners.add(listener); } public void removeMessageListener(MessageListener listener) { listeners.remove(listener); } /** * Returns an unmodifiable collection of all of the listeners registered with this chat. * * @return an unmodifiable collection of all of the listeners registered with this chat. */ public Collection<MessageListener> getListeners() { return Collections.unmodifiableCollection(listeners); } /** * Creates a {@link org.jivesoftware.smack.PacketCollector} which will accumulate the Messages * for this chat. Always cancel PacketCollectors when finished with them as they will accumulate * messages indefinitely. * * @return the PacketCollector which returns Messages for this chat. */ public PacketCollector createCollector() { return chatManager.createPacketCollector(this); } /** * Delivers a message directly to this chat, which will add the message * to the collector and deliver it to all listeners registered with the * Chat. This is used by the Connection class to deliver messages * without a thread ID. * * @param message the message. */ void deliver(Message message) { // Because the collector and listeners are expecting a thread ID with // a specific value, set the thread ID on the message even though it // probably never had one. message.setThread(threadID); for (MessageListener listener : listeners) { listener.processMessage(this, message); } } @Override public boolean equals(Object obj) { return obj instanceof Chat && threadID.equals(((Chat)obj).getThreadID()) && participant.equals(((Chat)obj).getParticipant()); } }
UzxMx/java-bells
lib-src/smack_src_3_3_0/source/org/jivesoftware/smack/Chat.java
Java
bsd-3-clause
6,098
/*- * Copyright (c) 2010-2012 Semihalf. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <libgeom.h> #include <sys/types.h> #include <sys/disk.h> #include <dev/nand/nand_dev.h> #include "nandtool.h" int nand_read_oob(struct cmd_param *params) { struct chip_param_io chip_params; struct nand_oob_rw req; char *dev, *out; int fd = -1, fd_out = -1, ret = 0; int page; uint8_t *buf = NULL; if ((page = param_get_int(params, "page")) < 0) { fprintf(stderr, "You must supply valid 'page' argument.\n"); return (1); } if (!(dev = param_get_string(params, "dev"))) { fprintf(stderr, "You must supply 'dev' argument.\n"); return (1); } if ((out = param_get_string(params, "out"))) { if ((fd_out = open(out, O_WRONLY | O_CREAT)) == -1) { perrorf("Cannot open %s", out); ret = 1; goto out; } } if ((fd = g_open(dev, 1)) == -1) { perrorf("Cannot open %s", dev); ret = 1; goto out; } if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) == -1) { perrorf("Cannot ioctl(NAND_IO_GET_CHIP_PARAM)"); ret = 1; goto out; } buf = malloc(chip_params.oob_size); if (buf == NULL) { perrorf("Cannot allocate %d bytes\n", chip_params.oob_size); ret = 1; goto out; } req.page = page; req.len = chip_params.oob_size; req.data = buf; if (ioctl(fd, NAND_IO_OOB_READ, &req) == -1) { perrorf("Cannot read OOB from %s", dev); ret = 1; goto out; } if (fd_out != -1) write(fd_out, buf, chip_params.oob_size); else hexdump(buf, chip_params.oob_size); out: close(fd_out); if (fd != -1) g_close(fd); if (buf) free(buf); return (ret); }
jhbsz/OSI-OS
usr.sbin/nandtool/nand_readoob.c
C
bsd-3-clause
2,996
// Copyright (c) 2012 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. #ifndef NET_BASE_UPLOAD_DATA_STREAM_H_ #define NET_BASE_UPLOAD_DATA_STREAM_H_ #include <stdint.h> #include <memory> #include <vector> #include "base/macros.h" #include "net/base/completion_callback.h" #include "net/base/net_export.h" namespace net { class DrainableIOBuffer; class IOBuffer; class UploadElementReader; // A class for retrieving all data to be sent as a request body. Supports both // chunked and non-chunked uploads. class NET_EXPORT UploadDataStream { public: // |identifier| identifies a particular upload instance, which is used by the // cache to formulate a cache key. This value should be unique across browser // sessions. A value of 0 is used to indicate an unspecified identifier. UploadDataStream(bool is_chunked, int64_t identifier); virtual ~UploadDataStream(); // Initializes the stream. This function must be called before calling any // other method. It is not valid to call any method (other than the // destructor) if Init() fails. This method can be called multiple times. // Calling this method after an Init() success results in resetting the // state (i.e. the stream is rewound). // // Does the initialization synchronously and returns the result if possible, // otherwise returns ERR_IO_PENDING and runs the callback with the result. // // Returns OK on success. Returns ERR_UPLOAD_FILE_CHANGED if the expected // file modification time is set (usually not set, but set for sliced // files) and the target file is changed. int Init(const CompletionCallback& callback); // When possible, reads up to |buf_len| bytes synchronously from the upload // data stream to |buf| and returns the number of bytes read; otherwise, // returns ERR_IO_PENDING and calls |callback| with the number of bytes read. // Partial reads are allowed. Zero is returned on a call to Read when there // are no remaining bytes in the stream, and IsEof() will return true // hereafter. // // If there's less data to read than we initially observed (i.e. the actual // upload data is smaller than size()), zeros are padded to ensure that // size() bytes can be read, which can happen for TYPE_FILE payloads. // // Reads are currently not allowed to fail - they must either return // a value >= 0 or ERR_IO_PENDING, and call OnReadCompleted with a // value >= 0. // TODO(mmenke): Investigate letting reads fail. int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback); // Returns the total size of the data stream and the current position. // When the data is chunked, always returns zero. Must always return the same // value after each call to Initialize(). uint64_t size() const { return total_size_; } uint64_t position() const { return current_position_; } // See constructor for description. int64_t identifier() const { return identifier_; } bool is_chunked() const { return is_chunked_; } // Returns true if all data has been consumed from this upload data // stream. For chunked uploads, returns false until the first read attempt. // This makes some state machines a little simpler. bool IsEOF() const; // Cancels all pending callbacks, and resets state. Any IOBuffer currently // being read to is not safe for future use, as it may be in use on another // thread. void Reset(); // Returns true if the upload data in the stream is entirely in memory, and // all read requests will succeed synchronously. Expected to return false for // chunked requests. virtual bool IsInMemory() const; // Returns a list of element readers owned by |this|, if it has any. virtual const std::vector<std::unique_ptr<UploadElementReader>>* GetElementReaders() const; protected: // Must be called by subclasses when InitInternal and ReadInternal complete // asynchronously. void OnInitCompleted(int result); void OnReadCompleted(int result); // Must be called before InitInternal completes, for non-chunked uploads. // Must not be called for chunked uploads. void SetSize(uint64_t size); // Must be called for chunked uploads before the final ReadInternal call // completes. Must not be called for non-chunked uploads. void SetIsFinalChunk(); private: // See Init(). If it returns ERR_IO_PENDING, OnInitCompleted must be called // once it completes. If the upload is not chunked, SetSize must be called // before it completes. virtual int InitInternal() = 0; // See Read(). For chunked uploads, must call SetIsFinalChunk if this is the // final chunk. For non-chunked uploads, the UploadDataStream determins which // read is the last based on size. Must read 1 or more bytes on every call, // though the final chunk may be 0 bytes, for chunked requests. If it returns // ERR_IO_PENDING, OnInitCompleted must be called once it completes. Must not // return any error, other than ERR_IO_PENDING. virtual int ReadInternal(IOBuffer* buf, int buf_len) = 0; // Resets state and cancels any pending callbacks. Guaranteed to be called // before all but the first call to InitInternal. virtual void ResetInternal() = 0; uint64_t total_size_; uint64_t current_position_; const int64_t identifier_; const bool is_chunked_; // True if the initialization was successful. bool initialized_successfully_; bool is_eof_; CompletionCallback callback_; DISALLOW_COPY_AND_ASSIGN(UploadDataStream); }; } // namespace net #endif // NET_BASE_UPLOAD_DATA_STREAM_H_
axinging/chromium-crosswalk
net/base/upload_data_stream.h
C
bsd-3-clause
5,642
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2011 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef PANGOLIN_DISPLAY_GLUT_H #define PANGOLIN_DISPLAY_GLUT_H #include <pangolin/platform.h> #include <pangolin/gl/glinclude.h> #include <string> #ifndef GLUT_DOUBLE // Avoid pulling in all of glut just for these defines. #define GLUT_RGB 0x0000 #define GLUT_RGBA 0x0000 #define GLUT_INDEX 0x0001 #define GLUT_SINGLE 0x0000 #define GLUT_DOUBLE 0x0002 #define GLUT_ACCUM 0x0004 #define GLUT_ALPHA 0x0008 #define GLUT_DEPTH 0x0010 #define GLUT_STENCIL 0x0020 #define GLUT_MULTISAMPLE 0x0080 #define GLUT_STEREO 0x0100 #define GLUT_LUMINANCE 0x0200 #endif namespace pangolin { /// Create GLUT window and bind Pangolin to it. /// All GLUT initialisation is taken care of. This prevents you /// from needing to call BindToContext() and TakeGlutCallbacks(). PANGOLIN_EXPORT void CreateGlutWindowAndBind(std::string window_title, int w = 640, int h = 480, unsigned int mode = GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH ); /// Applies any post-render events if they are defined, /// swaps buffers and processes events. Also resets viewport to /// entire window and disables scissoring. PANGOLIN_EXPORT void FinishGlutFrame(); /// Swaps OpenGL Buffers and processes input events. PANGOLIN_EXPORT void SwapGlutBuffersProcessGlutEvents(); /// Allow Pangolin to take GLUT callbacks for its own uses. /// Not needed if you instantiated a window through CreateWindowAndBind(). PANGOLIN_EXPORT void TakeGlutCallbacks(); } #endif // PANGOLIN_DISPLAY_GLUT_H
suzlab/Autoware
ros/src/computing/perception/localization/packages/orb_localizer/Thirdparty/Pangolin/include/pangolin/display/device/display_glut.h
C
bsd-3-clause
2,742
""" Test cases for the template loaders Note: This test requires setuptools! """ from django.conf import settings if __name__ == '__main__': settings.configure() import unittest import sys import pkg_resources import imp import StringIO import os.path from django.template import TemplateDoesNotExist from django.template.loaders.eggs import load_template_source as lts_egg # Mock classes and objects for pkg_resources functions. class MockProvider(pkg_resources.NullProvider): def __init__(self, module): pkg_resources.NullProvider.__init__(self, module) self.module = module def _has(self, path): return path in self.module._resources def _isdir(self,path): return False def get_resource_stream(self, manager, resource_name): return self.module._resources[resource_name] def _get(self, path): return self.module._resources[path].read() class MockLoader(object): pass def create_egg(name, resources): """ Creates a mock egg with a list of resources. name: The name of the module. resources: A dictionary of resources. Keys are the names and values the data. """ egg = imp.new_module(name) egg.__loader__ = MockLoader() egg._resources = resources sys.modules[name] = egg class EggLoader(unittest.TestCase): def setUp(self): pkg_resources._provider_factories[MockLoader] = MockProvider self.empty_egg = create_egg("egg_empty", {}) self.egg_1 = create_egg("egg_1", { os.path.normcase('templates/y.html') : StringIO.StringIO("y"), os.path.normcase('templates/x.txt') : StringIO.StringIO("x"), }) self._old_installed_apps = settings.INSTALLED_APPS settings.INSTALLED_APPS = [] def tearDown(self): settings.INSTALLED_APPS = self._old_installed_apps def test_empty(self): "Loading any template on an empty egg should fail" settings.INSTALLED_APPS = ['egg_empty'] self.assertRaises(TemplateDoesNotExist, lts_egg, "not-existing.html") def test_non_existing(self): "Template loading fails if the template is not in the egg" settings.INSTALLED_APPS = ['egg_1'] self.assertRaises(TemplateDoesNotExist, lts_egg, "not-existing.html") def test_existing(self): "A template can be loaded from an egg" settings.INSTALLED_APPS = ['egg_1'] contents, template_name = lts_egg("y.html") self.assertEqual(contents, "y") self.assertEqual(template_name, "egg:egg_1:templates/y.html") def test_not_installed(self): "Loading an existent template from an egg not included in INSTALLED_APPS should fail" settings.INSTALLED_APPS = [] self.assertRaises(TemplateDoesNotExist, lts_egg, "y.html") if __name__ == "__main__": unittest.main()
grangier/django-11599
tests/regressiontests/templates/loaders.py
Python
bsd-3-clause
2,859
#include "FLA_f2c.h" void d_cnjg(doublecomplex *dest, doublecomplex *src) { dest->r = src->r ; dest->i = -(src->i); }
yaowee/libflame
src/flablas/f2c/other/util/d_cnjg.c
C
bsd-3-clause
124
// lat/arctic-weight.h // Copyright 2012 Johns Hopkins University (Author: Guoguo Chen) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #ifndef KALDI_LAT_ARCTIC_WEIGHT_H_ #define KALDI_LAT_ARCTIC_WEIGHT_H_ #include "fst/float-weight.h" namespace fst { // Arctic semiring: (max, +, inf, 0) // We define the Arctic semiring T' = (R \cup {-inf, +inf}, max, +, -inf, 0). // The term "Arctic" came from Keith Kintzley (kintzley@jhu.edu), as opposite // to the Tropical semiring. template <class T> class ArcticWeightTpl : public FloatWeightTpl<T> { public: using FloatWeightTpl<T>::Value; typedef ArcticWeightTpl<T> ReverseWeight; ArcticWeightTpl() : FloatWeightTpl<T>() {} ArcticWeightTpl(T f) : FloatWeightTpl<T>(f) {} ArcticWeightTpl(const ArcticWeightTpl<T> &w) : FloatWeightTpl<T>(w) {} static const ArcticWeightTpl<T> Zero() { return ArcticWeightTpl<T>(-numeric_limits<T>::infinity()); } static const ArcticWeightTpl<T> One() { return ArcticWeightTpl<T>(0.0F); } static const string &Type() { static const string type = "arctic" + FloatWeightTpl<T>::GetPrecisionString(); return type; } static ArcticWeightTpl<T> NoWeight() { return ArcticWeightTpl<T>(numeric_limits<T>::infinity()); } bool Member() const { // First part fails for IEEE NaN return Value() == Value() && Value() != numeric_limits<T>::infinity(); } ArcticWeightTpl<T> Quantize(float delta = kDelta) const { if (Value() == -numeric_limits<T>::infinity() || Value() == numeric_limits<T>::infinity() || Value() != Value()) return *this; else return ArcticWeightTpl<T>(floor(Value() / delta + 0.5F) * delta); } ArcticWeightTpl<T> Reverse() const { return *this; } static uint64 Properties() { return kLeftSemiring | kRightSemiring | kCommutative | kPath | kIdempotent; } }; // Single precision arctic weight typedef ArcticWeightTpl<float> ArcticWeight; template <class T> inline ArcticWeightTpl<T> Plus(const ArcticWeightTpl<T> &w1, const ArcticWeightTpl<T> &w2) { return w1.Value() > w2.Value() ? w1 : w2; } inline ArcticWeightTpl<float> Plus(const ArcticWeightTpl<float> &w1, const ArcticWeightTpl<float> &w2) { return Plus<float>(w1, w2); } inline ArcticWeightTpl<double> Plus(const ArcticWeightTpl<double> &w1, const ArcticWeightTpl<double> &w2) { return Plus<double>(w1, w2); } template <class T> inline ArcticWeightTpl<T> Times(const ArcticWeightTpl<T> &w1, const ArcticWeightTpl<T> &w2) { T f1 = w1.Value(), f2 = w2.Value(); if (f1 == -numeric_limits<T>::infinity()) return w1; else if (f2 == -numeric_limits<T>::infinity()) return w2; else return ArcticWeightTpl<T>(f1 + f2); } inline ArcticWeightTpl<float> Times(const ArcticWeightTpl<float> &w1, const ArcticWeightTpl<float> &w2) { return Times<float>(w1, w2); } inline ArcticWeightTpl<double> Times(const ArcticWeightTpl<double> &w1, const ArcticWeightTpl<double> &w2) { return Times<double>(w1, w2); } template <class T> inline ArcticWeightTpl<T> Divide(const ArcticWeightTpl<T> &w1, const ArcticWeightTpl<T> &w2, DivideType typ = DIVIDE_ANY) { T f1 = w1.Value(), f2 = w2.Value(); if (f2 == -numeric_limits<T>::infinity()) return numeric_limits<T>::quiet_NaN(); else if (f1 == -numeric_limits<T>::infinity()) return -numeric_limits<T>::infinity(); else return ArcticWeightTpl<T>(f1 - f2); } inline ArcticWeightTpl<float> Divide(const ArcticWeightTpl<float> &w1, const ArcticWeightTpl<float> &w2, DivideType typ = DIVIDE_ANY) { return Divide<float>(w1, w2, typ); } inline ArcticWeightTpl<double> Divide(const ArcticWeightTpl<double> &w1, const ArcticWeightTpl<double> &w2, DivideType typ = DIVIDE_ANY) { return Divide<double>(w1, w2, typ); } } // namespace fst #endif // KALDI_LAT_ARCTIC_WEIGHT_H_
ypkang/djinn
tonic-suite/asr/src/lat/arctic-weight.h
C
bsd-3-clause
4,868
/* * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2009, 2010, 2011 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef InlineBox_h #define InlineBox_h #include "core/rendering/FloatToLayoutUnit.h" #include "core/rendering/RenderBoxModelObject.h" #include "core/rendering/RenderObjectInlines.h" #include "platform/text/TextDirection.h" namespace blink { class HitTestRequest; class HitTestResult; class RootInlineBox; enum MarkLineBoxes { MarkLineBoxesDirty, DontMarkLineBoxes }; // InlineBox represents a rectangle that occurs on a line. It corresponds to // some RenderObject (i.e., it represents a portion of that RenderObject). class InlineBox { WTF_MAKE_NONCOPYABLE(InlineBox); public: InlineBox(RenderObject& obj) : m_next(0) , m_prev(0) , m_parent(0) , m_renderer(obj) , m_logicalWidth() #if ENABLE(ASSERT) , m_hasBadParent(false) #endif { } InlineBox(RenderObject& obj, FloatPointWillBeLayoutPoint topLeft, FloatWillBeLayoutUnit logicalWidth, bool firstLine, bool constructed, bool dirty, bool extracted, bool isHorizontal, InlineBox* next, InlineBox* prev, InlineFlowBox* parent) : m_next(next) , m_prev(prev) , m_parent(parent) , m_renderer(obj) , m_topLeft(topLeft) , m_logicalWidth(logicalWidth) , m_bitfields(firstLine, constructed, dirty, extracted, isHorizontal) #if ENABLE(ASSERT) , m_hasBadParent(false) #endif { } virtual ~InlineBox(); virtual void destroy() { delete this; } virtual void deleteLine(); virtual void extractLine(); virtual void attachLine(); virtual bool isLineBreak() const { return false; } virtual void adjustPosition(FloatWillBeLayoutUnit dx, FloatWillBeLayoutUnit dy); void adjustLogicalPosition(FloatWillBeLayoutUnit deltaLogicalLeft, FloatWillBeLayoutUnit deltaLogicalTop) { if (isHorizontal()) adjustPosition(deltaLogicalLeft, deltaLogicalTop); else adjustPosition(deltaLogicalTop, deltaLogicalLeft); } void adjustLineDirectionPosition(FloatWillBeLayoutUnit delta) { if (isHorizontal()) adjustPosition(delta, 0); else adjustPosition(0, delta); } void adjustBlockDirectionPosition(FloatWillBeLayoutUnit delta) { if (isHorizontal()) adjustPosition(0, delta); else adjustPosition(delta, 0); } virtual void paint(const PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom); virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom); // InlineBoxes are allocated out of the rendering partition. void* operator new(size_t); void operator delete(void*); #ifndef NDEBUG void showTreeForThis() const; void showLineTreeForThis() const; virtual void showBox(int = 0) const; virtual void showLineTreeAndMark(const InlineBox* = 0, const char* = 0, const InlineBox* = 0, const char* = 0, const RenderObject* = 0, int = 0) const; virtual const char* boxName() const; #endif bool isText() const { return m_bitfields.isText(); } void setIsText(bool isText) { m_bitfields.setIsText(isText); } virtual bool isInlineFlowBox() const { return false; } virtual bool isInlineTextBox() const { return false; } virtual bool isRootInlineBox() const { return false; } virtual bool isSVGInlineTextBox() const { return false; } virtual bool isSVGInlineFlowBox() const { return false; } virtual bool isSVGRootInlineBox() const { return false; } bool hasVirtualLogicalHeight() const { return m_bitfields.hasVirtualLogicalHeight(); } void setHasVirtualLogicalHeight() { m_bitfields.setHasVirtualLogicalHeight(true); } virtual FloatWillBeLayoutUnit virtualLogicalHeight() const { ASSERT_NOT_REACHED(); return FloatWillBeLayoutUnit(); } bool isHorizontal() const { return m_bitfields.isHorizontal(); } void setIsHorizontal(bool isHorizontal) { m_bitfields.setIsHorizontal(isHorizontal); } virtual FloatRectWillBeLayoutRect calculateBoundaries() const { ASSERT_NOT_REACHED(); return FloatRectWillBeLayoutRect(); } bool isConstructed() { return m_bitfields.constructed(); } virtual void setConstructed() { m_bitfields.setConstructed(true); } void setExtracted(bool extracted = true) { m_bitfields.setExtracted(extracted); } void setFirstLineStyleBit(bool firstLine) { m_bitfields.setFirstLine(firstLine); } bool isFirstLineStyle() const { return m_bitfields.firstLine(); } void remove(MarkLineBoxes = MarkLineBoxesDirty); InlineBox* nextOnLine() const { return m_next; } InlineBox* prevOnLine() const { return m_prev; } void setNextOnLine(InlineBox* next) { ASSERT(m_parent || !next); m_next = next; } void setPrevOnLine(InlineBox* prev) { ASSERT(m_parent || !prev); m_prev = prev; } bool nextOnLineExists() const; virtual bool isLeaf() const { return true; } InlineBox* nextLeafChild() const; InlineBox* prevLeafChild() const; // Helper functions for editing and hit-testing code. // FIXME: These two functions should be moved to RenderedPosition once the code to convert between // Position and inline box, offset pair is moved to RenderedPosition. InlineBox* nextLeafChildIgnoringLineBreak() const; InlineBox* prevLeafChildIgnoringLineBreak() const; RenderObject& renderer() const { return m_renderer; } InlineFlowBox* parent() const { ASSERT(!m_hasBadParent); return m_parent; } void setParent(InlineFlowBox* par) { m_parent = par; } const RootInlineBox& root() const; RootInlineBox& root(); // x() is the left side of the box in the containing block's coordinate system. void setX(FloatWillBeLayoutUnit x) { m_topLeft.setX(x); } FloatWillBeLayoutUnit x() const { return m_topLeft.x(); } FloatWillBeLayoutUnit left() const { return m_topLeft.x(); } // y() is the top side of the box in the containing block's coordinate system. void setY(FloatWillBeLayoutUnit y) { m_topLeft.setY(y); } FloatWillBeLayoutUnit y() const { return m_topLeft.y(); } FloatWillBeLayoutUnit top() const { return m_topLeft.y(); } const FloatPointWillBeLayoutPoint& topLeft() const { return m_topLeft; } FloatWillBeLayoutUnit width() const { return isHorizontal() ? logicalWidth() : hasVirtualLogicalHeight() ? virtualLogicalHeight() : logicalHeight(); } FloatWillBeLayoutUnit height() const { return isHorizontal() ? hasVirtualLogicalHeight() ? virtualLogicalHeight() : logicalHeight() : logicalWidth(); } FloatSizeWillBeLayoutSize size() const { return FloatSizeWillBeLayoutSize(width(), height()); } FloatWillBeLayoutUnit right() const { return left() + width(); } FloatWillBeLayoutUnit bottom() const { return top() + height(); } // The logicalLeft position is the left edge of the line box in a horizontal line and the top edge in a vertical line. FloatWillBeLayoutUnit logicalLeft() const { return isHorizontal() ? m_topLeft.x() : m_topLeft.y(); } FloatWillBeLayoutUnit logicalRight() const { return logicalLeft() + logicalWidth(); } void setLogicalLeft(FloatWillBeLayoutUnit left) { if (isHorizontal()) setX(left); else setY(left); } int pixelSnappedLogicalLeft() const { return logicalLeft(); } int pixelSnappedLogicalRight() const { return ceilf(logicalRight()); } int pixelSnappedLogicalTop() const { return logicalTop(); } int pixelSnappedLogicalBottom() const { return ceilf(logicalBottom()); } // The logicalTop[ position is the top edge of the line box in a horizontal line and the left edge in a vertical line. FloatWillBeLayoutUnit logicalTop() const { return isHorizontal() ? m_topLeft.y() : m_topLeft.x(); } FloatWillBeLayoutUnit logicalBottom() const { return logicalTop() + logicalHeight(); } void setLogicalTop(FloatWillBeLayoutUnit top) { if (isHorizontal()) setY(top); else setX(top); } // The logical width is our extent in the line's overall inline direction, i.e., width for horizontal text and height for vertical text. void setLogicalWidth(FloatWillBeLayoutUnit w) { m_logicalWidth = w; } FloatWillBeLayoutUnit logicalWidth() const { return m_logicalWidth; } // The logical height is our extent in the block flow direction, i.e., height for horizontal text and width for vertical text. FloatWillBeLayoutUnit logicalHeight() const; FloatRectWillBeLayoutRect logicalFrameRect() const { return isHorizontal() ? FloatRectWillBeLayoutRect(m_topLeft.x(), m_topLeft.y(), m_logicalWidth, logicalHeight()) : FloatRectWillBeLayoutRect(m_topLeft.y(), m_topLeft.x(), m_logicalWidth, logicalHeight()); } virtual int baselinePosition(FontBaseline baselineType) const; virtual LayoutUnit lineHeight() const; virtual int caretMinOffset() const; virtual int caretMaxOffset() const; unsigned char bidiLevel() const { return m_bitfields.bidiEmbeddingLevel(); } void setBidiLevel(unsigned char level) { m_bitfields.setBidiEmbeddingLevel(level); } TextDirection direction() const { return bidiLevel() % 2 ? RTL : LTR; } bool isLeftToRightDirection() const { return direction() == LTR; } int caretLeftmostOffset() const { return isLeftToRightDirection() ? caretMinOffset() : caretMaxOffset(); } int caretRightmostOffset() const { return isLeftToRightDirection() ? caretMaxOffset() : caretMinOffset(); } virtual void clearTruncation() { } bool isDirty() const { return m_bitfields.dirty(); } virtual void markDirty() { m_bitfields.setDirty(true); } virtual void dirtyLineBoxes(); virtual RenderObject::SelectionState selectionState() const; virtual bool canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth) const; // visibleLeftEdge, visibleRightEdge are in the parent's coordinate system. virtual FloatWillBeLayoutUnit placeEllipsisBox(bool ltr, FloatWillBeLayoutUnit visibleLeftEdge, FloatWillBeLayoutUnit visibleRightEdge, FloatWillBeLayoutUnit ellipsisWidth, FloatWillBeLayoutUnit &truncatedWidth, bool&); #if ENABLE(ASSERT) void setHasBadParent(); #endif int expansion() const { return m_bitfields.expansion(); } bool visibleToHitTestRequest(const HitTestRequest& request) const { return renderer().visibleToHitTestRequest(request); } EVerticalAlign verticalAlign() const { return renderer().style(m_bitfields.firstLine())->verticalAlign(); } // Use with caution! The type is not checked! RenderBoxModelObject* boxModelObject() const { if (!renderer().isText()) return toRenderBoxModelObject(&renderer()); return 0; } FloatPointWillBeLayoutPoint locationIncludingFlipping(); void flipForWritingMode(FloatRect&); FloatPoint flipForWritingMode(const FloatPoint&); void flipForWritingMode(LayoutRect&); LayoutPoint flipForWritingMode(const LayoutPoint&); bool knownToHaveNoOverflow() const { return m_bitfields.knownToHaveNoOverflow(); } void clearKnownToHaveNoOverflow(); bool dirOverride() const { return m_bitfields.dirOverride(); } void setDirOverride(bool dirOverride) { m_bitfields.setDirOverride(dirOverride); } #define ADD_BOOLEAN_BITFIELD(name, Name) \ private:\ unsigned m_##name : 1;\ public:\ bool name() const { return m_##name; }\ void set##Name(bool name) { m_##name = name; }\ class InlineBoxBitfields { public: InlineBoxBitfields(bool firstLine = false, bool constructed = false, bool dirty = false, bool extracted = false, bool isHorizontal = true) : m_firstLine(firstLine) , m_constructed(constructed) , m_bidiEmbeddingLevel(0) , m_dirty(dirty) , m_extracted(extracted) , m_hasVirtualLogicalHeight(false) , m_isHorizontal(isHorizontal) , m_endsWithBreak(false) , m_hasSelectedChildrenOrCanHaveLeadingExpansion(false) , m_knownToHaveNoOverflow(true) , m_hasEllipsisBoxOrHyphen(false) , m_dirOverride(false) , m_isText(false) , m_determinedIfNextOnLineExists(false) , m_nextOnLineExists(false) , m_expansion(0) { } // Some of these bits are actually for subclasses and moved here to compact the structures. // for this class ADD_BOOLEAN_BITFIELD(firstLine, FirstLine); ADD_BOOLEAN_BITFIELD(constructed, Constructed); private: unsigned m_bidiEmbeddingLevel : 6; // The maximium bidi level is 62: http://unicode.org/reports/tr9/#Explicit_Levels_and_Directions public: unsigned char bidiEmbeddingLevel() const { return m_bidiEmbeddingLevel; } void setBidiEmbeddingLevel(unsigned char bidiEmbeddingLevel) { m_bidiEmbeddingLevel = bidiEmbeddingLevel; } ADD_BOOLEAN_BITFIELD(dirty, Dirty); ADD_BOOLEAN_BITFIELD(extracted, Extracted); ADD_BOOLEAN_BITFIELD(hasVirtualLogicalHeight, HasVirtualLogicalHeight); ADD_BOOLEAN_BITFIELD(isHorizontal, IsHorizontal); // for RootInlineBox ADD_BOOLEAN_BITFIELD(endsWithBreak, EndsWithBreak); // Whether the line ends with a <br>. // shared between RootInlineBox and InlineTextBox ADD_BOOLEAN_BITFIELD(hasSelectedChildrenOrCanHaveLeadingExpansion, HasSelectedChildrenOrCanHaveLeadingExpansion); ADD_BOOLEAN_BITFIELD(knownToHaveNoOverflow, KnownToHaveNoOverflow); ADD_BOOLEAN_BITFIELD(hasEllipsisBoxOrHyphen, HasEllipsisBoxOrHyphen); // for InlineTextBox ADD_BOOLEAN_BITFIELD(dirOverride, DirOverride); ADD_BOOLEAN_BITFIELD(isText, IsText); // Whether or not this object represents text with a non-zero height. Includes non-image list markers, text boxes. private: mutable unsigned m_determinedIfNextOnLineExists : 1; public: bool determinedIfNextOnLineExists() const { return m_determinedIfNextOnLineExists; } void setDeterminedIfNextOnLineExists(bool determinedIfNextOnLineExists) const { m_determinedIfNextOnLineExists = determinedIfNextOnLineExists; } private: mutable unsigned m_nextOnLineExists : 1; public: bool nextOnLineExists() const { return m_nextOnLineExists; } void setNextOnLineExists(bool nextOnLineExists) const { m_nextOnLineExists = nextOnLineExists; } private: signed m_expansion : 12; // for justified text public: signed expansion() const { return m_expansion; } void setExpansion(signed expansion) { m_expansion = expansion; } }; #undef ADD_BOOLEAN_BITFIELD private: InlineBox* m_next; // The next element on the same line as us. InlineBox* m_prev; // The previous element on the same line as us. InlineFlowBox* m_parent; // The box that contains us. RenderObject& m_renderer; protected: // For RootInlineBox bool endsWithBreak() const { return m_bitfields.endsWithBreak(); } void setEndsWithBreak(bool endsWithBreak) { m_bitfields.setEndsWithBreak(endsWithBreak); } bool hasEllipsisBox() const { return m_bitfields.hasEllipsisBoxOrHyphen(); } bool hasSelectedChildren() const { return m_bitfields.hasSelectedChildrenOrCanHaveLeadingExpansion(); } void setHasSelectedChildren(bool hasSelectedChildren) { m_bitfields.setHasSelectedChildrenOrCanHaveLeadingExpansion(hasSelectedChildren); } void setHasEllipsisBox(bool hasEllipsisBox) { m_bitfields.setHasEllipsisBoxOrHyphen(hasEllipsisBox); } // For InlineTextBox bool hasHyphen() const { return m_bitfields.hasEllipsisBoxOrHyphen(); } void setHasHyphen(bool hasHyphen) { m_bitfields.setHasEllipsisBoxOrHyphen(hasHyphen); } bool canHaveLeadingExpansion() const { return m_bitfields.hasSelectedChildrenOrCanHaveLeadingExpansion(); } void setCanHaveLeadingExpansion(bool canHaveLeadingExpansion) { m_bitfields.setHasSelectedChildrenOrCanHaveLeadingExpansion(canHaveLeadingExpansion); } signed expansion() { return m_bitfields.expansion(); } void setExpansion(signed expansion) { m_bitfields.setExpansion(expansion); } // For InlineFlowBox and InlineTextBox bool extracted() const { return m_bitfields.extracted(); } FloatPointWillBeLayoutPoint m_topLeft; FloatWillBeLayoutUnit m_logicalWidth; private: InlineBoxBitfields m_bitfields; #if ENABLE(ASSERT) bool m_hasBadParent; #endif }; #if !ENABLE(ASSERT) inline InlineBox::~InlineBox() { } #endif #if ENABLE(ASSERT) inline void InlineBox::setHasBadParent() { m_hasBadParent = true; } #endif #define DEFINE_INLINE_BOX_TYPE_CASTS(typeName) \ DEFINE_TYPE_CASTS(typeName, InlineBox, box, box->is##typeName(), box.is##typeName()) // Allow equality comparisons of InlineBox's by reference or pointer, interchangeably. DEFINE_COMPARISON_OPERATORS_WITH_REFERENCES(InlineBox) } // namespace blink #ifndef NDEBUG // Outside the WebCore namespace for ease of invocation from gdb. void showTree(const blink::InlineBox*); void showLineTree(const blink::InlineBox*); #endif #endif // InlineBox_h
mxOBS/deb-pkg_trusty_chromium-browser
third_party/WebKit/Source/core/rendering/InlineBox.h
C
bsd-3-clause
18,214
// // LERequest_A03010201.h // LoveEye // // Created by Flynn on 15/8/4. // Copyright (c) 2015年 Fly. All rights reserved. // #import <Foundation/Foundation.h> @interface LERequest_A03010201 : NSObject typedef void (^LEBlock_A03010201)(NSArray *wikiListArr, NSError *error); @property(nonatomic, copy) LEBlock_A03010201 callbackBlock; @property (strong, nonatomic) NSMutableDictionary *parametersDictionary; - (void) requestParams:(NSDictionary*)params; - (void) postDataWithBlock:(LEBlock_A03010201)finishBlock; @end
IphoneCoder/LoveEyeProject
LoveEye/LoveEye/Class/request/LERequest_A03010201.h
C
bsd-3-clause
535
<!doctype html> <!-- This file is generated by build.py. --> <title>Reference for embed wide.jpg; overflow:hidden; -o-object-fit:none; -o-object-position:100% center</title> <link rel="stylesheet" href="../../support/reftests.css"> <style> .helper { overflow:hidden } .helper > * { right:0; top:36.0px; } </style> <div id="ref"> <span class="helper"><img src="../../support/wide.jpg"></span> </div>
frivoal/presto-testo
css/image-fit/reftests/embed-jpg-wide/hidden_none_100_center-ref.html
HTML
bsd-3-clause
403
Nette Sandbox ============= Sandbox is a pre-packaged and pre-configured Nette Framework application that you can use as the skeleton for your new applications. [Nette](http://nette.org) is a popular tool for PHP web development. It is designed to be the most usable and friendliest as possible. It focuses on security and performance and is definitely one of the safest PHP frameworks. Installing ---------- The best way to install Sandbox is using Composer. If you don't have Composer yet, download it following [the instructions](http://doc.nette.org/composer). Then use command: composer create-project nette/sandbox my-app cd my-app Make directories `temp` and `log` writable. Navigate your browser to the `www` directory and you will see a welcome page. PHP 5.4 allows you run `php -S localhost:8888 -t www` to start the web server and then visit `http://localhost:8888` in your browser. It is CRITICAL that whole `app`, `log` and `temp` directories are NOT accessible directly via a web browser! See [security warning](http://nette.org/security-warning). License ------- - Nette: New BSD License or GPL 2.0 or 3.0 (http://nette.org/license) - Adminer: Apache License 2.0 or GPL 2 (http://www.adminer.org)
racinmat/BoardManager
readme.md
Markdown
bsd-3-clause
1,226
// Copyright (c) 2012 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. #ifndef GPU_COMMAND_BUFFER_SERVICE_GLES2_CMD_DECODER_UNITTEST_BASE_H_ #define GPU_COMMAND_BUFFER_SERVICE_GLES2_CMD_DECODER_UNITTEST_BASE_H_ #include "gpu/command_buffer/common/gles2_cmd_format.h" #include "gpu/command_buffer/common/gles2_cmd_utils.h" #include "gpu/command_buffer/service/buffer_manager.h" #include "gpu/command_buffer/service/cmd_buffer_engine.h" #include "gpu/command_buffer/service/context_group.h" #include "gpu/command_buffer/service/framebuffer_manager.h" #include "gpu/command_buffer/service/gl_context_mock.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/gles2_cmd_decoder_mock.h" #include "gpu/command_buffer/service/program_manager.h" #include "gpu/command_buffer/service/query_manager.h" #include "gpu/command_buffer/service/renderbuffer_manager.h" #include "gpu/command_buffer/service/shader_manager.h" #include "gpu/command_buffer/service/test_helper.h" #include "gpu/command_buffer/service/texture_manager.h" #include "gpu/command_buffer/service/valuebuffer_manager.h" #include "gpu/command_buffer/service/vertex_array_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gl/gl_surface_stub.h" #include "ui/gl/gl_mock.h" #include "ui/gl/gl_version_info.h" namespace base { class CommandLine; } namespace gpu { namespace gles2 { class MemoryTracker; class GLES2DecoderTestBase : public ::testing::TestWithParam<bool> { public: GLES2DecoderTestBase(); virtual ~GLES2DecoderTestBase(); // Template to call glGenXXX functions. template <typename T> void GenHelper(GLuint client_id) { int8 buffer[sizeof(T) + sizeof(client_id)]; T& cmd = *reinterpret_cast<T*>(&buffer); cmd.Init(1, &client_id); EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(client_id))); } // This template exists solely so we can specialize it for // certain commands. template <typename T, int id> void SpecializedSetup(bool valid) { } template <typename T> T* GetImmediateAs() { return reinterpret_cast<T*>(immediate_buffer_); } template <typename T, typename Command> T GetImmediateDataAs(Command* cmd) { return reinterpret_cast<T>(ImmediateDataAddress(cmd)); } void ClearSharedMemory() { engine_->ClearSharedMemory(); } void SetUp() override; void TearDown() override; template <typename T> error::Error ExecuteCmd(const T& cmd) { static_assert(T::kArgFlags == cmd::kFixed, "T::kArgFlags should equal cmd::kFixed"); return decoder_->DoCommands( 1, (const void*)&cmd, ComputeNumEntries(sizeof(cmd)), 0); } template <typename T> error::Error ExecuteImmediateCmd(const T& cmd, size_t data_size) { static_assert(T::kArgFlags == cmd::kAtLeastN, "T::kArgFlags should equal cmd::kAtLeastN"); return decoder_->DoCommands( 1, (const void*)&cmd, ComputeNumEntries(sizeof(cmd) + data_size), 0); } template <typename T> T GetSharedMemoryAs() { return reinterpret_cast<T>(shared_memory_address_); } template <typename T> T GetSharedMemoryAsWithOffset(uint32 offset) { void* ptr = reinterpret_cast<int8*>(shared_memory_address_) + offset; return reinterpret_cast<T>(ptr); } Buffer* GetBuffer(GLuint service_id) { return group_->buffer_manager()->GetBuffer(service_id); } Framebuffer* GetFramebuffer(GLuint service_id) { return group_->framebuffer_manager()->GetFramebuffer(service_id); } Renderbuffer* GetRenderbuffer( GLuint service_id) { return group_->renderbuffer_manager()->GetRenderbuffer(service_id); } TextureRef* GetTexture(GLuint client_id) { return group_->texture_manager()->GetTexture(client_id); } Shader* GetShader(GLuint client_id) { return group_->shader_manager()->GetShader(client_id); } Program* GetProgram(GLuint client_id) { return group_->program_manager()->GetProgram(client_id); } Valuebuffer* GetValuebuffer(GLuint client_id) { return group_->valuebuffer_manager()->GetValuebuffer(client_id); } QueryManager::Query* GetQueryInfo(GLuint client_id) { return decoder_->GetQueryManager()->GetQuery(client_id); } bool GetSamplerServiceId(GLuint client_id, GLuint* service_id) const { return group_->GetSamplerServiceId(client_id, service_id); } bool GetTransformFeedbackServiceId( GLuint client_id, GLuint* service_id) const { return group_->GetTransformFeedbackServiceId(client_id, service_id); } bool GetSyncServiceId(GLuint client_id, GLsync* service_id) const { return group_->GetSyncServiceId(client_id, service_id); } // This name doesn't match the underlying function, but doing it this way // prevents the need to special-case the unit test generation VertexAttribManager* GetVertexArrayInfo(GLuint client_id) { return decoder_->GetVertexArrayManager()->GetVertexAttribManager(client_id); } ProgramManager* program_manager() { return group_->program_manager(); } ValuebufferManager* valuebuffer_manager() { return group_->valuebuffer_manager(); } ValueStateMap* pending_valuebuffer_state() { return group_->pending_valuebuffer_state(); } FeatureInfo* feature_info() { return group_->feature_info(); } ImageManager* GetImageManager() { return decoder_->GetImageManager(); } void DoCreateProgram(GLuint client_id, GLuint service_id); void DoCreateShader(GLenum shader_type, GLuint client_id, GLuint service_id); void DoFenceSync(GLuint client_id, GLuint service_id); void SetBucketData(uint32_t bucket_id, const void* data, uint32_t data_size); void SetBucketAsCString(uint32 bucket_id, const char* str); // If we want a valid bucket, just set |count_in_header| as |count|, // and set |str_end| as 0. void SetBucketAsCStrings(uint32 bucket_id, GLsizei count, const char** str, GLsizei count_in_header, char str_end); void set_memory_tracker(MemoryTracker* memory_tracker) { memory_tracker_ = memory_tracker; } struct InitState { InitState(); std::string extensions; std::string gl_version; bool has_alpha; bool has_depth; bool has_stencil; bool request_alpha; bool request_depth; bool request_stencil; bool bind_generates_resource; bool lose_context_when_out_of_memory; bool use_native_vao; // default is true. unsigned webgl_version; // default to 0, i.e., not WebGL context. }; void InitDecoder(const InitState& init); void InitDecoderWithCommandLine(const InitState& init, const base::CommandLine* command_line); void ResetDecoder(); const ContextGroup& group() const { return *group_.get(); } void LoseContexts(error::ContextLostReason reason) const { group_->LoseContexts(reason); } ::testing::StrictMock< ::gfx::MockGLInterface>* GetGLMock() const { return gl_.get(); } GLES2Decoder* GetDecoder() const { return decoder_.get(); } typedef TestHelper::AttribInfo AttribInfo; typedef TestHelper::UniformInfo UniformInfo; void SetupShader( AttribInfo* attribs, size_t num_attribs, UniformInfo* uniforms, size_t num_uniforms, GLuint client_id, GLuint service_id, GLuint vertex_shader_client_id, GLuint vertex_shader_service_id, GLuint fragment_shader_client_id, GLuint fragment_shader_service_id); void SetupInitCapabilitiesExpectations(bool es3_capable); void SetupInitStateExpectations(); void ExpectEnableDisable(GLenum cap, bool enable); // Setups up a shader for testing glUniform. void SetupShaderForUniform(GLenum uniform_type); void SetupDefaultProgram(); void SetupCubemapProgram(); void SetupSamplerExternalProgram(); void SetupTexture(); // Note that the error is returned as GLint instead of GLenum. // This is because there is a mismatch in the types of GLenum and // the error values GL_NO_ERROR, GL_INVALID_ENUM, etc. GLenum is // typedef'd as unsigned int while the error values are defined as // integers. This is problematic for template functions such as // EXPECT_EQ that expect both types to be the same. GLint GetGLError(); void DoBindBuffer(GLenum target, GLuint client_id, GLuint service_id); void DoBindFramebuffer(GLenum target, GLuint client_id, GLuint service_id); void DoBindRenderbuffer(GLenum target, GLuint client_id, GLuint service_id); void DoRenderbufferStorageMultisampleCHROMIUM(GLenum target, GLsizei samples, GLenum internal_format, GLenum gl_format, GLsizei width, GLsizei height); void RestoreRenderbufferBindings(); void EnsureRenderbufferBound(bool expect_bind); void DoBindTexture(GLenum target, GLuint client_id, GLuint service_id); void DoBindVertexArrayOES(GLuint client_id, GLuint service_id); bool DoIsBuffer(GLuint client_id); bool DoIsFramebuffer(GLuint client_id); bool DoIsProgram(GLuint client_id); bool DoIsRenderbuffer(GLuint client_id); bool DoIsShader(GLuint client_id); bool DoIsTexture(GLuint client_id); void DoDeleteBuffer(GLuint client_id, GLuint service_id); void DoDeleteFramebuffer( GLuint client_id, GLuint service_id, bool reset_draw, GLenum draw_target, GLuint draw_id, bool reset_read, GLenum read_target, GLuint read_id); void DoDeleteProgram(GLuint client_id, GLuint service_id); void DoDeleteRenderbuffer(GLuint client_id, GLuint service_id); void DoDeleteShader(GLuint client_id, GLuint service_id); void DoDeleteTexture(GLuint client_id, GLuint service_id); void DoCompressedTexImage2D( GLenum target, GLint level, GLenum format, GLsizei width, GLsizei height, GLint border, GLsizei size, uint32 bucket_id); void DoBindTexImage2DCHROMIUM(GLenum target, GLint image_id); void DoTexImage2D( GLenum target, GLint level, GLenum internal_format, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, uint32 shared_memory_id, uint32 shared_memory_offset); void DoTexImage2DConvertInternalFormat( GLenum target, GLint level, GLenum requested_internal_format, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, uint32 shared_memory_id, uint32 shared_memory_offset, GLenum expected_internal_format); void DoRenderbufferStorage( GLenum target, GLenum internal_format, GLenum actual_format, GLsizei width, GLsizei height, GLenum error); void DoFramebufferRenderbuffer( GLenum target, GLenum attachment, GLenum renderbuffer_target, GLuint renderbuffer_client_id, GLuint renderbuffer_service_id, GLenum error); void DoFramebufferTexture2D( GLenum target, GLenum attachment, GLenum tex_target, GLuint texture_client_id, GLuint texture_service_id, GLint level, GLenum error); void DoVertexAttribPointer( GLuint index, GLint size, GLenum type, GLsizei stride, GLuint offset); void DoVertexAttribDivisorANGLE(GLuint index, GLuint divisor); void DoEnableDisable(GLenum cap, bool enable); void DoEnableVertexAttribArray(GLint index); void DoBufferData(GLenum target, GLsizei size); void DoBufferSubData( GLenum target, GLint offset, GLsizei size, const void* data); void DoScissor(GLint x, GLint y, GLsizei width, GLsizei height); void SetupVertexBuffer(); void SetupAllNeededVertexBuffers(); void SetupIndexBuffer(); void DeleteVertexBuffer(); void DeleteIndexBuffer(); void SetupClearTextureExpectations(GLuint service_id, GLuint old_service_id, GLenum bind_target, GLenum target, GLint level, GLenum internal_format, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height); void SetupExpectationsForRestoreClearState(GLclampf restore_red, GLclampf restore_green, GLclampf restore_blue, GLclampf restore_alpha, GLuint restore_stencil, GLclampf restore_depth, bool restore_scissor_test, GLint restore_scissor_x, GLint restore_scissor_y, GLsizei restore_scissor_width, GLsizei restore_scissor_height); void SetupExpectationsForFramebufferClearing(GLenum target, GLuint clear_bits, GLclampf restore_red, GLclampf restore_green, GLclampf restore_blue, GLclampf restore_alpha, GLuint restore_stencil, GLclampf restore_depth, bool restore_scissor_test, GLint restore_scissor_x, GLint restore_scissor_y, GLsizei restore_scissor_width, GLsizei restore_scissor_height); void SetupExpectationsForFramebufferClearingMulti( GLuint read_framebuffer_service_id, GLuint draw_framebuffer_service_id, GLenum target, GLuint clear_bits, GLclampf restore_red, GLclampf restore_green, GLclampf restore_blue, GLclampf restore_alpha, GLuint restore_stencil, GLclampf restore_depth, bool restore_scissor_test, GLint restore_scissor_x, GLint restore_scissor_y, GLsizei restore_scissor_width, GLsizei restore_scissor_height); void SetupExpectationsForDepthMask(bool mask); void SetupExpectationsForEnableDisable(GLenum cap, bool enable); void SetupExpectationsForColorMask(bool red, bool green, bool blue, bool alpha); void SetupExpectationsForStencilMask(GLuint front_mask, GLuint back_mask); void SetupExpectationsForApplyingDirtyState( bool framebuffer_is_rgb, bool framebuffer_has_depth, bool framebuffer_has_stencil, GLuint color_bits, // NOTE! bits are 0x1000, 0x0100, 0x0010, and 0x0001 bool depth_mask, bool depth_enabled, GLuint front_stencil_mask, GLuint back_stencil_mask, bool stencil_enabled); void SetupExpectationsForApplyingDefaultDirtyState(); void AddExpectationsForSimulatedAttrib0WithError( GLsizei num_vertices, GLuint buffer_id, GLenum error); void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id); void AddExpectationsForGenVertexArraysOES(); void AddExpectationsForDeleteVertexArraysOES(); void AddExpectationsForDeleteBoundVertexArraysOES(); void AddExpectationsForBindVertexArrayOES(); void AddExpectationsForRestoreAttribState(GLuint attrib); GLvoid* BufferOffset(unsigned i) { return static_cast<int8 *>(NULL)+(i); } template <typename Command, typename Result> bool IsObjectHelper(GLuint client_id) { Result* result = static_cast<Result*>(shared_memory_address_); Command cmd; cmd.Init(client_id, kSharedMemoryId, kSharedMemoryOffset); EXPECT_EQ(error::kNoError, ExecuteCmd(cmd)); bool isObject = static_cast<bool>(*result); EXPECT_EQ(GL_NO_ERROR, GetGLError()); return isObject; } protected: static const int kBackBufferWidth = 128; static const int kBackBufferHeight = 64; static const GLint kMaxTextureSize = 2048; static const GLint kMaxCubeMapTextureSize = 256; static const GLint kNumVertexAttribs = 16; static const GLint kNumTextureUnits = 8; static const GLint kMaxTextureImageUnits = 8; static const GLint kMaxVertexTextureImageUnits = 2; static const GLint kMaxFragmentUniformVectors = 16; static const GLint kMaxVaryingVectors = 8; static const GLint kMaxVertexUniformVectors = 128; static const GLint kMaxViewportWidth = 8192; static const GLint kMaxViewportHeight = 8192; static const GLint kViewportX = 0; static const GLint kViewportY = 0; static const GLint kViewportWidth = kBackBufferWidth; static const GLint kViewportHeight = kBackBufferHeight; static const GLuint kServiceAttrib0BufferId = 801; static const GLuint kServiceFixedAttribBufferId = 802; static const GLuint kServiceBufferId = 301; static const GLuint kServiceFramebufferId = 302; static const GLuint kServiceRenderbufferId = 303; static const GLuint kServiceTextureId = 304; static const GLuint kServiceProgramId = 305; static const GLuint kServiceSamplerId = 306; static const GLuint kServiceShaderId = 307; static const GLuint kServiceElementBufferId = 308; static const GLuint kServiceQueryId = 309; static const GLuint kServiceVertexArrayId = 310; static const GLuint kServiceTransformFeedbackId = 311; static const GLuint kServiceSyncId = 312; static const int32 kSharedMemoryId = 401; static const size_t kSharedBufferSize = 2048; static const uint32 kSharedMemoryOffset = 132; static const int32 kInvalidSharedMemoryId = 402; static const uint32 kInvalidSharedMemoryOffset = kSharedBufferSize + 1; static const uint32 kInitialResult = 0xBDBDBDBDu; static const uint8 kInitialMemoryValue = 0xBDu; static const uint32 kNewClientId = 501; static const uint32 kNewServiceId = 502; static const uint32 kInvalidClientId = 601; static const GLuint kServiceVertexShaderId = 321; static const GLuint kServiceFragmentShaderId = 322; static const GLuint kServiceCopyTextureChromiumShaderId = 701; static const GLuint kServiceCopyTextureChromiumProgramId = 721; static const GLuint kServiceCopyTextureChromiumTextureBufferId = 751; static const GLuint kServiceCopyTextureChromiumVertexBufferId = 752; static const GLuint kServiceCopyTextureChromiumFBOId = 753; static const GLuint kServiceCopyTextureChromiumPositionAttrib = 761; static const GLuint kServiceCopyTextureChromiumTexAttrib = 762; static const GLuint kServiceCopyTextureChromiumSamplerLocation = 763; static const GLsizei kNumVertices = 100; static const GLsizei kNumIndices = 10; static const int kValidIndexRangeStart = 1; static const int kValidIndexRangeCount = 7; static const int kInvalidIndexRangeStart = 0; static const int kInvalidIndexRangeCount = 7; static const int kOutOfRangeIndexRangeEnd = 10; static const GLuint kMaxValidIndex = 7; static const GLint kMaxAttribLength = 10; static const char* kAttrib1Name; static const char* kAttrib2Name; static const char* kAttrib3Name; static const GLint kAttrib1Size = 1; static const GLint kAttrib2Size = 1; static const GLint kAttrib3Size = 1; static const GLint kAttrib1Location = 0; static const GLint kAttrib2Location = 1; static const GLint kAttrib3Location = 2; static const GLenum kAttrib1Type = GL_FLOAT_VEC4; static const GLenum kAttrib2Type = GL_FLOAT_VEC2; static const GLenum kAttrib3Type = GL_FLOAT_VEC3; static const GLint kInvalidAttribLocation = 30; static const GLint kBadAttribIndex = kNumVertexAttribs; static const GLint kMaxUniformLength = 12; static const char* kUniform1Name; static const char* kUniform2Name; static const char* kUniform3Name; static const GLint kUniform1Size = 1; static const GLint kUniform2Size = 3; static const GLint kUniform3Size = 2; static const GLint kUniform1RealLocation = 3; static const GLint kUniform2RealLocation = 10; static const GLint kUniform2ElementRealLocation = 12; static const GLint kUniform3RealLocation = 20; static const GLint kUniform1FakeLocation = 0; // These are static const GLint kUniform2FakeLocation = 1; // hardcoded static const GLint kUniform2ElementFakeLocation = 0x10001; // to match static const GLint kUniform3FakeLocation = 2; // ProgramManager. static const GLint kUniform1DesiredLocation = -1; static const GLint kUniform2DesiredLocation = -1; static const GLint kUniform3DesiredLocation = -1; static const GLenum kUniform1Type = GL_SAMPLER_2D; static const GLenum kUniform2Type = GL_INT_VEC2; static const GLenum kUniform3Type = GL_FLOAT_VEC3; static const GLenum kUniformSamplerExternalType = GL_SAMPLER_EXTERNAL_OES; static const GLenum kUniformCubemapType = GL_SAMPLER_CUBE; static const GLint kInvalidUniformLocation = 30; static const GLint kBadUniformIndex = 1000; // Use StrictMock to make 100% sure we know how GL will be called. scoped_ptr< ::testing::StrictMock< ::gfx::MockGLInterface> > gl_; scoped_refptr<gfx::GLSurfaceStub> surface_; scoped_refptr<GLContextMock> context_; scoped_ptr<MockGLES2Decoder> mock_decoder_; scoped_ptr<GLES2Decoder> decoder_; MemoryTracker* memory_tracker_; GLuint client_buffer_id_; GLuint client_framebuffer_id_; GLuint client_program_id_; GLuint client_renderbuffer_id_; GLuint client_sampler_id_; GLuint client_shader_id_; GLuint client_texture_id_; GLuint client_element_buffer_id_; GLuint client_vertex_shader_id_; GLuint client_fragment_shader_id_; GLuint client_query_id_; GLuint client_vertexarray_id_; GLuint client_valuebuffer_id_; GLuint client_transformfeedback_id_; GLuint client_sync_id_; uint32 shared_memory_id_; uint32 shared_memory_offset_; void* shared_memory_address_; void* shared_memory_base_; GLuint service_renderbuffer_id_; bool service_renderbuffer_valid_; uint32 immediate_buffer_[64]; const bool ignore_cached_state_for_test_; bool cached_color_mask_red_; bool cached_color_mask_green_; bool cached_color_mask_blue_; bool cached_color_mask_alpha_; bool cached_depth_mask_; GLuint cached_stencil_front_mask_; GLuint cached_stencil_back_mask_; struct EnableFlags { EnableFlags(); bool cached_blend; bool cached_cull_face; bool cached_depth_test; bool cached_dither; bool cached_polygon_offset_fill; bool cached_sample_alpha_to_coverage; bool cached_sample_coverage; bool cached_scissor_test; bool cached_stencil_test; }; EnableFlags enable_flags_; private: class MockCommandBufferEngine : public CommandBufferEngine { public: MockCommandBufferEngine(); ~MockCommandBufferEngine() override; scoped_refptr<gpu::Buffer> GetSharedMemoryBuffer(int32 shm_id) override; void ClearSharedMemory() { memset(valid_buffer_->memory(), kInitialMemoryValue, kSharedBufferSize); } void set_token(int32 token) override; bool SetGetBuffer(int32 /* transfer_buffer_id */) override; // Overridden from CommandBufferEngine. bool SetGetOffset(int32 offset) override; // Overridden from CommandBufferEngine. int32 GetGetOffset() override; private: scoped_refptr<gpu::Buffer> valid_buffer_; scoped_refptr<gpu::Buffer> invalid_buffer_; }; // MockGLStates is used to track GL states and emulate driver // behaviors on top of MockGLInterface. class MockGLStates { public: MockGLStates() : bound_array_buffer_object_(0), bound_vertex_array_object_(0) { } ~MockGLStates() { } void OnBindArrayBuffer(GLuint id) { bound_array_buffer_object_ = id; } void OnBindVertexArrayOES(GLuint id) { bound_vertex_array_object_ = id; } void OnVertexAttribNullPointer() { // When a vertex array object is bound, some drivers (AMD Linux, // Qualcomm, etc.) have a bug where it incorrectly generates an // GL_INVALID_OPERATION on glVertexAttribPointer() if pointer // is NULL, no buffer is bound on GL_ARRAY_BUFFER. // Make sure we don't trigger this bug. if (bound_vertex_array_object_ != 0) EXPECT_TRUE(bound_array_buffer_object_ != 0); } private: GLuint bound_array_buffer_object_; GLuint bound_vertex_array_object_; }; // class MockGLStates void AddExpectationsForVertexAttribManager(); void SetupMockGLBehaviors(); scoped_ptr< ::testing::StrictMock<MockCommandBufferEngine> > engine_; scoped_refptr<ContextGroup> group_; MockGLStates gl_states_; }; class GLES2DecoderWithShaderTestBase : public GLES2DecoderTestBase { public: GLES2DecoderWithShaderTestBase() : GLES2DecoderTestBase() { } protected: void SetUp() override; void TearDown() override; }; // SpecializedSetup specializations that are needed in multiple unittest files. template <> void GLES2DecoderTestBase::SpecializedSetup<cmds::LinkProgram, 0>(bool valid); } // namespace gles2 } // namespace gpu #endif // GPU_COMMAND_BUFFER_SERVICE_GLES2_CMD_DECODER_UNITTEST_BASE_H_
Chilledheart/chromium
gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.h
C
bsd-3-clause
25,716
/* jshint latedef: false */ (function () { 'use strict'; angular .module('apigility.rest') .controller('Rest', Rest); Rest.$inject = [ 'api', '$modal', '$stateParams', '$rootScope', 'SidebarService', '$state', '$scope', '$sce', 'documentation']; function Rest(api, $modal, $stateParams, $rootScope, SidebarService, $state, $scope, $sce, documentation) { /* jshint validthis:true */ var vm = this; vm.apiName = $stateParams.api; vm.version = $stateParams.ver; vm.restName = $stateParams.rest; vm.httpMethods = [ 'GET', 'POST', 'PUT', 'PATCH', 'DELETE']; vm.disabled = !SidebarService.isLastVersion(vm.version, vm.apiName); vm.selectorNames = []; function initGeneral() { vm.tags = { accept_whitelist : [], content_type_whitelist : [] }; api.getHydrators(function(result){ vm.hydrators = result; }); api.getDatabase(function(err, response){ vm.db = response; }); api.getDoctrineAdapters(function(err, response) { vm.doctrine = response.doctrine_adapter; }); api.getRest(vm.apiName, vm.version, vm.restName, function(result){ vm.rest = result; vm.isDoctrine = angular.isDefined(result.object_manager); vm.rest.accept_whitelist.forEach(function(entry){ vm.tags.accept_whitelist.push({ text : entry }); }); vm.rest.content_type_whitelist.forEach(function(entry){ vm.tags.content_type_whitelist.push({ text : entry }); }); if (vm.isDoctrine) { if (vm.rest.strategies.length === 0) { vm.rest.strategies = {}; } api.getRestDoctrineMetadata(result.object_manager, result.entity_class, function(err, response) { if (err) { console.log(response); return; } vm.doctrineMetadata = response; }); } if (vm.rest.hasOwnProperty('table_name') && vm.rest.hasOwnProperty('db')) { for (var i = 0; i < vm.db.db_adapter.length; i++) { if (vm.db.db_adapter[i].adapter_name == vm.rest.adapter_name) { vm.adapter = vm.db.db_adapter[i]; break; } } } vm.rest.source_code = [ { name : 'Collection Class', classname: vm.rest.collection_class }, { name : 'Entity Class', classname: vm.rest.entity_class }, ]; if (vm.rest.resource_class) { vm.rest.source_code.push( { name : 'Resource Class', classname: vm.rest.resource_class }, { name : 'Resource Factory', classname: vm.rest.resource_class + 'Factory' } ); } vm.getSourceCode(vm.rest.source_code[0].classname); vm.source = vm.rest.source_code[0]; api.getContentNegotiation(function(result){ vm.content_negotiation = result; for (var property in result) { vm.selectorNames.push(result[property].content_name); } }); }); } vm.selectHydrator = function($item, $model) { }; function initAuthorization() { api.getAuthorizationRest(vm.apiName, vm.version, vm.restName, function(err, result){ if (err) { console.log('Error getting the authorization data'); return; } vm.auth = result; }); } initGeneral(); initAuthorization(); vm.saveGeneral = function() { vm.loading = true; if (vm.adapter) { vm.rest.adapter_name = vm.adapter.adapter_name; } if (vm.rest.hydrator_name.name) { vm.rest.hydrator_name = vm.rest.hydrator_name.name; } api.updateGeneralRest(vm.apiName, vm.version, vm.restName, vm.rest, vm.isDoctrine, function(err, result){ vm.loading = false; if (err) { vm.alert = result; return; } }); }; vm.resetGeneral = function() { initGeneral(); }; vm.newDoctrineStrategyModal = function () { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/new-doctrinestrategy.html', controller: 'NewDoctrineStrategy', controllerAs: 'vm', resolve : { fields : function() { return vm.doctrineMetadata.fieldNames; } } }); modalInstance.result.then(function (response) { vm.rest.strategies[response.field] = response.strategy; }); }; vm.removeStrategy = function(key) { delete vm.rest.strategies[key]; }; vm.hasProperties = function(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) return true; } return false; }; vm.saveContentNegotiation = function() { vm.loading = true; vm.rest.accept_whitelist = vm.tags.accept_whitelist.map(api.mapTagInput); vm.rest.content_type_whitelist = vm.tags.content_type_whitelist.map(api.mapTagInput); api.updateContentNegotiationRest(vm.apiName, vm.version, vm.restName, vm.rest, function(err, result){ vm.loading = false; if (err) { vm.alert = result; return; } }); }; vm.resetContentNegotiation = function() { initGeneral(); }; vm.saveAuthorization = function() { vm.loading = true; api.saveAuthorizationRest(vm.apiName, vm.version, vm.restName, vm.auth, function(err, result){ vm.loading = false; if (err) { vm.alert = result; return; } }); }; vm.resetAuthorization = function() { initAuthorization(); }; vm.saveDocumentation = function() { api.saveRestDoc(vm.apiName, vm.version, vm.restName, vm.rest.documentation, function(err,result){ vm.loading = false; if (err) { vm.alert = result; return; } }); }; vm.resetDocumentation = function() { initGeneral(); }; vm.deleteRestModal = function() { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/delete-rest.html', controller: 'DeleteRest', controllerAs: 'vm', resolve: { isDoctrine: function() { return vm.rest.object_manager !== undefined; } } }); modalInstance.result.then(function (response) { SidebarService.removeRestService(response.api, response.service); $state.go('ag.apimodule', {api: response.api, ver: response.version}, {reload: true}); }); }; vm.newFieldModal = function() { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/new-field.html', controller: 'NewField', controllerAs: 'vm', resolve : { fields : function() { return vm.rest.fields; }, type : function() { return 'rest'; } } }); modalInstance.result.then(function (response) { vm.rest.fields = response; }); }; vm.editFieldModal = function(field) { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/edit-field.html', controller: 'EditField', controllerAs: 'vm', resolve : { field : function() { return field; }, fields : function() { return vm.rest.fields; }, type : function() { return 'rest'; } } }); modalInstance.result.then(function (response) { vm.rest.fields = response; }); }; vm.deleteFieldModal = function(field) { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/delete-field.html', controller: 'DeleteField', controllerAs: 'vm', resolve : { field : function() { return field; }, fields : function() { return vm.rest.fields; }, type : function() { return 'rest'; } } }); modalInstance.result.then(function (response) { vm.rest.fields = response; }); }; vm.addValidatorModal = function(field) { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/add-validator.html', controller: 'AddValidator', controllerAs: 'vm', resolve : { field : function() { return field; }, fields : function() { return vm.rest.fields; }, type : function() { return 'rest'; } } }); modalInstance.result.then(function (response) { vm.rest.fields = response; }); }; vm.editValidatorModal = function(field, validator) { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/edit-validator.html', controller: 'EditValidator', controllerAs: 'vm', resolve : { field : function() { return field; }, validator : function() { return validator; }, fields : function() { return vm.rest.fields; }, type : function() { return 'rest'; } } }); modalInstance.result.then(function (response) { vm.rest.fields = response; }); }; vm.addFilterModal = function(field) { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/add-filter.html', controller: 'AddFilter', controllerAs: 'vm', resolve : { field : function() { return field; }, fields : function() { return vm.rest.fields; }, type : function() { return 'rest'; } } }); modalInstance.result.then(function (response) { vm.rest.fields = response; }); }; vm.editFilterModal = function(field, filter) { var modalInstance = $modal.open({ templateUrl: 'apigility-ui/modal/edit-filter.html', controller: 'EditFilter', controllerAs: 'vm', resolve : { field : function() { return field; }, filter : function() { return filter; }, fields : function() { return vm.rest.fields; }, type : function() { return 'rest'; } } }); modalInstance.result.then(function (response) { vm.rest.fields = response; }); }; vm.getSourceCode = function(classname) { api.getSourceCode(vm.apiName, classname, function(err, response){ vm.sourcecode = $sce.trustAsHtml(response.source); vm.file = response.file; }); }; vm.generateFromConfiguration = function(method, direction, restPart) { return documentation.fromConfiguration( method, direction, restPart, vm.rest.fields, vm.tags.accept_whitelist, vm.rest.route_match, vm.rest.collection_name ); }; } })();
pradithahidayat/apigility-research
vendor/zfcampus/zf-apigility-admin-ui/src/apigility-ui/rest/rest.controller.js
JavaScript
bsd-3-clause
11,250
/* * Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ package org.antlr.v4.test.tool; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CharStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.Parser; import org.antlr.runtime.RuleReturnScope; import org.antlr.runtime.TokenSource; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.Tree; import org.antlr.runtime.tree.TreeAdaptor; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import static org.junit.Assert.assertEquals; // NO LONGER using gunit!!! public class TestASTStructure { String lexerClassName = "org.antlr.v4.parse.ANTLRLexer"; String parserClassName = "org.antlr.v4.parse.ANTLRParser"; String adaptorClassName = "org.antlr.v4.parse.GrammarASTAdaptor"; public Object execParser( String ruleName, String input, int scriptLine) throws Exception { ANTLRStringStream is = new ANTLRStringStream(input); Class<? extends TokenSource> lexerClass = Class.forName(lexerClassName).asSubclass(TokenSource.class); Constructor<? extends TokenSource> lexConstructor = lexerClass.getConstructor(CharStream.class); TokenSource lexer = lexConstructor.newInstance(is); is.setLine(scriptLine); CommonTokenStream tokens = new CommonTokenStream(lexer); Class<? extends Parser> parserClass = Class.forName(parserClassName).asSubclass(Parser.class); Constructor<? extends Parser> parConstructor = parserClass.getConstructor(TokenStream.class); Parser parser = parConstructor.newInstance(tokens); // set up customized tree adaptor if necessary if ( adaptorClassName!=null ) { Method m = parserClass.getMethod("setTreeAdaptor", TreeAdaptor.class); Class<? extends TreeAdaptor> adaptorClass = Class.forName(adaptorClassName).asSubclass(TreeAdaptor.class); m.invoke(parser, adaptorClass.newInstance()); } Method ruleMethod = parserClass.getMethod(ruleName); // INVOKE RULE return ruleMethod.invoke(parser); } @Test public void test_grammarSpec1() throws Exception { // gunit test on line 15 RuleReturnScope rstruct = (RuleReturnScope)execParser("grammarSpec", "parser grammar P; a : A;", 15); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(PARSER_GRAMMAR P (RULES (RULE a (BLOCK (ALT A)))))"; assertEquals("testing rule grammarSpec", expecting, actual); } @Test public void test_grammarSpec2() throws Exception { // gunit test on line 18 RuleReturnScope rstruct = (RuleReturnScope)execParser("grammarSpec", "\n parser grammar P;\n tokens { A, B }\n @header {foo}\n a : A;\n ", 18); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(PARSER_GRAMMAR P (tokens { A B) (@ header {foo}) (RULES (RULE a (BLOCK (ALT A)))))"; assertEquals("testing rule grammarSpec", expecting, actual); } @Test public void test_grammarSpec3() throws Exception { // gunit test on line 30 RuleReturnScope rstruct = (RuleReturnScope)execParser("grammarSpec", "\n parser grammar P;\n @header {foo}\n tokens { A,B }\n a : A;\n ", 30); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(PARSER_GRAMMAR P (@ header {foo}) (tokens { A B) (RULES (RULE a (BLOCK (ALT A)))))"; assertEquals("testing rule grammarSpec", expecting, actual); } @Test public void test_grammarSpec4() throws Exception { // gunit test on line 42 RuleReturnScope rstruct = (RuleReturnScope)execParser("grammarSpec", "\n parser grammar P;\n import A=B, C;\n a : A;\n ", 42); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(PARSER_GRAMMAR P (import (= A B) C) (RULES (RULE a (BLOCK (ALT A)))))"; assertEquals("testing rule grammarSpec", expecting, actual); } @Test public void test_delegateGrammars1() throws Exception { // gunit test on line 53 RuleReturnScope rstruct = (RuleReturnScope)execParser("delegateGrammars", "import A;", 53); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(import A)"; assertEquals("testing rule delegateGrammars", expecting, actual); } @Test public void test_rule1() throws Exception { // gunit test on line 56 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "a : A<X,Y=a.b.c>;", 56); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE a (BLOCK (ALT (A (ELEMENT_OPTIONS X (= Y a.b.c))))))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_rule2() throws Exception { // gunit test on line 58 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "A : B+;", 58); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE A (BLOCK (ALT (+ (BLOCK (ALT B))))))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_rule3() throws Exception { // gunit test on line 60 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "\n a[int i] returns [int y]\n @init {blort}\n : ID ;\n ", 60); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE a int i (returns int y) (@ init {blort}) (BLOCK (ALT ID)))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_rule4() throws Exception { // gunit test on line 75 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "\n a[int i] returns [int y]\n @init {blort}\n options {backtrack=true;}\n : ID;\n ", 75); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE a int i (returns int y) (@ init {blort}) (OPTIONS (= backtrack true)) (BLOCK (ALT ID)))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_rule5() throws Exception { // gunit test on line 88 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "\n a : ID ;\n catch[A b] {foo}\n finally {bar}\n ", 88); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE a (BLOCK (ALT ID)) (catch A b {foo}) (finally {bar}))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_rule6() throws Exception { // gunit test on line 97 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "\n a : ID ;\n catch[A a] {foo}\n catch[B b] {fu}\n finally {bar}\n ", 97); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE a (BLOCK (ALT ID)) (catch A a {foo}) (catch B b {fu}) (finally {bar}))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_rule7() throws Exception { // gunit test on line 107 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "\n\ta[int i]\n\tlocals [int a, float b]\n\t\t:\tA\n\t\t;\n\t", 107); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE a int i (locals int a, float b) (BLOCK (ALT A)))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_rule8() throws Exception { // gunit test on line 115 RuleReturnScope rstruct = (RuleReturnScope)execParser("rule", "\n\ta[int i] throws a.b.c\n\t\t:\tA\n\t\t;\n\t", 115); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(RULE a int i (throws a.b.c) (BLOCK (ALT A)))"; assertEquals("testing rule rule", expecting, actual); } @Test public void test_ebnf1() throws Exception { // gunit test on line 123 RuleReturnScope rstruct = (RuleReturnScope)execParser("ebnf", "(A|B)", 123); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(BLOCK (ALT A) (ALT B))"; assertEquals("testing rule ebnf", expecting, actual); } @Test public void test_ebnf2() throws Exception { // gunit test on line 124 RuleReturnScope rstruct = (RuleReturnScope)execParser("ebnf", "(A|B)?", 124); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(? (BLOCK (ALT A) (ALT B)))"; assertEquals("testing rule ebnf", expecting, actual); } @Test public void test_ebnf3() throws Exception { // gunit test on line 125 RuleReturnScope rstruct = (RuleReturnScope)execParser("ebnf", "(A|B)*", 125); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT A) (ALT B)))"; assertEquals("testing rule ebnf", expecting, actual); } @Test public void test_ebnf4() throws Exception { // gunit test on line 126 RuleReturnScope rstruct = (RuleReturnScope)execParser("ebnf", "(A|B)+", 126); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT A) (ALT B)))"; assertEquals("testing rule ebnf", expecting, actual); } @Test public void test_element1() throws Exception { // gunit test on line 129 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "~A", 129); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(~ (SET A))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element2() throws Exception { // gunit test on line 130 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "b+", 130); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT b)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element3() throws Exception { // gunit test on line 131 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "(b)+", 131); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT b)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element4() throws Exception { // gunit test on line 132 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "b?", 132); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(? (BLOCK (ALT b)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element5() throws Exception { // gunit test on line 133 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "(b)?", 133); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(? (BLOCK (ALT b)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element6() throws Exception { // gunit test on line 134 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "(b)*", 134); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT b)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element7() throws Exception { // gunit test on line 135 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "b*", 135); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT b)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element8() throws Exception { // gunit test on line 136 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "'while'*", 136); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT 'while')))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element9() throws Exception { // gunit test on line 137 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "'a'+", 137); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT 'a')))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element10() throws Exception { // gunit test on line 138 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "a[3]", 138); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(a 3)"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element11() throws Exception { // gunit test on line 139 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "'a'..'z'+", 139); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT (.. 'a' 'z'))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element12() throws Exception { // gunit test on line 140 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x=ID", 140); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(= x ID)"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element13() throws Exception { // gunit test on line 141 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x=ID?", 141); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(? (BLOCK (ALT (= x ID))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element14() throws Exception { // gunit test on line 142 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x=ID*", 142); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT (= x ID))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element15() throws Exception { // gunit test on line 143 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x=b", 143); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(= x b)"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element16() throws Exception { // gunit test on line 144 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x=(A|B)", 144); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(= x (BLOCK (ALT A) (ALT B)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element17() throws Exception { // gunit test on line 145 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x=~(A|B)", 145); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(= x (~ (SET A B)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element18() throws Exception { // gunit test on line 146 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x+=~(A|B)", 146); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+= x (~ (SET A B)))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element19() throws Exception { // gunit test on line 147 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x+=~(A|B)+", 147); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT (+= x (~ (SET A B))))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element20() throws Exception { // gunit test on line 148 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x=b+", 148); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT (= x b))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element21() throws Exception { // gunit test on line 149 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x+=ID*", 149); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT (+= x ID))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element22() throws Exception { // gunit test on line 150 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x+='int'*", 150); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT (+= x 'int'))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element23() throws Exception { // gunit test on line 151 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "x+=b+", 151); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(+ (BLOCK (ALT (+= x b))))"; assertEquals("testing rule element", expecting, actual); } @Test public void test_element24() throws Exception { // gunit test on line 152 RuleReturnScope rstruct = (RuleReturnScope)execParser("element", "({blort} 'x')*", 152); Object actual = ((Tree)rstruct.getTree()).toStringTree(); Object expecting = "(* (BLOCK (ALT {blort} 'x')))"; assertEquals("testing rule element", expecting, actual); } }
wjkohnen/antlr4
tool-testsuite/test/org/antlr/v4/test/tool/TestASTStructure.java
Java
bsd-3-clause
16,971
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <jni.h> #include "chrome/browser/android/chrome_startup_flags.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/command_line.h" #include "base/system/sys_info.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_switches.h" #include "components/browser_sync/browser_sync_switches.h" #include "components/dom_distiller/core/dom_distiller_switches.h" #include "media/base/media_switches.h" namespace { void SetCommandLineSwitch(const std::string& switch_string) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switch_string)) command_line->AppendSwitch(switch_string); } void SetCommandLineSwitchASCII(const std::string& switch_string, const std::string& value) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switch_string)) command_line->AppendSwitchASCII(switch_string, value); } } // namespace void SetChromeSpecificCommandLineFlags() { // Disable syncing favicons on low end devices. if (base::SysInfo::IsLowEndDevice()) SetCommandLineSwitchASCII(switches::kDisableSyncTypes, "Favicon Images"); // Enable DOM Distiller backend. SetCommandLineSwitch(switches::kEnableDomDistiller); }
ric2b/Vivaldi-browser
chromium/chrome/browser/android/chrome_startup_flags.cc
C++
bsd-3-clause
1,553
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * vie_channel_manager.cc */ #include "vie_channel_manager.h" #include "engine_configurations.h" #include "vie_defines.h" #include "critical_section_wrapper.h" #include "trace.h" #include "vie_channel.h" #include "vie_encoder.h" #include "process_thread.h" // VoiceEngine #include "voe_video_sync.h" namespace webrtc { ViEChannelManagerScoped::ViEChannelManagerScoped( const ViEChannelManager& vieChannelManager) : ViEManagerScopedBase(vieChannelManager) { } ViEChannel* ViEChannelManagerScoped::Channel(int vieChannelId) const { return static_cast<const ViEChannelManager*> (_vieManager)->ViEChannelPtr(vieChannelId); } ViEEncoder* ViEChannelManagerScoped::Encoder(int vieChannelId) const { return static_cast<const ViEChannelManager*> (_vieManager)->ViEEncoderPtr(vieChannelId); } bool ViEChannelManagerScoped::ChannelUsingViEEncoder(int channelId) const { return (static_cast<const ViEChannelManager*> (_vieManager))->ChannelUsingViEEncoder( channelId); } // ============================================================================ // VieChannelManager // ============================================================================ // ---------------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------------- ViEChannelManager::ViEChannelManager(int engineId, int numberOfCores, ViEPerformanceMonitor& viePerformanceMonitor) : _ptrChannelIdCritsect(CriticalSectionWrapper::CreateCriticalSection()), _engineId(engineId), _numberOfCores(numberOfCores), _viePerformanceMonitor(viePerformanceMonitor), _channelMap(), _freeChannelIds(new bool[kViEMaxNumberOfChannels]), _freeChannelIdsSize(kViEMaxNumberOfChannels), _vieEncoderMap(), _voiceSyncInterface(NULL), _voiceEngine(NULL), _moduleProcessThread(NULL) { WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideo, ViEId(engineId), "ViEChannelManager::ViEChannelManager(engineId: %d) - Constructor", engineId); for (int idx = 0; idx < _freeChannelIdsSize; idx++) { _freeChannelIds[idx] = true; } } // ---------------------------------------------------------------------------- // SetModuleProcessThread // Initialize the thread context used by none time critical tasks in video channels. // ---------------------------------------------------------------------------- void ViEChannelManager::SetModuleProcessThread( ProcessThread& moduleProcessThread) { assert(!_moduleProcessThread); _moduleProcessThread = &moduleProcessThread; } // ---------------------------------------------------------------------------- // Destructor // ---------------------------------------------------------------------------- ViEChannelManager::~ViEChannelManager() { WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideo, ViEId(_engineId), "ViEChannelManager Destructor, engineId: %d", _engineId); while (_channelMap.Size() != 0) { MapItem* item = _channelMap.First(); const int channelId = item->GetId(); item = NULL; DeleteChannel(channelId); } if (_voiceSyncInterface) _voiceSyncInterface->Release(); if (_ptrChannelIdCritsect) { delete _ptrChannelIdCritsect; _ptrChannelIdCritsect = NULL; } if (_freeChannelIds) { delete[] _freeChannelIds; _freeChannelIds = NULL; _freeChannelIdsSize = 0; } } // ---------------------------------------------------------------------------- // CreateChannel // // Creates a new channel. 'channelId' will be the id of the created channel // ---------------------------------------------------------------------------- int ViEChannelManager::CreateChannel(int& channelId) { CriticalSectionScoped cs(*_ptrChannelIdCritsect); // Get a free id for the new channel if (GetFreeChannelId(channelId) == false) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "Max number of channels reached: %d", _channelMap.Size()); return -1; } ViEChannel* vieChannel = new ViEChannel(channelId, _engineId, _numberOfCores, *_moduleProcessThread); if (vieChannel == NULL) { ReturnChannelId(channelId); return -1; } if (vieChannel->Init() != 0) { // Could not init channel WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s could not init channel", __FUNCTION__, channelId); ReturnChannelId(channelId); delete vieChannel; vieChannel = NULL; return -1; } // There is no ViEEncoder for this channel, create one with default settings ViEEncoder* vieEncoder = new ViEEncoder(_engineId, channelId, _numberOfCores, *_moduleProcessThread); if (vieEncoder == NULL) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s(videoChannelId: %d) - Could not create a new encoder", __FUNCTION__, channelId); delete vieChannel; return -1; } // Add to the map if (_vieEncoderMap.Insert(channelId, vieEncoder) != 0) { // Could not add to the map WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s: Could not add new encoder for video channel %d", __FUNCTION__, channelId); delete vieChannel; delete vieEncoder; return -1; } _channelMap.Insert(channelId, vieChannel); // Register the channel at the encoder RtpRtcp* ptrSendRtpRtcpModule = vieEncoder->SendRtpRtcpModule(); if (vieChannel->RegisterSendRtpRtcpModule(*ptrSendRtpRtcpModule) != 0) { assert(false); _vieEncoderMap.Erase(channelId); _channelMap.Erase(channelId); ReturnChannelId(channelId); delete vieChannel; WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, channelId), "%s: Could not register rtp module %d", __FUNCTION__, channelId); return -1; } return 0; } // ---------------------------------------------------------------------------- // CreateChannel // // Creates a channel and attaches to an already existing ViEEncoder // ---------------------------------------------------------------------------- int ViEChannelManager::CreateChannel(int& channelId, int originalChannel) { CriticalSectionScoped cs(*_ptrChannelIdCritsect); // Check that originalChannel already exists ViEEncoder* vieEncoder = ViEEncoderPtr(originalChannel); if (vieEncoder == NULL) { // The original channel doesn't exist WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s: Original channel doesn't exist", __FUNCTION__, originalChannel); return -1; } // Get a free id for the new channel if (GetFreeChannelId(channelId) == false) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "Max number of channels reached: %d", _channelMap.Size()); return -1; } ViEChannel* vieChannel = new ViEChannel(channelId, _engineId, _numberOfCores, *_moduleProcessThread); if (vieChannel == NULL) { ReturnChannelId(channelId); return -1; } if (vieChannel->Init() != 0) { // Could not init channel WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s could not init channel", __FUNCTION__, channelId); ReturnChannelId(channelId); delete vieChannel; vieChannel = NULL; return -1; } if (_vieEncoderMap.Insert(channelId, vieEncoder) != 0) { // Could not add to the map WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s: Could not add new encoder for video channel %d", __FUNCTION__, channelId); ReturnChannelId(channelId); delete vieChannel; return -1; } // Set the same encoder settings for the channel as used by the master channel. // Do this before attaching rtp module to ensure all rtp cihldren has the same codec type VideoCodec encoder; if (vieEncoder->GetEncoder(encoder) == 0) { vieChannel->SetSendCodec(encoder); } _channelMap.Insert(channelId, vieChannel); // Register the channel at the encoder RtpRtcp* ptrSendRtpRtcpModule = vieEncoder->SendRtpRtcpModule(); if (vieChannel->RegisterSendRtpRtcpModule(*ptrSendRtpRtcpModule) != 0) { assert(false); _vieEncoderMap.Erase(channelId); _channelMap.Erase(channelId); ReturnChannelId(channelId); delete vieChannel; WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, channelId), "%s: Could not register rtp module %d", __FUNCTION__, channelId); return -1; } return 0; } // ---------------------------------------------------------------------------- // DeleteChannel // ---------------------------------------------------------------------------- int ViEChannelManager::DeleteChannel(int channelId) { ViEChannel* vieChannel = NULL; ViEEncoder* vieEncoder = NULL; { // Write lock to make sure no one is using the channel ViEManagerWriteScoped wl(*this); // Protect the map CriticalSectionScoped cs(*_ptrChannelIdCritsect); MapItem* mapItem = _channelMap.Find(channelId); if (mapItem == NULL) { // No such channel WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s Channel doesn't exist: %d", __FUNCTION__, channelId); return -1; } vieChannel = reinterpret_cast<ViEChannel*> (mapItem->GetItem()); _channelMap.Erase(mapItem); // Deregister the channel from the ViEEncoder to stop the media flow vieChannel->DeregisterSendRtpRtcpModule(); ReturnChannelId(channelId); // Find the encoder object mapItem = _vieEncoderMap.Find(channelId); if (mapItem == NULL) { assert(false); WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId), "%s ViEEncoder not found for channel %d", __FUNCTION__, channelId); return -1; } // Get the ViEEncoder item vieEncoder = reinterpret_cast<ViEEncoder*> (mapItem->GetItem()); // Check if other channels are using the same encoder if (ChannelUsingViEEncoder(channelId)) { // Don't delete the ViEEncoder, at least on other channel is using it. WEBRTC_TRACE( webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId), "%s ViEEncoder removed from map for channel %d, not deleted", __FUNCTION__, channelId); vieEncoder = NULL; } else { WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId), "%s ViEEncoder deleted for channel %d", __FUNCTION__, channelId); // Delete later when we've released the critsect } // We can't erase the item before we've checked for other channels using same ViEEncoder _vieEncoderMap.Erase(mapItem); } // Leave the write critsect before deleting the objects. // Deleting a channel can cause other objects, such as renderers, to be deleted and might take time if (vieEncoder) { delete vieEncoder; } delete vieChannel; WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(_engineId), "%s Channel %d deleted", __FUNCTION__, channelId); return 0; } // ---------------------------------------------------------------------------- // Channel // // Returns a pointer to the channel with id 'channelId' // ---------------------------------------------------------------------------- ViEChannel* ViEChannelManager::ViEChannelPtr(int channelId) const { CriticalSectionScoped cs(*_ptrChannelIdCritsect); MapItem* mapItem = _channelMap.Find(channelId); if (mapItem == NULL) { // No such channel WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s Channel doesn't exist: %d", __FUNCTION__, channelId); return NULL; } ViEChannel* vieChannel = reinterpret_cast<ViEChannel*> (mapItem->GetItem()); return vieChannel; } // ---------------------------------------------------------------------------- // GetChannels // // Adds all channels to channelMap // ---------------------------------------------------------------------------- void ViEChannelManager::GetViEChannels(MapWrapper& channelMap) { CriticalSectionScoped cs(*_ptrChannelIdCritsect); if (channelMap.Size() == 0) { // No channels return; } // Add all items to 'channelMap' for (MapItem* item = _channelMap.First(); item != NULL; item = _channelMap.Next(item)) { channelMap.Insert(item->GetId(), item->GetItem()); } return; } // ---------------------------------------------------------------------------- // ViEEncoderPtr // // Gets the ViEEncoder used as input for videoChannelId // ---------------------------------------------------------------------------- ViEEncoder* ViEChannelManager::ViEEncoderPtr(int videoChannelId) const { CriticalSectionScoped cs(*_ptrChannelIdCritsect); MapItem* mapItem = _vieEncoderMap.Find(videoChannelId); if (mapItem == NULL) { // No ViEEncoder for this channel... return NULL; } ViEEncoder* vieEncoder = static_cast<ViEEncoder*> (mapItem->GetItem()); return vieEncoder; } // ---------------------------------------------------------------------------- // GetFreeChannelId // // Returns true if we found a new channel id, freeChannelId, false otherwise // ---------------------------------------------------------------------------- bool ViEChannelManager::GetFreeChannelId(int& freeChannelId) { CriticalSectionScoped cs(*_ptrChannelIdCritsect); int idx = 0; while (idx < _freeChannelIdsSize) { if (_freeChannelIds[idx] == true) { // We've found a free id, allocate it and return _freeChannelIds[idx] = false; freeChannelId = idx + kViEChannelIdBase; return true; } idx++; } // No free channel id freeChannelId = -1; return false; } // ---------------------------------------------------------------------------- // ReturnChannelID // // Returns a previously allocated channel id // ---------------------------------------------------------------------------- void ViEChannelManager::ReturnChannelId(int channelId) { CriticalSectionScoped cs(*_ptrChannelIdCritsect); assert(channelId < kViEMaxNumberOfChannels+kViEChannelIdBase && channelId>=kViEChannelIdBase); _freeChannelIds[channelId - kViEChannelIdBase] = true; } // ---------------------------------------------------------------------------- // ChannelUsingViEEncoder // // Returns true if at least one nother channel is using the same encoder // ---------------------------------------------------------------------------- bool ViEChannelManager::ChannelUsingViEEncoder(int channelId) const { CriticalSectionScoped cs(*_ptrChannelIdCritsect); MapItem* channelItem = _vieEncoderMap.Find(channelId); if (channelItem == NULL) { // No ViEEncoder for this channel... return false; } ViEEncoder* channelEncoder = static_cast<ViEEncoder*> (channelItem->GetItem()); // Loop through all other channels to see if anyone points at the same ViEEncoder MapItem* mapItem = _vieEncoderMap.First(); while (mapItem) { ViEEncoder* vieEncoder = static_cast<ViEEncoder*> (mapItem->GetItem()); if (mapItem->GetId() != channelId) { if (channelEncoder == static_cast<ViEEncoder*> (mapItem->GetItem())) { // We've found another channel using the same ViEEncoder return true; } } mapItem = _vieEncoderMap.Next(mapItem); } return false; } // ---------------------------------------------------------------------------- // SetVoiceEngine // // Set the voice engine instance to be used by all video channels. We are interested in the voice engine sync interfaces // ---------------------------------------------------------------------------- int ViEChannelManager::SetVoiceEngine(VoiceEngine* voiceEngine) { // Write lock to make sure no one is using the channel ViEManagerWriteScoped wl(*this); CriticalSectionScoped cs(*_ptrChannelIdCritsect); VoEVideoSync* syncInterface = NULL; if (voiceEngine) { // Get new sync interface; syncInterface = VoEVideoSync::GetInterface(voiceEngine); if (!syncInterface) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId), "%s Can't get audio sync interface from VoiceEngine.", __FUNCTION__); if (syncInterface) { syncInterface->Release(); } return -1; } } for (MapItem* item = _channelMap.First(); item != NULL; item = _channelMap.Next(item)) { ViEChannel* channel = static_cast<ViEChannel*> (item->GetItem()); assert(channel); channel->SetVoiceChannel(-1, syncInterface); } if (_voiceSyncInterface) { _voiceSyncInterface->Release(); } _voiceEngine = voiceEngine; _voiceSyncInterface = syncInterface; return 0; } VoiceEngine* ViEChannelManager::GetVoiceEngine() { CriticalSectionScoped cs(*_ptrChannelIdCritsect); return _voiceEngine; } // ---------------------------------------------------------------------------- // ConnectVoiceChannel // // Enables lip sync of the channel. // ---------------------------------------------------------------------------- int ViEChannelManager::ConnectVoiceChannel(int channelId, int audioChannelId) { CriticalSectionScoped cs(*_ptrChannelIdCritsect); if (_voiceSyncInterface == NULL) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(_engineId, channelId), "No VoE set"); return -1; } ViEChannel* channel = ViEChannelPtr(channelId); if (!channel) { return -1; } return channel->SetVoiceChannel(audioChannelId, _voiceSyncInterface); } // ---------------------------------------------------------------------------- // DisconnectVoiceChannel // // Disables lip sync of the channel. // ---------------------------------------------------------------------------- int ViEChannelManager::DisconnectVoiceChannel(int channelId) { CriticalSectionScoped cs(*_ptrChannelIdCritsect); ViEChannel* channel = ViEChannelPtr(channelId); if (channel) { channel->SetVoiceChannel(-1, NULL); return 0; } else { return -1; } } } // namespace webrtc
ikonin/WebRTC
video_engine/main/source/vie_channel_manager.cc
C++
bsd-3-clause
20,449
# All of the other examples directly embed the Javascript and CSS code for # Bokeh's client-side runtime into the HTML. This leads to the HTML files # being rather large. An alternative is to ask Bokeh to produce HTML that # has a relative link to the Bokeh Javascript and CSS. This is easy to # do; you just pass in a few extra arguments to the output_file() command. import numpy as np from bokeh.plotting import * N = 100 x = np.linspace(0, 4*np.pi, N) y = np.sin(x) output_file("relative_paths.html", title="Relative path example", mode="relative") scatter(x,y, color="#FF00FF", tools="pan,wheel_zoom,box_zoom,reset,previewsave") show() # By default, the URLs for the Javascript and CSS will be relative to # the current directory, i.e. the directory in which the HTML file is # generated. You can provide a different "root" directory from which # the relative paths will be computed: # # output_file("scatter.html", title="scatter.py example", # resources="relative", rootdir="some/other/path")
the13fools/Bokeh_Examples
plotting/file/relative_paths.py
Python
bsd-3-clause
1,023
/* * Copyright (c) 2010 by Bjoern Kolbeck, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.common; /** * * @author bjko */ public class ReplicaUpdatePolicies { public static final String REPL_UPDATE_PC_NONE = ""; public static final String REPL_UPDATE_PC_RONLY = "ronly"; public static final String REPL_UPDATE_PC_WARONE = "WaR1"; public static final String REPL_UPDATE_PC_WARA = "WaRa"; // @deprecated as of XtreemFS 1.3.1 and no longer allowed to set. Use WaR1 instead. public static final String REPL_UPDATE_PC_WQRQ = "WqRq"; /** * Returns true if the replicaUpdatePolicy is read-write replicated. */ public static boolean isRwReplicated(String replicaUpdatePolicy) { return (replicaUpdatePolicy.equals(REPL_UPDATE_PC_WARA) || replicaUpdatePolicy.equals(REPL_UPDATE_PC_WARONE) || replicaUpdatePolicy .equals(REPL_UPDATE_PC_WQRQ)); } }
jswrenn/xtreemfs
java/servers/src/org/xtreemfs/common/ReplicaUpdatePolicies.java
Java
bsd-3-clause
1,007