text
stringlengths 2
1.04M
| meta
dict |
|---|---|
require File.dirname(__FILE__) + '/../../../spec_helper'
require 'net/ftp'
require File.dirname(__FILE__) + "/fixtures/server"
require File.dirname(__FILE__) + '/shared/list'
describe "Net::FTP#dir" do
it_behaves_like :net_ftp_list, :dir
end
|
{
"content_hash": "f399a4dfd5b19173d2c4e5958ebdcf82",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 56,
"avg_line_length": 30.625,
"alnum_prop": 0.6571428571428571,
"repo_name": "torquebox/rubyspec",
"id": "e67ebc42bcc45d1850528e19c69d9b0ede8fcf05",
"size": "245",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "library/net/ftp/dir_spec.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
..
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.
Convention for heading levels in Neutron devref:
======= Heading 0 (reserved for the title in a document)
------- Heading 1
~~~~~~~ Heading 2
+++++++ Heading 3
''''''' Heading 4
(Avoid deeper levels because they do not render well.)
L3 agent extensions
===================
L3 agent extensions are part of a generalized L2/L3 extension framework. See
:doc:`agent extensions <agent_extensions>`.
L3 agent extension API
----------------------
The L3 agent extension API object includes several methods that expose
router information to L3 agent extensions::
#. get_routers_in_project
#. get_router_hosting_port
#. is_router_in_namespace
|
{
"content_hash": "6e437789b118256d2cd4257bb23c7f64",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 79,
"avg_line_length": 33.421052631578945,
"alnum_prop": 0.6740157480314961,
"repo_name": "igor-toga/local-snat",
"id": "9c8cdc6aa6e1a1c785cac1a81e29c50095a2e1b6",
"size": "1270",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "doc/source/devref/l3_agent_extensions.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "1047"
},
{
"name": "Python",
"bytes": "9636936"
},
{
"name": "Shell",
"bytes": "14072"
}
],
"symlink_target": ""
}
|
* [Introduction](README.md)
* [Legal Notice](notice.md)
* [Getting Started](getting-started.adoc)
* [Longer Getting Started Guide](book-getting-started.adoc)
* [Architecture](architecture.adoc)
* [Async](async.adoc)
* [Asynchronous Routing Engine](asynchronous-routing-engine.adoc)
* [BacklogDebugger](backlogdebugger.adoc)
* [BAM](bam.adoc)
* [Batch Consumer](batch-consumer.adoc)
* [BrowsableEndpoint](browsable-endpoint.adoc)
* [Camel Core](camel-core.adoc)
* [CamelContext](camelcontext.adoc)
* [CEP](cep.adoc)
* [Debugger](debugger.adoc)
* [Delay Interceptor](delay-interceptor.adoc)
* [Dependency Injection](dependency-injection.adoc)
* [Dozer Type Conversion](dozer-type-conversion.adoc)
* [DSL](dsl.adoc)
* [Java DSL](java-dsl.adoc)
* [Spring DSL](spring.adoc)
* [Blueprint DSL](using-osgi-blueprint-with-camel.adoc)
* [Groovy DSL](groovy-dsl.adoc)
* [Scala DSL](scala-dsl.adoc)
* [Scala DSL Getting Started](scala-dsl-getting-started.adoc)
* [Scala DSL EIP](scala-dsl-eip.adoc)
* [Scala DSL Supported Languages](scala-dsl-supported-languages.adoc)
* [Annotation DSL](bean-integration.adoc)
* [Endpoint](endpoint.adoc)
* [Error Handler](error-handler.adoc)
* [Exchange](exchange.adoc)
* [Exchange Pattern](exchange-pattern.adoc)
* [Expression](expression.adoc)
* [Injector](injector.adoc)
* [Intercept](intercept.adoc)
* [Inversion Of Control With Smart Defaults](inversion-of-control-with-smart-defaults.adoc)
* [Lifecycle](lifecycle.adoc)
* [OnCompletion](oncompletion.adoc)
* [Registry](registry.adoc)
* [RX](rx.adoc)
* [Scala DSL](scala-dsl.adoc)
<!--
* [Pluggable Class Resolvers](.adoc)
* [Predicate](.adoc)
* [Processor](.adoc)
* [RouteBuilder](.adoc)
* [RoutePolicy](.adoc)
* [Routes](.adoc)
* [ServicePool](.adoc)
* [Stream caching](.adoc)
* [ToAsync](.adoc)
* [Tracer](.adoc)
* [Transport](.adoc)
* [Type Converter](.adoc)
* [URIs](.adoc)
* [Xml Configuration](.adoc)
* [ProcessorFactory](.adoc)
* [Asynchronous Routing Engine](.adoc)
* [Security](.adoc)
* [UuidGenerator](.adoc)
* [Binding](.adoc)
* [BacklogTracer](.adoc)
* [Endpoint Annotations](.adoc)
* [ComponentConfiguration](.adoc)
* [BacklogDebugger](.adoc)
* [EndpointCompleter](.adoc)
* [Clustering and loadbalancing](.adoc)
* [Threading Model](.adoc)
-->
* [Enterprise Integration Patterns](enterprise-integration-patterns.adoc)
* [Event Message](event-message.adoc)
* [Message](message.adoc)
* [Request Reply](request-reply.adoc)
* Community
* FAQ
* Using Camel questions
* [How do I configure endpoints](how-do-i-configure-endpoints.adoc)
<!-- core components: START -->
* Core Components
* [Bean](bean-component.adoc)
* [Binding](binding-component.adoc)
* [Browse](browse-component.adoc)
* [Class](class-component.adoc)
* [Control Bus](controlbus-component.adoc)
* [Data Format](dataformat-component.adoc)
* [Dataset](dataset-component.adoc)
* [Direct](direct-component.adoc)
* [Direct VM](direct-vm-component.adoc)
* [File](file-component.adoc)
* [Language](language-component.adoc)
* [Log](log-component.adoc)
* [Mock](mock-component.adoc)
* [Properties](properties-component.adoc)
* [Ref](ref-component.adoc)
* [REST](rest-component.adoc)
* [REST API](rest-api-component.adoc)
* [Scheduler](scheduler-component.adoc)
* [SEDA](seda-component.adoc)
* [Stub](stub-component.adoc)
* [Test](test-component.adoc)
* [Timer](timer-component.adoc)
* [Validator](validator-component.adoc)
* [VM](vm-component.adoc)
* [XSLT](xslt-component.adoc)
<!-- core components: END -->
<!-- components: START -->
* Components
* [AHC](ahc-component.adoc)
* [AHC Websocket](ahc-ws-component.adoc)
* [AMQP](amqp-component.adoc)
* [Apache Flink](flink-component.adoc)
* [Apache Spark](spark-component.adoc)
* [APNS](apns-component.adoc)
* [Asterisk](asterisk-component.adoc)
* [Atmos](atmos-component.adoc)
* [Atmosphere Websocket](atmosphere-websocket-component.adoc)
* [Atom](atom-component.adoc)
* [Atomix Map](atomix-map-component.adoc)
* [Atomix Messaging](atomix-messaging-component.adoc)
* [Atomix MultiMap](atomix-multimap-component.adoc)
* [Atomix Queue](atomix-queue-component.adoc)
* [Atomix Set](atomix-set-component.adoc)
* [Atomix Value](atomix-value-component.adoc)
* [Avro](avro-component.adoc)
* [AWS CloudWatch](aws-cw-component.adoc)
* [AWS DynamoDB](aws-ddb-component.adoc)
* [AWS DynamoDB Streams](aws-ddbstream-component.adoc)
* [AWS EC2](aws-ec2-component.adoc)
* [AWS Kinesis](aws-kinesis-component.adoc)
* [AWS Kinesis Firehose](aws-kinesis-firehose-component.adoc)
* [AWS S3 Storage Service](aws-s3-component.adoc)
* [AWS Simple Email Service](aws-ses-component.adoc)
* [AWS Simple Notification System](aws-sns-component.adoc)
* [AWS Simple Queue Service](aws-sqs-component.adoc)
* [AWS Simple Workflow](aws-swf-component.adoc)
* [AWS SimpleDB](aws-sdb-component.adoc)
* [Azure Storage Blob Service](azure-blob-component.adoc)
* [Azure Storage Queue Service](azure-queue-component.adoc)
* [Bean Validator](bean-validator-component.adoc)
* [Beanstalk](beanstalk-component.adoc)
* [BigQuery](bigquery-component.adoc)
* [Bonita](bonita-component.adoc)
* [Box](box-component.adoc)
* [Braintree](braintree-component.adoc)
* [Caffeine Cache](caffeine-cache-component.adoc)
* [Caffeine LoadCache](caffeine-loadcache-component.adoc)
* [Camel Context](context-component.adoc)
* [Cassandra CQL](cql-component.adoc)
* [Chronicle Engine](chronicle-engine-component.adoc)
* [Chunk](chunk-component.adoc)
* [CM SMS Gateway](cm-sms-component.adoc)
* [CMIS](cmis-component.adoc)
* [CoAP](coap-component.adoc)
* [CometD](cometd-component.adoc)
* [Consul](consul-component.adoc)
* [Couchbase](couchbase-component.adoc)
* [CouchDB](couchdb-component.adoc)
* [Crypto (JCE)](crypto-component.adoc)
* [Crypto CMS](crypto-cms-component.adoc)
* [CXF](cxf-component.adoc)
* [CXF-RS](cxfrs-component.adoc)
* [DigitalOcean](digitalocean-component.adoc)
* [Disruptor](disruptor-component.adoc)
* [DNS](dns-component.adoc)
* [Docker](docker-component.adoc)
* [Dozer](dozer-component.adoc)
* [Drill](drill-component.adoc)
* [Dropbox](dropbox-component.adoc)
* [EHCache](cache-component.adoc)
* [Ehcache](ehcache-component.adoc)
* [EJB](ejb-component.adoc)
* [Elasticsearch](elasticsearch-component.adoc)
* [Elasticsearch5](elasticsearch5-component.adoc)
* [ElSQL](elsql-component.adoc)
* [etcd](etcd-component.adoc)
* [Exec](exec-component.adoc)
* [Facebook](facebook-component.adoc)
* [Flatpack](flatpack-component.adoc)
* [FOP](fop-component.adoc)
* [Freemarker](freemarker-component.adoc)
* [FTP](ftp-component.adoc)
* [FTPS](ftps-component.adoc)
* [Ganglia](ganglia-component.adoc)
* [Geocoder](geocoder-component.adoc)
* [Git](git-component.adoc)
* [GitHub](github-component.adoc)
* [Google Calendar](google-calendar-component.adoc)
* [Google Drive](google-drive-component.adoc)
* [Google Mail](google-mail-component.adoc)
* [Google Pubsub](google-pubsub-component.adoc)
* [Gora](gora-component.adoc)
* [Grape](grape-component.adoc)
* [gRPC](grpc-component.adoc)
* [Guava EventBus](guava-eventbus-component.adoc)
* [Hazelcast Atomic Number](hazelcast-atomicvalue-component.adoc)
* [Hazelcast Instance](hazelcast-instance-component.adoc)
* [Hazelcast List](hazelcast-list-component.adoc)
* [Hazelcast Map](hazelcast-map-component.adoc)
* [Hazelcast Multimap](hazelcast-multimap-component.adoc)
* [Hazelcast Queue](hazelcast-queue-component.adoc)
* [Hazelcast Replicated Map](hazelcast-replicatedmap-component.adoc)
* [Hazelcast Ringbuffer](hazelcast-ringbuffer-component.adoc)
* [Hazelcast SEDA](hazelcast-seda-component.adoc)
* [Hazelcast Set](hazelcast-set-component.adoc)
* [Hazelcast Topic](hazelcast-topic-component.adoc)
* [HBase](hbase-component.adoc)
* [HDFS](hdfs-component.adoc)
* [HDFS2](hdfs2-component.adoc)
* [Hipchat](hipchat-component.adoc)
* [HTTP](http-component.adoc)
* [HTTP4](http4-component.adoc)
* [iBatis](ibatis-component.adoc)
* [IEC 60870 Client](iec60870-client-component.adoc)
* [IEC 60870-5-104 server](iec60870-server-component.adoc)
* [Ignite Cache](ignite-cache-component.adoc)
* [Ignite Compute](ignite-compute-component.adoc)
* [Ignite Events](ignite-events-component.adoc)
* [Ignite ID Generator](ignite-idgen-component.adoc)
* [Ignite Messaging](ignite-messaging-component.adoc)
* [Ignite Queues](ignite-queue-component.adoc)
* [Ignite Sets](ignite-set-component.adoc)
* [IMAP](imap-component.adoc)
* [Infinispan](infinispan-component.adoc)
* [InfluxDB](influxdb-component.adoc)
* [IRC](irc-component.adoc)
* [IronMQ](ironmq-component.adoc)
* [JavaSpace](javaspace-component.adoc)
* [JBPM](jbpm-component.adoc)
* [JCache](jcache-component.adoc)
* [JClouds](jclouds-component.adoc)
* [JCR](jcr-component.adoc)
* [JDBC](jdbc-component.adoc)
* [Jetty 9](jetty-component.adoc)
* [Jetty Websocket](websocket-component.adoc)
* [JGroups](jgroups-component.adoc)
* [Jing](jing-component.adoc)
* [JIRA](jira-component.adoc)
* [JMS](jms-component.adoc)
* [JMX](jmx-component.adoc)
* [JOLT](jolt-component.adoc)
* [JPA](jpa-component.adoc)
* [JT400](jt400-component.adoc)
* [Kafka](kafka-component.adoc)
* [Kestrel](kestrel-component.adoc)
* [Krati](krati-component.adoc)
* [Kubernetes](kubernetes-component.adoc)
* [Kubernetes Build Config](kubernetes-build-configs-component.adoc)
* [Kubernetes Builds](kubernetes-builds-component.adoc)
* [Kubernetes ConfigMap](kubernetes-config-maps-component.adoc)
* [Kubernetes Deployments](kubernetes-deployments-component.adoc)
* [Kubernetes Namespaces](kubernetes-namespaces-component.adoc)
* [Kubernetes Nodes](kubernetes-nodes-component.adoc)
* [Kubernetes Persistent Volume](kubernetes-persistent-volumes-component.adoc)
* [Kubernetes Persistent Volume Claim](kubernetes-persistent-volumes-claims-component.adoc)
* [Kubernetes Pods](kubernetes-pods-component.adoc)
* [Kubernetes Replication Controller](kubernetes-replication-controllers-component.adoc)
* [Kubernetes Resources Quota](kubernetes-resources-quota-component.adoc)
* [Kubernetes Secrets](kubernetes-secrets-component.adoc)
* [Kubernetes Services](kubernetes-services-component.adoc)
* [Kubernetes Servkce Account](kubernetes-service-account-component.adoc)
* [LDAP](ldap-component.adoc)
* [Linkedin](linkedin-component.adoc)
* [Lucene](lucene-component.adoc)
* [Lumberjack](lumberjack-component.adoc)
* [Metrics](metrics-component.adoc)
* [Mina](mina-component.adoc)
* [Mina2](mina2-component.adoc)
* [MLLP](mllp-component.adoc)
* [MongoDB](mongodb-component.adoc)
* [MongoDB](mongodb3-component.adoc)
* [MongoDB GridFS](mongodb-gridfs-component.adoc)
* [MQTT](mqtt-component.adoc)
* [MSV](msv-component.adoc)
* [Mustache](mustache-component.adoc)
* [MVEL](mvel-component.adoc)
* [MyBatis](mybatis-component.adoc)
* [Nagios](nagios-component.adoc)
* [Nats](nats-component.adoc)
* [Netty](netty-component.adoc)
* [Netty HTTP](netty-http-component.adoc)
* [Netty4](netty4-component.adoc)
* [Netty4 HTTP](netty4-http-component.adoc)
* [Olingo2](olingo2-component.adoc)
* [Olingo4](olingo4-component.adoc)
* [OPC UA Client](milo-client-component.adoc)
* [OPC UA Server](milo-server-component.adoc)
* [OpenShift](openshift-component.adoc)
* [OpenStack Cinder](openstack-cinder-component.adoc)
* [OpenStack Glance](openstack-glance-component.adoc)
* [OpenStack Keystone](openstack-keystone-component.adoc)
* [OpenStack Neutron](openstack-neutron-component.adoc)
* [OpenStack Nova](openstack-nova-component.adoc)
* [OpenStack Swift](openstack-swift-component.adoc)
* [OptaPlanner](optaplanner-component.adoc)
* [OSGi EventAdmin](eventadmin-component.adoc)
* [OSGi PAX Logging](paxlogging-component.adoc)
* [Paho](paho-component.adoc)
* [PDF](pdf-component.adoc)
* [PostgresSQL Event](pgevent-component.adoc)
* [Printer](lpr-component.adoc)
* [PubNub](pubnub-component.adoc)
* [Quartz](quartz-component.adoc)
* [Quartz2](quartz2-component.adoc)
* [QuickFix](quickfix-component.adoc)
* [RabbitMQ](rabbitmq-component.adoc)
* [Reactive Streams](reactive-streams-component.adoc)
* [REST Swagger](rest-swagger-component.adoc)
* [Restlet](restlet-component.adoc)
* [RMI](rmi-component.adoc)
* [RouteBox](routebox-component.adoc)
* [RSS](rss-component.adoc)
* [Salesforce](salesforce-component.adoc)
* [SAP NetWeaver](sap-netweaver-component.adoc)
* [Schematron](schematron-component.adoc)
* [SCP](scp-component.adoc)
* [ServiceNow](servicenow-component.adoc)
* [Servlet](servlet-component.adoc)
* [SFTP](sftp-component.adoc)
* [Simple JMS](sjms-component.adoc)
* [Simple JMS Batch](sjms-batch-component.adoc)
* [Simple JMS2](sjms2-component.adoc)
* [SIP](sip-component.adoc)
* [Slack](slack-component.adoc)
* [SMPP](smpp-component.adoc)
* [SNMP](snmp-component.adoc)
* [Solr](solr-component.adoc)
* [Spark Rest](spark-rest-component.adoc)
* [Splunk](splunk-component.adoc)
* [Spring Batch](spring-batch-component.adoc)
* [Spring Event](spring-event-component.adoc)
* [Spring Integration](spring-integration-component.adoc)
* [Spring LDAP](spring-ldap-component.adoc)
* [Spring Redis](spring-redis-component.adoc)
* [Spring WebService](spring-ws-component.adoc)
* [SQL](sql-component.adoc)
* [SQL Stored Procedure](sql-stored-component.adoc)
* [SSH](ssh-component.adoc)
* [StAX](stax-component.adoc)
* [Stomp](stomp-component.adoc)
* [Stream](stream-component.adoc)
* [String Template](string-template-component.adoc)
* [Telegram](telegram-component.adoc)
* [Thrift](thrift-component.adoc)
* [Tika](tika-component.adoc)
* [Twilio](twilio-component.adoc)
* [Twitter](twitter-component.adoc)
* [Twitter Direct Message](twitter-directmessage-component.adoc)
* [Twitter Search](twitter-search-component.adoc)
* [Twitter Streaming](twitter-streaming-component.adoc)
* [Twitter Timeline](twitter-timeline-component.adoc)
* [Undertow](undertow-component.adoc)
* [Velocity](velocity-component.adoc)
* [Vert.x](vertx-component.adoc)
* [Weather](weather-component.adoc)
* [XML RPC](xmlrpc-component.adoc)
* [XML Security](xmlsecurity-component.adoc)
* [XMPP](xmpp-component.adoc)
* [XQuery](xquery-component.adoc)
* [Yammer](yammer-component.adoc)
* [Zendesk](zendesk-component.adoc)
* [ZooKeeper](zookeeper-component.adoc)
* [ZooKeeper Master](zookeeper-master-component.adoc)
<!-- components: END -->
<!-- others: START -->
* Miscellaneous Components
* [BAM](bam.adoc)
* [Blueprint](blueprint.adoc)
* [CDI](cdi.adoc)
* [CXF Transport](cxf-transport.adoc)
* [Eclipse](eclipse.adoc)
* [Groovy DSL](groovy-dsl.adoc)
* [Guice](guice.adoc)
* [HawtDB](hawtdb.adoc)
* [Headersmap](headersmap.adoc)
* [Hystrix](hystrix.adoc)
* [Jasypt](jasypt.adoc)
* [Kura](kura.adoc)
* [LevelDB](leveldb.adoc)
* [OpenTracing](opentracing.adoc)
* [Reactor](reactor.adoc)
* [Ribbon](ribbon.adoc)
* [Ruby](ruby.adoc)
* [RX](rx.adoc)
* [Scala DSL](scala.adoc)
* [SCR](scr.adoc)
* [Servlet Listener](servletlistener.adoc)
* [Shiro](shiro.adoc)
* [Spring Boot](spring-boot.adoc)
* [Spring Cloud](spring-cloud.adoc)
* [Spring Cloud Netflix](spring-cloud-netflix.adoc)
* [Spring Java Configuration](spring-javaconfig.adoc)
* [Spring Security](spring-security.adoc)
* [Swagger](swagger.adoc)
* [Swagger Java](swagger-java.adoc)
* [Test](test.adoc)
* [Test Blueprint](test-blueprint.adoc)
* [Test CDI](test-cdi.adoc)
* [Test Karaf](test-karaf.adoc)
* [Test Spring](test-spring.adoc)
* [TestNG](testng.adoc)
* [URLRewrite](urlrewrite.adoc)
* [Zipkin](zipkin.adoc)
<!-- others: END -->
<!-- dataformats: START -->
* Data Formats
* [ASN.1 File](asn1-dataformat.adoc)
* [Avro](avro-dataformat.adoc)
* [Barcode](barcode-dataformat.adoc)
* [Base64](base64-dataformat.adoc)
* [BeanIO](beanio-dataformat.adoc)
* [Bindy CSV](bindy-dataformat.adoc)
* [Bindy Fixed Length](bindy-dataformat.adoc)
* [Bindy Key Value Pair](bindy-dataformat.adoc)
* [Boon](boon-dataformat.adoc)
* [Castor](castor-dataformat.adoc)
* [Crypto (Java Cryptographic Extension)](crypto-dataformat.adoc)
* [CSV](csv-dataformat.adoc)
* [Flatpack](flatpack-dataformat.adoc)
* [GZip](gzip-dataformat.adoc)
* [Hessian](hessian-dataformat.adoc)
* [HL7](hl7-dataformat.adoc)
* [iCal](ical-dataformat.adoc)
* [JacksonXML](jacksonxml-dataformat.adoc)
* [Java Object Serialization](serialization-dataformat.adoc)
* [JAXB](jaxb-dataformat.adoc)
* [JiBX](jibx-dataformat.adoc)
* [JSon Fastjson](json-fastjson-dataformat.adoc)
* [JSon GSon](json-gson-dataformat.adoc)
* [JSon Jackson](json-jackson-dataformat.adoc)
* [JSon Johnzon](json-johnzon-dataformat.adoc)
* [JSon XStream](json-xstream-dataformat.adoc)
* [LZF Deflate Compression](lzf-dataformat.adoc)
* [MIME Multipart](mime-multipart-dataformat.adoc)
* [PGP](pgp-dataformat.adoc)
* [Protobuf](protobuf-dataformat.adoc)
* [RSS](rss-dataformat.adoc)
* [SOAP](soapjaxb-dataformat.adoc)
* [String Encoding](string-dataformat.adoc)
* [Syslog](syslog-dataformat.adoc)
* [Tar File](tarfile-dataformat.adoc)
* [Thrift](thrift-dataformat.adoc)
* [TidyMarkup](tidyMarkup-dataformat.adoc)
* [uniVocity CSV](univocity-csv-dataformat.adoc)
* [uniVocity Fixed Length](univocity-fixed-dataformat.adoc)
* [uniVocity TSV](univocity-tsv-dataformat.adoc)
* [XML Beans](xmlBeans-dataformat.adoc)
* [XML JSon](xmljson-dataformat.adoc)
* [XML RPC](xmlrpc-dataformat.adoc)
* [XML Security](secureXML-dataformat.adoc)
* [XStream](xstream-dataformat.adoc)
* [YAML SnakeYAML](yaml-snakeyaml-dataformat.adoc)
* [Zip Deflate Compression](zip-dataformat.adoc)
* [Zip File](zipfile-dataformat.adoc)
<!-- dataformats: END -->
<!-- languages: START -->
* Expression Languages
* [Bean method](bean-language.adoc)
* [Constant](constant-language.adoc)
* [EL](el-language.adoc)
* [ExchangeProperty](exchangeProperty-language.adoc)
* [File](file-language.adoc)
* [Groovy](groovy-language.adoc)
* [Header](header-language.adoc)
* [HL7 Terser](terser-language.adoc)
* [JavaScript](javaScript-language.adoc)
* [JSonPath](jsonpath-language.adoc)
* [JXPath](jxpath-language.adoc)
* [MVEL](mvel-language.adoc)
* [OGNL](ognl-language.adoc)
* [PHP](php-language.adoc)
* [Python](python-language.adoc)
* [Ref](ref-language.adoc)
* [Ruby](ruby-language.adoc)
* [Simple](simple-language.adoc)
* [SpEL](spel-language.adoc)
* [SQL](sql-language.adoc)
* [Tokenize](tokenize-language.adoc)
* [XML Tokenize](xtokenize-language.adoc)
* [XPath](xpath-language.adoc)
* [XQuery](xquery-language.adoc)
<!-- languages: END -->
* Example
* [BAM Example](bam-example.adoc)
* User Guide
* [Karaf](karaf.adoc)
* [Testing](testing.adoc)
* [Test](test.adoc)
* [Blueprint Testing](test-blueprint.adoc)
* [CDI Testing](test-cdi.adoc)
* [Spring Testing](test-spring.adoc)
* [JSSE Utility](camel-configuration-utilities.adoc)
|
{
"content_hash": "1778c45e7f93ef9832895bedb5758fe3",
"timestamp": "",
"source": "github",
"line_count": 528,
"max_line_length": 95,
"avg_line_length": 36.38068181818182,
"alnum_prop": 0.712270289968244,
"repo_name": "mgyongyosi/camel",
"id": "fd51b73259ca0ddf5d019eef346d8d7259aaa27e",
"size": "19220",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/user-manual/en/SUMMARY.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1518"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "54390"
},
{
"name": "HTML",
"bytes": "189079"
},
{
"name": "Java",
"bytes": "67201824"
},
{
"name": "JavaScript",
"bytes": "90230"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "PLSQL",
"bytes": "1419"
},
{
"name": "Protocol Buffer",
"bytes": "2514"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323702"
},
{
"name": "Shell",
"bytes": "17092"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "284638"
}
],
"symlink_target": ""
}
|
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/counter';
function mapStateToProps(state) {
return {
counter: state.counter
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(CounterActions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
|
{
"content_hash": "6a44ab512f3a3827e8bd42ea756d4e88",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 69,
"avg_line_length": 26.875,
"alnum_prop": 0.7604651162790698,
"repo_name": "tgirgin23/osm-electron-editor",
"id": "89d206323e0e611c04a7e6fcd129a7b10a442765",
"size": "430",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/containers/Map.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2901"
},
{
"name": "HTML",
"bytes": "1967"
},
{
"name": "JavaScript",
"bytes": "59204"
}
],
"symlink_target": ""
}
|
using System.Collections.Generic;
namespace Markdig
{
/// <summary>
/// Provides a context that can be used as part of parsing Markdown documents.
/// </summary>
public class MarkdownParserContext
{
/// <summary>
/// Gets or sets the context property collection.
/// </summary>
public Dictionary<object, object> Properties { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MarkdownParserContext" /> class.
/// </summary>
public MarkdownParserContext()
{
Properties = new Dictionary<object, object>();
}
}
}
|
{
"content_hash": "d6d498c8affedda635ad98ca9f8b9793",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 89,
"avg_line_length": 28.130434782608695,
"alnum_prop": 0.5904173106646059,
"repo_name": "lunet-io/markdig",
"id": "6cf0020f935629545060ff95350b94c68a4fb9f5",
"size": "831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Markdig/MarkdownParserContext.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C#",
"bytes": "2087944"
},
{
"name": "PowerShell",
"bytes": "4550"
}
],
"symlink_target": ""
}
|
import sys
import pybindgen
from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink
from pybindgen import CppMethod, CppConstructor, CppClass, Enum
def my_module_gen(out_file):
mod = Module('b')
mod.add_include('"b.h"')
B = mod.add_class('B')
B.add_constructor([])
B.add_copy_constructor()
B.add_instance_attribute('b_a', ReturnValue.new('uint32_t'))
B.add_instance_attribute('b_b', ReturnValue.new('uint32_t'))
mod.add_function('BDoA', None, [Parameter.new('B', 'b')])
mod.add_function('BDoB', ReturnValue.new('B'), [])
mod.generate(FileCodeSink(out_file) )
if __name__ == '__main__':
my_module_gen(sys.stdout)
|
{
"content_hash": "c6f6eab59c859033096a7d5d5262912b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 76,
"avg_line_length": 27.4,
"alnum_prop": 0.6613138686131387,
"repo_name": "softDi/clusim",
"id": "7c65ef0eff5e5355c8af9896061de17571a57565",
"size": "709",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "ns3/pybindgen-0.17.0.post57+nga6376f2/examples/b/modulegen.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3021"
},
{
"name": "C",
"bytes": "365226"
},
{
"name": "C++",
"bytes": "24340132"
},
{
"name": "CSS",
"bytes": "3775"
},
{
"name": "Click",
"bytes": "19348"
},
{
"name": "Gnuplot",
"bytes": "9919"
},
{
"name": "HTML",
"bytes": "7942"
},
{
"name": "JavaScript",
"bytes": "7698"
},
{
"name": "Makefile",
"bytes": "92131"
},
{
"name": "Matlab",
"bytes": "39069"
},
{
"name": "Perl",
"bytes": "302716"
},
{
"name": "Perl 6",
"bytes": "151"
},
{
"name": "Python",
"bytes": "44191047"
},
{
"name": "QMake",
"bytes": "6602"
},
{
"name": "Shell",
"bytes": "146434"
}
],
"symlink_target": ""
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Problem 5. Boolean Variable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem 5. Boolean Variable")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("462fcf25-0e8c-488f-b5b9-bf2351220269")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
{
"content_hash": "bc9941ab03418abc7b366c64db483a6f",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.638888888888886,
"alnum_prop": 0.7449194113524877,
"repo_name": "AlexanderDanev/csharp-tests",
"id": "cfefb3ed48c40facad547178188f873cf1e85673",
"size": "1430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2.Data Types and Variables/Problem 5. Boolean Variable/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "50650"
}
],
"symlink_target": ""
}
|
namespace octomap_msgs
{
static const char BOUNDINGBOXQUERY[] = "octomap_msgs/BoundingBoxQuery";
class BoundingBoxQueryRequest : public ros::Msg
{
public:
geometry_msgs::Point min;
geometry_msgs::Point max;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->min.serialize(outbuffer + offset);
offset += this->max.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->min.deserialize(inbuffer + offset);
offset += this->max.deserialize(inbuffer + offset);
return offset;
}
const char * getType(){ return BOUNDINGBOXQUERY; };
const char * getMD5(){ return "93aa3d73b866f04880927745f4aab303"; };
};
class BoundingBoxQueryResponse : public ros::Msg
{
public:
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
return offset;
}
const char * getType(){ return BOUNDINGBOXQUERY; };
const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; };
};
class BoundingBoxQuery {
public:
typedef BoundingBoxQueryRequest Request;
typedef BoundingBoxQueryResponse Response;
};
}
#endif
|
{
"content_hash": "4aa091d31b05428f90c8232f91b83139",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 72,
"avg_line_length": 22.78688524590164,
"alnum_prop": 0.6553956834532374,
"repo_name": "robotican/ric",
"id": "a9510f97652c72532eb76f1ec369a27061004670",
"size": "1585",
"binary": false,
"copies": "4",
"ref": "refs/heads/indigo-devel",
"path": "ric_mc/Arduino/libraries/ros_lib/octomap_msgs/BoundingBoxQuery.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arduino",
"bytes": "142621"
},
{
"name": "C",
"bytes": "39802"
},
{
"name": "C#",
"bytes": "316699"
},
{
"name": "C++",
"bytes": "3208133"
},
{
"name": "CMake",
"bytes": "10309"
},
{
"name": "Objective-C",
"bytes": "2102"
},
{
"name": "Processing",
"bytes": "20189"
},
{
"name": "Python",
"bytes": "12216967"
},
{
"name": "Shell",
"bytes": "7029"
}
],
"symlink_target": ""
}
|
package com.coreoz.plume.file.services.cache;
import java.util.function.Function;
import com.coreoz.plume.file.services.file.data.FileData;
import com.google.common.cache.LoadingCache;
public interface FileCacheService {
LoadingCache<Long, FileData> newFileDataCache(Function<Long, FileData> loadingData);
LoadingCache<Long, String> newFileUrlCache(Function<Long, String> loadingData);
}
|
{
"content_hash": "76de5fb8fc91245b16b386aba642a11b",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 85,
"avg_line_length": 28.285714285714285,
"alnum_prop": 0.8131313131313131,
"repo_name": "Coreoz/Plume-file",
"id": "8ad5b6ad6f50973d7b058725952b75becc5fd076",
"size": "396",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plume-file-core/src/main/java/com/coreoz/plume/file/services/cache/FileCacheService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "69946"
}
],
"symlink_target": ""
}
|
Raft is a protocol with which a cluster of nodes can maintain a replicated state machine.
The state machine is kept in sync through the use of a replicated log.
For more details on Raft, see "In Search of an Understandable Consensus Algorithm"
(https://ramcloud.stanford.edu/raft.pdf) by Diego Ongaro and John Ousterhout.
This Raft library is stable and feature complete. As of 2016, it is **the most widely used** Raft library in production, serving tens of thousands clusters each day. It powers distributed systems such as etcd, Kubernetes, Docker Swarm, Cloud Foundry Diego, CockroachDB, TiDB, Project Calico, Flannel, and more.
Most Raft implementations have a monolithic design, including storage handling, messaging serialization, and network transport. This library instead follows a minimalistic design philosophy by only implementing the core raft algorithm. This minimalism buys flexibility, determinism, and performance.
To keep the codebase small as well as provide flexibility, the library only implements the Raft algorithm; both network and disk IO are left to the user. Library users must implement their own transportation layer for message passing between Raft peers over the wire. Similarly, users must implement their own storage layer to persist the Raft log and state.
In order to easily test the Raft library, its behavior should be deterministic. To achieve this determinism, the library models Raft as a state machine. The state machine takes a `Message` as input. A message can either be a local timer update or a network message sent from a remote peer. The state machine's output is a 3-tuple `{[]Messages, []LogEntries, NextState}` consisting of an array of `Messages`, `log entries`, and `Raft state changes`. For state machines with the same state, the same state machine input should always generate the same state machine output.
A simple example application, _raftexample_, is also available to help illustrate how to use this package in practice: https://github.com/etcd-io/etcd/tree/master/contrib/raftexample
# Features
This raft implementation is a full feature implementation of Raft protocol. Features includes:
- Leader election
- Log replication
- Log compaction
- Membership changes
- Leadership transfer extension
- Efficient linearizable read-only queries served by both the leader and followers
- leader checks with quorum and bypasses Raft log before processing read-only queries
- followers asks leader to get a safe read index before processing read-only queries
- More efficient lease-based linearizable read-only queries served by both the leader and followers
- leader bypasses Raft log and processing read-only queries locally
- followers asks leader to get a safe read index before processing read-only queries
- this approach relies on the clock of the all the machines in raft group
This raft implementation also includes a few optional enhancements:
- Optimistic pipelining to reduce log replication latency
- Flow control for log replication
- Batching Raft messages to reduce synchronized network I/O calls
- Batching log entries to reduce disk synchronized I/O
- Writing to leader's disk in parallel
- Internal proposal redirection from followers to leader
- Automatic stepping down when the leader loses quorum
## Notable Users
- [cockroachdb](https://github.com/cockroachdb/cockroach) A Scalable, Survivable, Strongly-Consistent SQL Database
- [dgraph](https://github.com/dgraph-io/dgraph) A Scalable, Distributed, Low Latency, High Throughput Graph Database
- [etcd](https://github.com/etcd-io/etcd) A distributed reliable key-value store
- [tikv](https://github.com/pingcap/tikv) A Distributed transactional key value database powered by Rust and Raft
- [swarmkit](https://github.com/docker/swarmkit) A toolkit for orchestrating distributed systems at any scale.
- [chain core](https://github.com/chain/chain) Software for operating permissioned, multi-asset blockchain networks
## Usage
The primary object in raft is a Node. Either start a Node from scratch using raft.StartNode or start a Node from some initial state using raft.RestartNode.
To start a three-node cluster
```go
storage := raft.NewMemoryStorage()
c := &Config{
ID: 0x01,
ElectionTick: 10,
HeartbeatTick: 1,
Storage: storage,
MaxSizePerMsg: 4096,
MaxInflightMsgs: 256,
}
// Set peer list to the other nodes in the cluster.
// Note that they need to be started separately as well.
n := raft.StartNode(c, []raft.Peer{{ID: 0x02}, {ID: 0x03}})
```
Start a single node cluster, like so:
```go
// Create storage and config as shown above.
// Set peer list to itself, so this node can become the leader of this single-node cluster.
peers := []raft.Peer{{ID: 0x01}}
n := raft.StartNode(c, peers)
```
To allow a new node to join this cluster, do not pass in any peers. First, add the node to the existing cluster by calling `ProposeConfChange` on any existing node inside the cluster. Then, start the node with an empty peer list, like so:
```go
// Create storage and config as shown above.
n := raft.StartNode(c, nil)
```
To restart a node from previous state:
```go
storage := raft.NewMemoryStorage()
// Recover the in-memory storage from persistent snapshot, state and entries.
storage.ApplySnapshot(snapshot)
storage.SetHardState(state)
storage.Append(entries)
c := &Config{
ID: 0x01,
ElectionTick: 10,
HeartbeatTick: 1,
Storage: storage,
MaxSizePerMsg: 4096,
MaxInflightMsgs: 256,
}
// Restart raft without peer information.
// Peer information is already included in the storage.
n := raft.RestartNode(c)
```
After creating a Node, the user has a few responsibilities:
First, read from the Node.Ready() channel and process the updates it contains. These steps may be performed in parallel, except as noted in step 2.
1. Write Entries, HardState and Snapshot to persistent storage in order, i.e. Entries first, then HardState and Snapshot if they are not empty. If persistent storage supports atomic writes then all of them can be written together. Note that when writing an Entry with Index i, any previously-persisted entries with Index >= i must be discarded.
2. Send all Messages to the nodes named in the To field. It is important that no messages be sent until the latest HardState has been persisted to disk, and all Entries written by any previous Ready batch (Messages may be sent while entries from the same batch are being persisted). To reduce the I/O latency, an optimization can be applied to make leader write to disk in parallel with its followers (as explained at section 10.2.1 in Raft thesis). If any Message has type MsgSnap, call Node.ReportSnapshot() after it has been sent (these messages may be large). Note: Marshalling messages is not thread-safe; it is important to make sure that no new entries are persisted while marshalling. The easiest way to achieve this is to serialise the messages directly inside the main raft loop.
3. Apply Snapshot (if any) and CommittedEntries to the state machine. If any committed Entry has Type EntryConfChange, call Node.ApplyConfChange() to apply it to the node. The configuration change may be cancelled at this point by setting the NodeID field to zero before calling ApplyConfChange (but ApplyConfChange must be called one way or the other, and the decision to cancel must be based solely on the state machine and not external information such as the observed health of the node).
4. Call Node.Advance() to signal readiness for the next batch of updates. This may be done at any time after step 1, although all updates must be processed in the order they were returned by Ready.
Second, all persisted log entries must be made available via an implementation of the Storage interface. The provided MemoryStorage type can be used for this (if repopulating its state upon a restart), or a custom disk-backed implementation can be supplied.
Third, after receiving a message from another node, pass it to Node.Step:
```go
func recvRaftRPC(ctx context.Context, m raftpb.Message) {
n.Step(ctx, m)
}
```
Finally, call `Node.Tick()` at regular intervals (probably via a `time.Ticker`). Raft has two important timeouts: heartbeat and the election timeout. However, internally to the raft package time is represented by an abstract "tick".
The total state machine handling loop will look something like this:
```go
for {
select {
case <-s.Ticker:
n.Tick()
case rd := <-s.Node.Ready():
saveToStorage(rd.HardState, rd.Entries, rd.Snapshot)
send(rd.Messages)
if !raft.IsEmptySnap(rd.Snapshot) {
processSnapshot(rd.Snapshot)
}
for _, entry := range rd.CommittedEntries {
process(entry)
if entry.Type == raftpb.EntryConfChange {
var cc raftpb.ConfChange
cc.Unmarshal(entry.Data)
s.Node.ApplyConfChange(cc)
}
}
s.Node.Advance()
case <-s.done:
return
}
}
```
To propose changes to the state machine from the node to take application data, serialize it into a byte slice and call:
```go
n.Propose(ctx, data)
```
If the proposal is committed, data will appear in committed entries with type raftpb.EntryNormal. There is no guarantee that a proposed command will be committed; the command may have to be reproposed after a timeout.
To add or remove node in a cluster, build ConfChange struct 'cc' and call:
```go
n.ProposeConfChange(ctx, cc)
```
After config change is committed, some committed entry with type raftpb.EntryConfChange will be returned. This must be applied to node through:
```go
var cc raftpb.ConfChange
cc.Unmarshal(data)
n.ApplyConfChange(cc)
```
Note: An ID represents a unique node in a cluster for all time. A
given ID MUST be used only once even if the old node has been removed.
This means that for example IP addresses make poor node IDs since they
may be reused. Node IDs must be non-zero.
## Implementation notes
This implementation is up to date with the final Raft thesis (https://ramcloud.stanford.edu/~ongaro/thesis.pdf), although this implementation of the membership change protocol differs somewhat from that described in chapter 4. The key invariant that membership changes happen one node at a time is preserved, but in our implementation the membership change takes effect when its entry is applied, not when it is added to the log (so the entry is committed under the old membership instead of the new). This is equivalent in terms of safety, since the old and new configurations are guaranteed to overlap.
To ensure there is no attempt to commit two membership changes at once by matching log positions (which would be unsafe since they should have different quorum requirements), any proposed membership change is simply disallowed while any uncommitted change appears in the leader's log.
This approach introduces a problem when removing a member from a two-member cluster: If one of the members dies before the other one receives the commit of the confchange entry, then the member cannot be removed any more since the cluster cannot make progress. For this reason it is highly recommended to use three or more nodes in every cluster.
|
{
"content_hash": "e76104f31d56350434bc22bbfa208df8",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 789,
"avg_line_length": 58.25773195876289,
"alnum_prop": 0.7644664661121925,
"repo_name": "vimalk78/etcd",
"id": "0ddf3f48f8a3894e8a3cfb65d978bfa37a75e9ac",
"size": "11318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "raft/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "51"
},
{
"name": "Dockerfile",
"bytes": "6462"
},
{
"name": "Go",
"bytes": "4518135"
},
{
"name": "Makefile",
"bytes": "18955"
},
{
"name": "PowerShell",
"bytes": "2718"
},
{
"name": "Shell",
"bytes": "99850"
}
],
"symlink_target": ""
}
|
<Record>
<Term>Pericoronitis</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Gingival Diseases</ParentTerm>
<ClassificationPath>Stomatognathic Diseases/Mouth Diseases/Periodontal Diseases/Gingival Diseases/Pericoronitis</ClassificationPath>
<BroaderTerm>Stomatognathic Diseases</BroaderTerm>
<BroaderTerm>Mouth Diseases</BroaderTerm>
<BroaderTerm>Gingival Diseases</BroaderTerm>
<BroaderTerm>Pericoronitis</BroaderTerm>
<BroaderTerm>Periodontal Diseases</BroaderTerm>
<Synonym>Pericoronitis</Synonym>
<Synonym>Pericoronitides</Synonym>
<Description>Inflammation of the gingiva surrounding the crown of a tooth.</Description>
<Source>MeSH</Source>
</Record>
|
{
"content_hash": "b861137b6df2a075e3e5a6ee24c0c50d",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 132,
"avg_line_length": 46.13333333333333,
"alnum_prop": 0.819364161849711,
"repo_name": "detnavillus/modular-informatic-designs",
"id": "7d65956477218bb292fc27a4c25717b7e395773d",
"size": "692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pipeline/src/test/resources/thesaurus/diseaseorsyndrome/pericoronitis.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2069134"
}
],
"symlink_target": ""
}
|
Lang_AllFolders = "Todas as Pastas";
Lang_Page = "Page";
Lang_First = "Primeira";
Lang_Last = "Última";
Lang_NextMsg = "Próximas Mensagens";
Lang_PrevMsg = "Mensagens Anterires";
Lang_Viewing = "Visualizando";
Lang_Messages = "Mensagem";
Lang_To = "Para";
Lang_Of = "of";
Lang_From = "De";
Lang_Subject = "Assunto";
Lang_Date = "Data";
Lang_Size = "Tamanho";
Lang_DragDrop = "Arrastar e Soltar em uma Pasta";
Lang_DoubleClick = "Double Click to Open";
Lang_CacheStatus = "Message Cache Status";
Lang_Type = "Tipo";
Lang_Priority = "Prioridade";
Lang_Normal = "Normal";
Lang_High = "Alta";
Lang_Low = "Baixa";
Lang_Reply = "Resposta";
Lang_ReplyAll = "Responder Todos";
Lang_Forward = "Encaminhar";
Lang_Delete = "Apagar";
Lang_Abook = "Livro de Endereços";
Lang_Print = "Imprimir";
Lang_BlockSender = "Bloquear Remetente";
Lang_ViewHeaders = "View Headers";
Lang_Next = "Próxima";
Lang_Prev = "Mensagem Anterior";
Lang_Back = "Voltar";
Lang_Send = "Send Mail";
Lang_AddRecpt = "Adicionar Destinatários";
Lang_AddBCC = "Adicionar Cópia Oculta";
Lang_SpellCheck = "Verificar Ortografia";
Lang_Attachments = "Anexos";
Lang_SaveMsg = "Salvar Msg";
Lang_Resume = "Resume Editing";
Lang_BackTo = "Back to";
Lang_Text = "Texto";
Lang_Open = "Aberto";
Lang_Editor = "Editor";
Lang_Bcc = "Bcc";
Lang_Cc = "Cc";
Lang_ItemsToMove = "Items to move";
Lang_BlackListAdded = "The user has been added to your Spam blacklist";
Lang_AbookAdded = "The users email-address has been added to the addressbook";
Lang_MoveHead = "Message cannot be moved";
Lang_MoveHead2 = "The unique message identifier does not match the selected message for move/deletion. This error can occur if:";
Lang_MoveReason1 = "You have refreshed the WebMail window after moving a message. The previous message cannot be moved twice";
Lang_MoveReason2 = "The message has been moved from another application via POP3/IMAP. Please reload your mailbox folder for an updated listing";
Lang_MoveReason3 = "The message no longer exists on the mail-server";
Lang_Headers = "Cabeçalho";
Lang_AddSender = "Adicionar no Livro de Endereços";
Lang_Sent = "Enviadas";
Lang_AddWord = "Adicionar Palavra";
Lang_Edit = "Editar";
Lang_BlockedAlert = "Alert:";
Lang_Blocked = "$var['BlockImages'] images have been blocked.";
Lang_Display = "Display Images in message";
Lang_DisplayAdd = "Always display images from this user";
Lang_AlertPerm = "Tem certeza que deseja apagar permenentemente as mensagens selecionadas?";
Lang_MarkAsRead = "Mark as Read";
Lang_MarkAsUnread = "Mark as Unread";
// Calendar Language files
Lang_Months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
Lang_Days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
Lang_AllDayAdd = "Double Click to Add an All Day Appointment";
Lang_DayAdd = "Click & Drag or Double Click to Add an Appointment";
Lang_TaskAdd = "Adicionar";
Lang_TaskHeader = "Tarefas";
Lang_AllDayEvents = "All Day Events";
Lang_Done = "Finalizar";
Lang_Personal = "Pessoal";
Lang_Shared = "Shared";
Lang_VideoMail = "Video Mail";
Lang_Help = "Help Guide for Recording Video messages";
Lang_Start = "Data de Início";
Lang_End = "Data de Fim";
// Used for the overdue.html template in the calendar
Lang_Complete = "Completo";
Lang_Sleep = "Remind in 30 minutes";
Lang_DueDate = "Até Data";
Lang_OverDue = "Overdue Appointments";
Lang_ViewDay = "Vendo Hoje";
Lang_ViewWeek = "View 5 day Week";
Lang_ViewWeek7 = "View 7 day Week";
Lang_ViewMonth = "View Month";
Lang_BackToEmail = "Back to Email";
Lang_Sync = "Ajuda do Outlook-Sync";
Lang_HelpGuide = "Guia de Ajuda";
Lang_ExportToIcal = "Export to iCal";
Lang_HasNoMsgs = "$var['FolderName'] não há mensagens";
Lang_CalImportTitle = "Import from iCal";
Lang_CalImportLabel = "Import Calendar in iCal (ics) format:";
|
{
"content_hash": "4419c21dbaa886245c1c3f863b16ff44",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 146,
"avg_line_length": 37.990196078431374,
"alnum_prop": 0.7220645161290322,
"repo_name": "BigBlueHat/atmailopen",
"id": "78f5bc2c4de5d46d9c83a5b78fc832b7bd4fae31",
"size": "3927",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "html/portuguese/javascript/ajax-lang.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "417054"
},
{
"name": "PHP",
"bytes": "2039705"
},
{
"name": "Perl",
"bytes": "25877"
}
],
"symlink_target": ""
}
|
namespace parquet {
// ----------------------------------------------------------------------
// Metadata enums to match Thrift metadata
//
// The reason we maintain our own enums is to avoid transitive dependency on
// the compiled Thrift headers (and thus thrift/Thrift.h) for users of the
// public API. After building parquet-cpp, you should not need to include
// Thrift headers in your application. This means some boilerplate to convert
// between our types and Parquet's Thrift types.
//
// We can also add special values like NONE to distinguish between metadata
// values being set and not set. As an example consider ConvertedType and
// CompressionCodec
// Mirrors parquet::Type
struct Type {
enum type {
BOOLEAN = 0,
INT32 = 1,
INT64 = 2,
INT96 = 3,
FLOAT = 4,
DOUBLE = 5,
BYTE_ARRAY = 6,
FIXED_LEN_BYTE_ARRAY = 7
};
};
// Mirrors parquet::ConvertedType
struct LogicalType {
enum type {
NONE,
UTF8,
MAP,
MAP_KEY_VALUE,
LIST,
ENUM,
DECIMAL,
DATE,
TIME_MILLIS,
TIME_MICROS,
TIMESTAMP_MILLIS,
TIMESTAMP_MICROS,
UINT_8,
UINT_16,
UINT_32,
UINT_64,
INT_8,
INT_16,
INT_32,
INT_64,
JSON,
BSON,
INTERVAL,
NA = 25
};
};
// Mirrors parquet::FieldRepetitionType
struct Repetition {
enum type { REQUIRED = 0, OPTIONAL = 1, REPEATED = 2 };
};
// Data encodings. Mirrors parquet::Encoding
struct Encoding {
enum type {
PLAIN = 0,
PLAIN_DICTIONARY = 2,
RLE = 3,
BIT_PACKED = 4,
DELTA_BINARY_PACKED = 5,
DELTA_LENGTH_BYTE_ARRAY = 6,
DELTA_BYTE_ARRAY = 7,
RLE_DICTIONARY = 8
};
};
// Compression, mirrors parquet::CompressionCodec
struct Compression {
enum type { UNCOMPRESSED, SNAPPY, GZIP, LZO, BROTLI, LZ4, ZSTD };
};
struct Encryption {
enum type { AES_GCM_V1 = 0, AES_GCM_CTR_V1 = 1 };
};
// parquet::PageType
struct PageType {
enum type { DATA_PAGE, INDEX_PAGE, DICTIONARY_PAGE, DATA_PAGE_V2 };
};
// Reference:
// parquet-mr/parquet-hadoop/src/main/java/org/apache/parquet/
// format/converter/ParquetMetadataConverter.java
// Sort order for page and column statistics. Types are associated with sort
// orders (e.g., UTF8 columns should use UNSIGNED) and column stats are
// aggregated using a sort order. As of parquet-format version 2.3.1, the
// order used to aggregate stats is always SIGNED and is not stored in the
// Parquet file. These stats are discarded for types that need unsigned.
// See PARQUET-686.
struct SortOrder {
enum type { SIGNED, UNSIGNED, UNKNOWN };
};
class ColumnOrder {
public:
enum type { UNDEFINED, TYPE_DEFINED_ORDER };
explicit ColumnOrder(ColumnOrder::type column_order) : column_order_(column_order) {}
// Default to Type Defined Order
ColumnOrder() : column_order_(type::TYPE_DEFINED_ORDER) {}
ColumnOrder::type get_order() { return column_order_; }
static ColumnOrder undefined_;
static ColumnOrder type_defined_;
private:
ColumnOrder::type column_order_;
};
// ----------------------------------------------------------------------
struct ByteArray {
ByteArray() : len(0), ptr(nullptr) {}
ByteArray(uint32_t len, const uint8_t* ptr) : len(len), ptr(ptr) {}
uint32_t len;
const uint8_t* ptr;
};
inline bool operator==(const ByteArray& left, const ByteArray& right) {
return left.len == right.len && 0 == std::memcmp(left.ptr, right.ptr, left.len);
}
inline bool operator!=(const ByteArray& left, const ByteArray& right) {
return !(left == right);
}
struct FixedLenByteArray {
FixedLenByteArray() : ptr(nullptr) {}
explicit FixedLenByteArray(const uint8_t* ptr) : ptr(ptr) {}
const uint8_t* ptr;
};
using FLBA = FixedLenByteArray;
MANUALLY_ALIGNED_STRUCT(1) Int96 { uint32_t value[3]; };
STRUCT_END(Int96, 12);
inline bool operator==(const Int96& left, const Int96& right) {
return std::equal(left.value, left.value + 3, right.value);
}
inline bool operator!=(const Int96& left, const Int96& right) { return !(left == right); }
static inline std::string ByteArrayToString(const ByteArray& a) {
return std::string(reinterpret_cast<const char*>(a.ptr), a.len);
}
static inline std::string Int96ToString(const Int96& a) {
std::ostringstream result;
std::copy(a.value, a.value + 3, std::ostream_iterator<uint32_t>(result, " "));
return result.str();
}
static inline std::string FixedLenByteArrayToString(const FixedLenByteArray& a, int len) {
std::ostringstream result;
std::copy(a.ptr, a.ptr + len, std::ostream_iterator<uint32_t>(result, " "));
return result.str();
}
template <Type::type TYPE>
struct type_traits {};
template <>
struct type_traits<Type::BOOLEAN> {
using value_type = bool;
static constexpr int value_byte_size = 1;
static constexpr const char* printf_code = "d";
};
template <>
struct type_traits<Type::INT32> {
using value_type = int32_t;
static constexpr int value_byte_size = 4;
static constexpr const char* printf_code = "d";
};
template <>
struct type_traits<Type::INT64> {
using value_type = int64_t;
static constexpr int value_byte_size = 8;
static constexpr const char* printf_code = "ld";
};
template <>
struct type_traits<Type::INT96> {
using value_type = Int96;
static constexpr int value_byte_size = 12;
static constexpr const char* printf_code = "s";
};
template <>
struct type_traits<Type::FLOAT> {
using value_type = float;
static constexpr int value_byte_size = 4;
static constexpr const char* printf_code = "f";
};
template <>
struct type_traits<Type::DOUBLE> {
using value_type = double;
static constexpr int value_byte_size = 8;
static constexpr const char* printf_code = "lf";
};
template <>
struct type_traits<Type::BYTE_ARRAY> {
using value_type = ByteArray;
static constexpr int value_byte_size = sizeof(ByteArray);
static constexpr const char* printf_code = "s";
};
template <>
struct type_traits<Type::FIXED_LEN_BYTE_ARRAY> {
using value_type = FixedLenByteArray;
static constexpr int value_byte_size = sizeof(FixedLenByteArray);
static constexpr const char* printf_code = "s";
};
template <Type::type TYPE>
struct DataType {
using c_type = typename type_traits<TYPE>::value_type;
static constexpr Type::type type_num = TYPE;
};
using BooleanType = DataType<Type::BOOLEAN>;
using Int32Type = DataType<Type::INT32>;
using Int64Type = DataType<Type::INT64>;
using Int96Type = DataType<Type::INT96>;
using FloatType = DataType<Type::FLOAT>;
using DoubleType = DataType<Type::DOUBLE>;
using ByteArrayType = DataType<Type::BYTE_ARRAY>;
using FLBAType = DataType<Type::FIXED_LEN_BYTE_ARRAY>;
template <typename Type>
inline std::string format_fwf(int width) {
std::stringstream ss;
ss << "%-" << width << type_traits<Type::type_num>::printf_code;
return ss.str();
}
PARQUET_EXPORT std::string CompressionToString(Compression::type t);
PARQUET_EXPORT std::string EncodingToString(Encoding::type t);
PARQUET_EXPORT std::string LogicalTypeToString(LogicalType::type t);
PARQUET_EXPORT std::string TypeToString(Type::type t);
PARQUET_EXPORT std::string FormatStatValue(Type::type parquet_type,
const std::string& val);
/// \deprecated Since 1.5.0
PARQUET_DEPRECATED("Use std::string instead of char* as input")
PARQUET_EXPORT std::string FormatStatValue(Type::type parquet_type, const char* val);
PARQUET_EXPORT int GetTypeByteSize(Type::type t);
PARQUET_EXPORT SortOrder::type DefaultSortOrder(Type::type primitive);
PARQUET_EXPORT SortOrder::type GetSortOrder(LogicalType::type converted,
Type::type primitive);
} // namespace parquet
#endif // PARQUET_TYPES_H
|
{
"content_hash": "431c0fb1723e1e07dd8d365c09facb27",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 90,
"avg_line_length": 27.091549295774648,
"alnum_prop": 0.6774109695866909,
"repo_name": "apache/parquet-cpp",
"id": "10789cbf5452dbc15282f1125c1d550d99dcf106",
"size": "8765",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/parquet/types.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4350"
},
{
"name": "C",
"bytes": "12729"
},
{
"name": "C++",
"bytes": "1043162"
},
{
"name": "CMake",
"bytes": "104812"
},
{
"name": "Perl",
"bytes": "4010"
},
{
"name": "Python",
"bytes": "17142"
},
{
"name": "Ruby",
"bytes": "4368"
},
{
"name": "Shell",
"bytes": "34266"
},
{
"name": "Thrift",
"bytes": "28874"
}
],
"symlink_target": ""
}
|
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__)
TEST_GROUP(UnitTestStringMacros)
{
TestTestingFixture fixture;
};
static void _STRCMP_EQUALWithActualIsNULLTestMethod()
{
STRCMP_EQUAL("ok", NULL);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_EQUALWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>");
}
static void _STRCMP_EQUALWithExpectedIsNULLTestMethod()
{
STRCMP_EQUAL(NULL, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_EQUALWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>");
}
static void _STRCMP_CONTAINSWithActualIsNULLTestMethod()
{
STRCMP_CONTAINS("ok", NULL);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_CONTAINSWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>");
}
static void _STRCMP_CONTAINSWithExpectedIsNULLTestMethod()
{
STRCMP_CONTAINS(NULL, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_CONTAINSWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>");
}
static void _STRNCMP_EQUALWithActualIsNULLTestMethod()
{
STRNCMP_EQUAL("ok", NULL, 2);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndActualIsNULL)
{
fixture.runTestWithMethod(_STRNCMP_EQUALWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>");
}
static void _STRNCMP_EQUALWithExpectedIsNULLTestMethod()
{
STRNCMP_EQUAL(NULL, "ok", 2);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRNCMP_EQUALWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>");
}
static void _STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod()
{
STRCMP_NOCASE_EQUAL("ok", NULL);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>");
}
static void _STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod()
{
STRCMP_NOCASE_EQUAL(NULL, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>");
}
static void _STRCMP_NOCASE_EQUALWithUnequalInputTestMethod()
{
STRCMP_NOCASE_EQUAL("no", "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndUnequalInput)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithUnequalInputTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <ok>");
}
static void _STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod()
{
STRCMP_NOCASE_CONTAINS("ok", NULL);
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndActualIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>");
}
static void _STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod()
{
STRCMP_NOCASE_CONTAINS(NULL, "ok");
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndExpectedIsNULL)
{
fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>");
}
static void _failingTestMethodWithSTRCMP_EQUAL()
{
STRCMP_EQUAL("hello", "hell");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>");
}
TEST(UnitTestStringMacros, STRCMP_EQUALBehavesAsProperMacro)
{
if (false) STRCMP_EQUAL("1", "2")
else STRCMP_EQUAL("1", "1")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUALWorksInAnIgnoredTest)
{
STRCMP_EQUAL("Hello", "World") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_EQUAL_TEXT()
{
STRCMP_EQUAL_TEXT("hello", "hell", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_EQUAL_TEXT("1", "2", "Failed because it failed")
else STRCMP_EQUAL_TEXT("1", "1", "Failed because it failed")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTWorksInAnIgnoredTest)
{
STRCMP_EQUAL_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRNCMP_EQUAL()
{
STRNCMP_EQUAL("hello", "hallo", 5);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>");
}
TEST(UnitTestStringMacros, STRNCMP_EQUALBehavesAsProperMacro)
{
if (false) STRNCMP_EQUAL("1", "2", 1)
else STRNCMP_EQUAL("1", "1", 1)
}
IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUALWorksInAnIgnoredTest)
{
STRNCMP_EQUAL("Hello", "World", 3) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRNCMP_EQUAL_TEXT()
{
STRNCMP_EQUAL_TEXT("hello", "hallo", 5, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) STRNCMP_EQUAL_TEXT("1", "2", 1, "Failed because it failed")
else STRNCMP_EQUAL_TEXT("1", "1", 1, "Failed because it failed")
}
IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTWorksInAnIgnoredTest)
{
STRNCMP_EQUAL_TEXT("Hello", "World", 3, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL()
{
STRCMP_NOCASE_EQUAL("hello", "Hell");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hell>");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_EQUAL("1", "2")
else STRCMP_NOCASE_EQUAL("1", "1")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALWorksInAnIgnoredTest)
{
STRCMP_NOCASE_EQUAL("Hello", "World") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT()
{
STRCMP_NOCASE_EQUAL_TEXT("hello", "hell", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_EQUAL_TEXT("1", "2", "Failed because it failed")
else STRCMP_NOCASE_EQUAL_TEXT("1", "1", "Failed because it failed")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTWorksInAnIgnoredTest)
{
STRCMP_NOCASE_EQUAL_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_CONTAINS()
{
STRCMP_CONTAINS("hello", "world");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
}
TEST(UnitTestStringMacros, STRCMP_CONTAINSBehavesAsProperMacro)
{
if (false) STRCMP_CONTAINS("1", "2")
else STRCMP_CONTAINS("1", "1")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINSWorksInAnIgnoredTest)
{
STRCMP_CONTAINS("Hello", "World") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_CONTAINS_TEXT()
{
STRCMP_CONTAINS_TEXT("hello", "world", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_CONTAINS_TEXT("1", "2", "Failed because it failed")
else STRCMP_CONTAINS_TEXT("1", "1", "Failed because it failed")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTWorksInAnIgnoredTest)
{
STRCMP_CONTAINS_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS()
{
STRCMP_NOCASE_CONTAINS("hello", "WORLD");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINSBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_CONTAINS("never", "executed")
else STRCMP_NOCASE_CONTAINS("hello", "HELLO WORLD")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINSWorksInAnIgnoredTest)
{
STRCMP_NOCASE_CONTAINS("Hello", "World") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT()
{
STRCMP_NOCASE_CONTAINS_TEXT("hello", "WORLD", "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINS_TEXTBehavesAsProperMacro)
{
if (false) STRCMP_NOCASE_CONTAINS_TEXT("never", "executed", "Failed because it failed")
else STRCMP_NOCASE_CONTAINS_TEXT("hello", "HELLO WORLD", "Failed because it failed")
}
IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINS_TEXTWorksInAnIgnoredTest)
{
STRCMP_NOCASE_CONTAINS_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, NFirstCharsComparison)
{
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 0);
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 1);
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 6);
STRNCMP_EQUAL("Hello World!", "Hello", 5);
}
static void _compareNFirstCharsWithUpperAndLowercase()
{
STRNCMP_EQUAL("hello world!", "HELLO WORLD!", 12);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithUpperAndLowercase)
{
fixture.runTestWithMethod(_compareNFirstCharsWithUpperAndLowercase);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello world!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <HELLO WORLD!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0");
}
static void _compareNFirstCharsWithDifferenceInTheMiddle()
{
STRNCMP_EQUAL("Hello World!", "Hello Peter!", 12);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithDifferenceInTheMiddle)
{
fixture.runTestWithMethod(_compareNFirstCharsWithDifferenceInTheMiddle);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Hello World!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hello Peter!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 6");
}
static void _compareNFirstCharsWithEmptyString()
{
STRNCMP_EQUAL("", "Not empty string", 5);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithEmptyString)
{
fixture.runTestWithMethod(_compareNFirstCharsWithEmptyString);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0");
}
static void _compareNFirstCharsWithLastCharDifferent()
{
STRNCMP_EQUAL("Not empty string?", "Not empty string!", 17);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestStringMacros, CompareNFirstCharsWithLastCharDifferent)
{
fixture.runTestWithMethod(_compareNFirstCharsWithLastCharDifferent);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Not empty string?>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string!>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 16");
}
|
{
"content_hash": "2e997f3f3a397309a1faf66911a97fd2",
"timestamp": "",
"source": "github",
"line_count": 443,
"max_line_length": 118,
"avg_line_length": 33.794582392776526,
"alnum_prop": 0.7480462226972147,
"repo_name": "jaeguly/cpputest",
"id": "62ac79ddb5ddeb94c36407b3787ec2e841a0b9e0",
"size": "16573",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "tests/TestUTestStringMacro.cpp",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "36202"
},
{
"name": "Batchfile",
"bytes": "3440"
},
{
"name": "C",
"bytes": "635413"
},
{
"name": "C++",
"bytes": "1311080"
},
{
"name": "CMake",
"bytes": "22814"
},
{
"name": "Makefile",
"bytes": "93870"
},
{
"name": "PowerShell",
"bytes": "6290"
},
{
"name": "Ruby",
"bytes": "19028"
},
{
"name": "Shell",
"bytes": "16422"
}
],
"symlink_target": ""
}
|
package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.connector.internal.InternalConnector;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MatcherWrapper;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
public class NavigateAnyPointActivity extends AbstractActionBarActivity {
private static final Pattern PATTERN_COORDS_NAME = Pattern.compile("^geo:0,0\\?q=([-]?[0-9]{1,2}\\.[0-9]{1,15}),([-]?[0-9]{1,3}\\.[0-9]{1,15})(\\((.*)\\))?$");
private static final Pattern PATTERN_COORDS = Pattern.compile("^geo:([-]?[0-9]{1,2}\\.[0-9]{1,15}),([-]?[0-9]{1,3}\\.[0-9]{1,15})$");
private static final Pattern PATTERN_COORDS_ZOOM = Pattern.compile("^geo:([-]?[0-9]{1,2}\\.[0-9]{1,15}),([-]?[0-9]{1,3}\\.[0-9]{1,15})\\?z=([1-9]|1[0-9]|2[0-3])$");
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.cgeo);
InternalConnector.assertHistoryCacheExists(this);
// check if "geo" action is requested
boolean geoActionRequested = false;
final String data = getIntent().getDataString();
if (StringUtils.isNotBlank(data)) {
MatcherWrapper match = new MatcherWrapper(PATTERN_COORDS, data);
if (match.find()) {
Log.i("Received a geo intent: lat=" + match.group(1) + ", lon=" + match.group(2));
selectTargetType(this, Double.parseDouble(match.group(1)), Double.parseDouble(match.group(2)), null);
geoActionRequested = true;
} else {
match = new MatcherWrapper(PATTERN_COORDS_NAME, data);
if (match.find()) {
Log.i("Received a geo intent: lat=" + match.group(1) + ", lon=" + match.group(2) + ", name=" + match.group(4));
try {
selectTargetType(this, Double.parseDouble(match.group(1)), Double.parseDouble(match.group(2)), URLDecoder.decode(match.group(4), "UTF-8"));
} catch (UnsupportedEncodingException e) {
// try without URL decoding as fallback
selectTargetType(this, Double.parseDouble(match.group(1)), Double.parseDouble(match.group(2)), match.group(4));
}
geoActionRequested = true;
} else {
match = new MatcherWrapper(PATTERN_COORDS_ZOOM, data);
if (match.find()) {
Log.i("Received a geo intent: lat=" + match.group(1) + ", lon=" + match.group(2) + ", zoom=" + match.group(3) + " (zoom level being ignored currently)");
selectTargetType(this, Double.parseDouble(match.group(1)), Double.parseDouble(match.group(2)), null);
geoActionRequested = true;
}
}
}
}
if (!geoActionRequested) {
CacheDetailActivity.startActivity(this, InternalConnector.GEOCODE_HISTORY_CACHE, true);
finish();
}
}
private static void selectTargetType(final Activity context, final double latitude, final double longitude, @Nullable final String name) {
final ArrayList<Geocache> items = new ArrayList<>();
items.add(null);
items.add(DataStore.loadCache(InternalConnector.GEOCODE_HISTORY_CACHE, LoadFlags.LOAD_CACHE_OR_DB));
items.addAll(DataStore.loadUDCSorted());
final LayoutInflater inflater = LayoutInflater.from(context);
final ListAdapter adapter = new ArrayAdapter<Geocache>(context, R.layout.cacheslist_item_select, items) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
final View view = convertView == null ? inflater.inflate(R.layout.twotexts_twobuttons_item, parent, false) : convertView;
final TextView title = (TextView) view.findViewById(R.id.title);
final TextView detail = (TextView) view.findViewById(R.id.detail);
final Geocache item = getItem(position);
title.setText(item == null ? "<" + context.getString(R.string.create_internal_cache_short) + ">" : item.getName());
if (null != item) {
title.setCompoundDrawablesWithIntrinsicBounds(item.getType().markerId, 0, 0, 0);
detail.setText(item.getShortGeocode());
} else {
detail.setText(context.getString(R.string.create_internal_cache));
}
return view;
}
};
final AlertDialog dialog = Dialogs.newBuilder(context)
.setTitle(R.string.add_target_to)
.setAdapter(adapter, (dialog1, which) -> {
final String geocode;
if (which == 0) {
// create new UDC
geocode = InternalConnector.createCache(context, name, null, 0, new Geopoint(latitude, longitude), StoredList.STANDARD_LIST_ID);
} else {
// add to an existing UDC
geocode = items.get(which).getGeocode();
final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB);
final Waypoint newWaypoint = new Waypoint(null != name ? name : Waypoint.getDefaultWaypointName(cache, WaypointType.WAYPOINT), WaypointType.WAYPOINT, true);
newWaypoint.setCoords(new Geopoint(latitude, longitude));
newWaypoint.setGeocode(geocode);
cache.addOrChangeWaypoint(newWaypoint, true);
}
CacheDetailActivity.startActivity(context, geocode, which != 0);
context.finish();
})
.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
}
|
{
"content_hash": "03186df95394f725cb7c765e1baaea2a",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 177,
"avg_line_length": 49.16546762589928,
"alnum_prop": 0.617500731635938,
"repo_name": "rsudev/c-geo-opensource",
"id": "ece88f29ac99a7573daf03252ba408274cc89d47",
"size": "6834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main/src/cgeo/geocaching/NavigateAnyPointActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AIDL",
"bytes": "2756"
},
{
"name": "HTML",
"bytes": "2984533"
},
{
"name": "Java",
"bytes": "5664213"
},
{
"name": "Shell",
"bytes": "8245"
}
],
"symlink_target": ""
}
|
classdef Pooling < dagnn.Filter
properties
method = 'max'
poolSize = [1 2]
opts = {'cuDNN'}
end
methods
function outputs = forward(self, inputs, params)
outputs{1} = vl_nnpool(inputs{1}, self.poolSize, ...
'pad', self.pad, ...
'stride', self.stride, ...
'method', self.method, ...
self.opts{:}) ;
end
function [derInputs, derParams] = backward(self, inputs, params, derOutputs)
derInputs{1} = vl_nnpool(inputs{1}, self.poolSize, derOutputs{1}, ...
'pad', self.pad, ...
'stride', self.stride, ...
'method', self.method, ...
self.opts{:}) ;
derParams = {} ;
end
function kernelSize = getKernelSize(obj)
kernelSize = obj.poolSize ;
end
function outputSizes = getOutputSizes(obj, inputSizes)
outputSizes = getOutputSizes@dagnn.Filter(obj, inputSizes) ;
outputSizes{1}(3) = inputSizes{1}(3) ;
end
function obj = Pooling(varargin)
obj.load(varargin) ;
end
end
end
|
{
"content_hash": "2390a47a9b3de4d7fba5d0247d60b6fb",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 80,
"avg_line_length": 30.897435897435898,
"alnum_prop": 0.4987551867219917,
"repo_name": "feichtenhofer/twostreamfusion",
"id": "c2814eadc202272f70ea4303d62a70c00dd08c65",
"size": "1205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "matconvnet/matlab/+dagnn/Pooling.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "21309"
},
{
"name": "C++",
"bytes": "197442"
},
{
"name": "Cuda",
"bytes": "316535"
},
{
"name": "Matlab",
"bytes": "312400"
},
{
"name": "Shell",
"bytes": "10182"
}
],
"symlink_target": ""
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text.Primitives.Tests.Encoding
{
public static class TextEncoderTestHelper
{
public static string GenerateValidString(int length, CodePointSubset subset)
{
int minCodePoint = 0;
int maxCodePoint = 0;
bool ignoreSurrogates = false;
switch (subset)
{
case CodePointSubset.ASCII:
maxCodePoint = TextEncoderConstants.Utf8OneByteLastCodePoint;
break;
case CodePointSubset.TwoBytes:
minCodePoint = TextEncoderConstants.Utf8OneByteLastCodePoint + 1;
maxCodePoint = TextEncoderConstants.Utf8TwoBytesLastCodePoint;
break;
case CodePointSubset.ThreeBytes:
minCodePoint = TextEncoderConstants.Utf8TwoBytesLastCodePoint + 1;
maxCodePoint = TextEncoderConstants.Utf8ThreeBytesLastCodePoint;
ignoreSurrogates = true;
break;
case CodePointSubset.Surrogates:
minCodePoint = TextEncoderConstants.Utf16HighSurrogateFirstCodePoint;
maxCodePoint = TextEncoderConstants.Utf16LowSurrogateLastCodePoint;
break;
case CodePointSubset.Mixed:
maxCodePoint = TextEncoderConstants.Utf8ThreeBytesLastCodePoint;
break;
default:
break;
}
return GenerateValidString(TextEncoderConstants.DataLength, minCodePoint, maxCodePoint, ignoreSurrogates);
}
public static string GenerateValidString(int length, int minCodePoint, int maxCodePoint, bool ignoreSurrogates = false)
{
Random rand = new Random(TextEncoderConstants.RandomSeed);
var plainText = new StringBuilder();
for (int j = 0; j < length; j++)
{
var val = rand.Next(minCodePoint, maxCodePoint + 1);
if (ignoreSurrogates)
{
while (val >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
val = rand.Next(minCodePoint, maxCodePoint + 1); // skip surrogate characters
}
plainText.Append((char)val);
continue;
}
if (j < length - 1)
{
while (val >= TextEncoderConstants.Utf16LowSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
val = rand.Next(minCodePoint, maxCodePoint + 1); // skip surrogate characters if they can't be paired
}
if (val >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16HighSurrogateLastCodePoint)
{
plainText.Append((char)val); // high surrogate
j++;
val = rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1); // low surrogate
}
}
else
{
while (val >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
val = rand.Next(0, TextEncoderConstants.Utf8ThreeBytesLastCodePoint + 1); // skip surrogate characters if they can't be paired
}
}
plainText.Append((char)val);
}
return plainText.ToString();
}
public static string GenerateStringAlternatingASCIIAndNonASCII(int charLength)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 5);
var plainText = new StringBuilder();
for (int j = 0; j < charLength / 3; j++)
{
var ascii = rand.Next(0, TextEncoderConstants.Utf8OneByteLastCodePoint + 1);
var highSurrogate = rand.Next(TextEncoderConstants.Utf16HighSurrogateFirstCodePoint, TextEncoderConstants.Utf16HighSurrogateLastCodePoint + 1);
var lowSurrogate = rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1);
plainText.Append((char)ascii);
plainText.Append((char)highSurrogate);
plainText.Append((char)lowSurrogate);
}
for (int j = 0; j < charLength % 3; j++)
{
plainText.Append((char)rand.Next(0, TextEncoderConstants.Utf8OneByteLastCodePoint + 1));
}
return plainText.ToString();
}
public static string GenerateStringWithMostlyASCIIAndSomeNonASCII(int charLength)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 6);
var plainText = new StringBuilder();
int j = 0;
while (j < charLength - 70)
{
for (int i = 0; i < rand.Next(20, 51); i++)
{
var ascii = rand.Next(0, TextEncoderConstants.Utf8OneByteLastCodePoint + 1);
plainText.Append((char)ascii);
j++;
}
for (int i = 0; i < rand.Next(5, 11); i++)
{
var highSurrogate = rand.Next(TextEncoderConstants.Utf16HighSurrogateFirstCodePoint, TextEncoderConstants.Utf16HighSurrogateLastCodePoint + 1);
var lowSurrogate = rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1);
j += 2;
plainText.Append((char)highSurrogate);
plainText.Append((char)lowSurrogate);
}
}
while (j < charLength)
{
plainText.Append((char)rand.Next(0, TextEncoderConstants.Utf8OneByteLastCodePoint + 1));
j++;
}
return plainText.ToString();
}
public static string GenerateAllCharacters()
{
var plainText = new StringBuilder();
for (int j = 0; j <= TextEncoderConstants.Utf8ThreeBytesLastCodePoint; j++)
{
if (j >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && j <= TextEncoderConstants.Utf16HighSurrogateLastCodePoint)
{
// high surrogate, pair it with all low surrogates possible
for (int i = TextEncoderConstants.Utf16LowSurrogateFirstCodePoint; i <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint; i++)
{
plainText.Append((char)j);
plainText.Append((char)i);
}
}
else if (!IsSupportedCodePoint((uint)j))
{
continue; // don't want unpaird low surrogates
}
else
{
// characters not reserved for surrogate pairs
plainText.Append((char)j);
}
}
return plainText.ToString(); // Length should be 0x10FFFF characters (1114112 in decimal)
}
public static string GenerateOnlyInvalidString(int length, bool highSurrogateOnly = false)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 2);
var plainText = new StringBuilder();
for (int j = 0; j < length; j++)
{
var val = highSurrogateOnly ?
rand.Next(TextEncoderConstants.Utf16HighSurrogateFirstCodePoint, TextEncoderConstants.Utf16HighSurrogateLastCodePoint + 1) :
rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1);
plainText.Append((char)val);
}
return plainText.ToString();
}
public static byte[] GenerateOnlyInvalidUtf8Bytes(int length)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 2);
var utf8Byte = new byte[length];
for (int j = 0; j < length; j++)
{
var val = rand.Next(0x60, 0xFF + 1); // Each byte starts with 11xx xxxx with no bytes that start with 10xx xxxx following it.
utf8Byte[j] = (byte)val;
}
return utf8Byte;
}
public static uint[] GenerateOnlyInvalidUtf32CodePoints(int length)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 2);
var codepoints = new uint[length];
for (int j = 0; j < length; j++)
codepoints[j] = GenerateInvalidCodePoint(ref rand);
return codepoints;
}
public static string GenerateInvalidStringEndsWithLow(int length)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 3);
var plainText = new StringBuilder();
for (int j = 0; j < length - 1; j++)
{
var val = rand.Next(0, TextEncoderConstants.Utf8TwoBytesLastCodePoint + 1);
plainText.Append((char)val);
}
// last char should be low surrogate (no high surrogate before, invalid)
plainText.Append((char)rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1));
return plainText.ToString();
}
public static string GenerateStringWithInvalidChars(int length)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 3);
var plainText = new StringBuilder();
for (int j = 0; j < length; j++)
{
var val = rand.Next(0, TextEncoderConstants.Utf8ThreeBytesLastCodePoint + 1);
if (j < length - 1)
{
while (val >= TextEncoderConstants.Utf16LowSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
val = rand.Next(0, TextEncoderConstants.Utf8ThreeBytesLastCodePoint + 1); // skip surrogate characters if they can't be paired
}
if (val >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16HighSurrogateLastCodePoint)
{
plainText.Append((char)val); // high surrogate
j++;
val = rand.Next(0, TextEncoderConstants.Utf8ThreeBytesLastCodePoint + 1); // high surrogate may not be paired with a low surrogate (invalid)
}
}
else
{
// last char should be high surrogate (no low surrogate after, invalid)
val = rand.Next(TextEncoderConstants.Utf16HighSurrogateFirstCodePoint, TextEncoderConstants.Utf16HighSurrogateLastCodePoint + 1);
}
plainText.Append((char)val);
}
return plainText.ToString();
}
public static byte[] GenerateUtf8BytesWithInvalidBytes(int length)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 3);
var utf8Byte = new byte[length];
for (int j = 0; j < length; j++)
{
// High probability of invalid utf8 bytes since there is no gaurantee that bytes following a byte within 0x60 and 0xFF
// will be of the required form 10xx xxxx (and that there will be the correct number of such bytes).
var val = rand.Next(0, 0xFF + 1);
if (j < length - 1)
{
utf8Byte[j] = (byte)val;
}
else
{
utf8Byte[j] = 0xFF; // Only possible for codepoints larger than 0x10FFFF, hence invalid
}
}
return utf8Byte;
}
public static uint[] GenerateUtf32WithInvalidCodePoints(int length)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 3);
var codepoints = new uint[length];
for (int j = 0; j < length; j++)
{
// Every 10 codepoints, we will inject a guaranteed invalid one.
// However, there may be others as well based on small ranges inside the valid codepoint range.
if (j % 10 == 0)
codepoints[j] = GenerateInvalidCodePoint(ref rand);
else
codepoints[j] = (uint)rand.Next(0, 0x110000);
}
return codepoints;
}
public static string GenerateValidStringEndsWithHighStartsWithLow(int length, bool startsWithLow)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 4);
var plainText = new StringBuilder();
int val = rand.Next(0, TextEncoderConstants.Utf8TwoBytesLastCodePoint + 1);
if (length > 0)
{
if (startsWithLow)
{
// first character must be low surrogate
val = rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1);
}
plainText.Append((char)val);
}
for (int j = 1; j < length; j++)
{
val = rand.Next(0, TextEncoderConstants.Utf8ThreeBytesLastCodePoint + 1);
if (j < length - 1)
{
while (val >= TextEncoderConstants.Utf16LowSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
val = rand.Next(0, TextEncoderConstants.Utf8ThreeBytesLastCodePoint + 1); // skip surrogate characters if they can't be paired
}
if (val >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16HighSurrogateLastCodePoint)
{
plainText.Append((char)val); // high surrogate
j++;
val = rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1); // low surrogate
}
}
else
{
// if first char is valid, last char should be high surrogate (no low surrogate after, invalid)
val = startsWithLow ? rand.Next(0, TextEncoderConstants.Utf8OneByteLastCodePoint + 1) : rand.Next(TextEncoderConstants.Utf16HighSurrogateFirstCodePoint, TextEncoderConstants.Utf16HighSurrogateLastCodePoint + 1);
}
plainText.Append((char)val);
}
return plainText.ToString();
}
public static uint[] GenerateValidUtf32CodePoints(int length)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 3);
var codepoints = new uint[length];
for (int j = 0; j < length; j++)
{
while (true)
{
codepoints[j] = (uint)rand.Next(0, 0x110000);
if (IsSupportedCodePoint(codepoints[j]))
break;
}
}
return codepoints;
}
public static byte[] GenerateValidBytesUtf32EndsWithHighStartsWithLow(int length, bool startsWithLow)
{
Random rand = new Random(TextEncoderConstants.RandomSeed * 4);
var utf32 = new byte[length*4];
int val = rand.Next(0, TextEncoderConstants.Utf8TwoBytesLastCodePoint + 1);
if (length > 0)
{
if (startsWithLow)
{
val = rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1);
}
WriteToArray(ref utf32, 0, val);
}
for (int j = 1; j < length - 1; j++)
{
val = rand.Next(0, (int)TextEncoderConstants.LastValidCodePoint + 1);
if (j < length - 1)
{
while (val >= TextEncoderConstants.Utf16LowSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
val = rand.Next(0, (int)TextEncoderConstants.LastValidCodePoint + 1); // skip surrogate characters if they can't be paired
}
if (val >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && val <= TextEncoderConstants.Utf16HighSurrogateLastCodePoint)
{
WriteToArray(ref utf32, j*4, val); // high surrogate
j++;
val = rand.Next(TextEncoderConstants.Utf16LowSurrogateFirstCodePoint, TextEncoderConstants.Utf16LowSurrogateLastCodePoint + 1); // low surrogate
}
}
else
{
// if first char is valid, last char should be high surrogate (no low surrogate after, invalid)
val = startsWithLow ? rand.Next(0, TextEncoderConstants.Utf8OneByteLastCodePoint + 1) : rand.Next(TextEncoderConstants.Utf16HighSurrogateFirstCodePoint, TextEncoderConstants.Utf16HighSurrogateLastCodePoint + 1);
}
WriteToArray(ref utf32, j * 4, val);
}
return utf32;
}
private static void WriteToArray(ref byte[] utf32, int index, int val)
{
byte[] intBytes = BitConverter.GetBytes(val);
Array.Copy(intBytes, 0, utf32, index, intBytes.Length);
}
public static int GetUtf8ByteCount(ReadOnlySpan<byte> utf8)
{
var inputLength = utf8.Length;
int byteCount = 0;
while (byteCount < inputLength)
{
byte byte1 = utf8[byteCount];
if ((byte1 & 0x80) == 0)
{
byteCount += 1;
}
else if ((byte1 & 0xE0) == 0xC0)
{
if (byteCount + 1 >= inputLength) return byteCount; //not enough bytes follow
byte byte2 = utf8[byteCount + 1];
if ((byte2 & 0x60) != 0x40) return byteCount; // invalid byte sequence. Expect 10xx xxxx
byteCount += 2;
}
else if ((byte1 & 0xF0) == 0xE0)
{
if (byteCount + 2 >= inputLength) return byteCount; //not enough bytes follow
byte byte2 = utf8[byteCount + 1];
byte byte3 = utf8[byteCount + 2];
if ((byte2 & 0x60) != 0x40) return byteCount; // invalid byte sequence. Expect 10xx xxxx
if ((byte3 & 0x60) != 0x40) return byteCount;
byteCount += 3;
}
else if ((byte1 & 0xF8) == 0xF0)
{
if (byteCount + 3 >= inputLength) return byteCount; //not enough bytes follow
byte byte2 = utf8[byteCount + 1];
byte byte3 = utf8[byteCount + 2];
byte byte4 = utf8[byteCount + 3];
if ((byte2 & 0x60) != 0x40) return byteCount; // invalid byte sequence. Expect 10xx xxxx
if ((byte3 & 0x60) != 0x40) return byteCount;
if ((byte4 & 0x60) != 0x40) return byteCount;
byteCount += 4;
}
else
{
return byteCount; // invalid first byte
}
}
return byteCount;
}
public static int GetUtf8ByteCount(ReadOnlySpan<char> utf16)
{
var inputLength = utf16.Length;
int byteCount = 0;
for (int i = 0; i < inputLength; i++)
{
char codePoint = utf16[i];
if (codePoint <= TextEncoderConstants.Utf8OneByteLastCodePoint)
{
byteCount += 1;
}
else if (codePoint <= TextEncoderConstants.Utf8TwoBytesLastCodePoint)
{
byteCount += 2;
}
else if (codePoint >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && codePoint <= TextEncoderConstants.Utf16HighSurrogateLastCodePoint)
{
i++;
if (i >= inputLength)
{
return byteCount;
}
char lowSurrogate = utf16[i];
if (lowSurrogate < TextEncoderConstants.Utf16LowSurrogateFirstCodePoint || lowSurrogate > TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
return byteCount; // invalid char
}
byteCount += 4;
}
else if (codePoint >= TextEncoderConstants.Utf16LowSurrogateFirstCodePoint && codePoint <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
{
return byteCount; // invalid char
}
else
{
byteCount += 3;
}
}
return byteCount;
}
public static int GetUtf8ByteCount(string utf16String)
{
return GetUtf8ByteCount(utf16String.AsSpan());
}
public static int GetUtf8ByteCount(ReadOnlySpan<uint> utf32)
{
int byteCount = 0;
for (int i = 0; i < utf32.Length; i++)
{
uint codePoint = utf32[i];
if (!IsSupportedCodePoint(codePoint))
return byteCount;
else if (codePoint > TextEncoderConstants.Utf8ThreeBytesLastCodePoint)
byteCount += 4;
else if (codePoint > TextEncoderConstants.Utf8TwoBytesLastCodePoint)
byteCount += 3;
else if (codePoint > TextEncoderConstants.Utf8OneByteLastCodePoint)
byteCount += 2;
else
byteCount += 1;
}
return byteCount;
}
public static bool IsSupportedCodePoint(uint codePoint)
{
if (codePoint > TextEncoderConstants.LastValidCodePoint)
return false;
if (codePoint >= TextEncoderConstants.Utf16HighSurrogateFirstCodePoint && codePoint <= TextEncoderConstants.Utf16LowSurrogateLastCodePoint)
return false;
return true;
}
public static uint GenerateInvalidCodePoint(ref Random rnd)
{
int range = rnd.Next(0, 2);
if (range == 0)
return (uint)rnd.Next(0xD800, 0xE000); // Generate a random surrogate
else
return (uint)rnd.Next(0x110000, 0xFFFFFF); // Generate something above 0x110000
}
public enum CodePointSubset
{
ASCII, TwoBytes, ThreeBytes, Surrogates, Mixed
}
public enum SupportedEncoding
{
FromUtf8, FromUtf16, FromString, FromUtf32
}
}
}
|
{
"content_hash": "df850d1a9ae62d03558a90c2a1c47c52",
"timestamp": "",
"source": "github",
"line_count": 550,
"max_line_length": 231,
"avg_line_length": 44.11272727272727,
"alnum_prop": 0.5410106339131152,
"repo_name": "KrzysztofCwalina/corefxlab",
"id": "c69c8484f4f56067177c7812040f9c8f0c291421",
"size": "24264",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "tests/System.Text.Primitives.Tests/Encoding/TextEncoderTestHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "678"
},
{
"name": "C#",
"bytes": "5811431"
},
{
"name": "Groovy",
"bytes": "2527"
},
{
"name": "PowerShell",
"bytes": "26234"
},
{
"name": "Shell",
"bytes": "25169"
}
],
"symlink_target": ""
}
|
<div class="row">
<div ng-controller="CreateDishCtrl as cuc">
<h1>Create Dish</h1>
<form id="CreateDishForm" name="CreateDishForm" class="form-horizontal" role="form"
ng-submit="cuc.createDish()">
<legend class="sm-col-12">Basic Information</legend>
<div class="form-group">
<label id="lbl_firstName" for="firstName" class="col-sm-4 control-label">First Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="firstName" id="firstName" placeholder=""
ng-model="cuc.dish.firstName">
</div>
</div>
<div class="form-group">
<label id="lbl_lastName" for="lastName" class="col-sm-4 control-label">Last Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="lastName" id="lastName" placeholder=""
ng-model="cuc.dish.lastName">
</div>
</div>
<div class="form-group">
<label id="lbl_age" for="age" class="col-sm-4 control-label"
is-required="CreateDishForm.age">Age</label>
<div class="col-sm-8">
<input type="number" class="form-control" name="age" id="age"
ng-model="cuc.dish.age">
</div>
</div>
<pre>{{ cuc.dish | json }}</pre>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8 text-right">
<a ng-href="/#/" id="btn_cancel" class="btn btn-warning">Cancel</a>
<button type="submit" class="btn btn-success" id="btn_create">Create Dish</button>
</div>
</div>
</form>
</div>
</div>
|
{
"content_hash": "5c20c7a18ea88df476b3b49d3b0f4969",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 107,
"avg_line_length": 37.19607843137255,
"alnum_prop": 0.4881391671059568,
"repo_name": "joludigo/home-made",
"id": "c33f5d3e04a1b56e2ce6f85de11cc9a91502ef7e",
"size": "1897",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/partials/createDish.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "146"
},
{
"name": "CoffeeScript",
"bytes": "6121"
},
{
"name": "Scala",
"bytes": "14509"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (c) 2013 Soichiro Kashima.
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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#FFFFFFFF"/>
<item android:state_enabled="false" android:state_pressed="false" android:color="#FF999999"/>
<item android:color="#FF333333"/>
</selector>
|
{
"content_hash": "461771ad0a6668fe74af291f7bbb2a15",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 97,
"avg_line_length": 49.206896551724135,
"alnum_prop": 0.759635599159075,
"repo_name": "owwlo/JarIt",
"id": "43bab8f304c628e656c31cfd3ce0ac92bcb8ad64",
"size": "1427",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "res/drawable/rb__button_text_color.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "61993"
}
],
"symlink_target": ""
}
|
<?php
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
function getAllTasksFromProject($projectId){
global $conn;
$stmt = $conn->prepare("SELECT * FROM task WHERE project_id = ? ORDER BY deadline ASC;");
$stmt->execute($projectId);
return $stmt->fetchAll();
}
function getTagFromTaskId($taskId){
global $conn;
$stmt = $conn->prepare("SELECT DISTINCT tag.name, tag.id FROM tag, task_tag WHERE task_tag.task_id = ? AND tag.id = task_tag.tag_id;");
$stmt->execute([$taskId]);
return $stmt->fetchAll();
}
function createTask(){
global $conn;
$stmt = $conn->prepare("INSERT INTO task (id, name, description, deadline, creator_id, assigned_id, completer_id, project_id) VALUES (DEFAULT, ?, NULL, NULL, ?, NULL, NULL, ?) RETURNING id;");
$stmt->execute(["New Task", $_SESSION['user_id'], $_SESSION['project_id']]);
}
function completeTask(){
}
function deleteTask($taskId){
}
function getTaskDetails($taskId){
global $conn;
$stmt = $conn->prepare("SELECT * FROM task WHERE id = ?;");
$stmt->execute([$taskId]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function getTaskName($taskId){
global $conn;
$stmt = $conn->prepare("SELECT name FROM task WHERE id = ?;");
$stmt->execute([$taskId]);
return $stmt->fetchAll();
}
function getTaskDescription($taskId){
global $conn;
$stmt = $conn->prepare("SELECT description FROM task WHERE id = ?;");
$stmt->execute([$taskId]);
return $stmt->fetchAll();
}
function getTaskDeadline($taskId){
global $conn;
$stmt = $conn->prepare("SELECT deadline FROM task WHERE id = ?;");
$stmt->execute([$taskId]);
return $stmt->fetchAll();
}
function getTaskCreatorName($taskId){
global $conn;
$stmt = $conn->prepare("SELECT name FROM user_table, task WHERE task.id = ? AND task.creator_id = user_table.id;");
$stmt->execute([$taskId]);
return $stmt->fetchAll();
}
function getTaskAssignedName($taskId){
global $conn;
$stmt = $conn->prepare("SELECT user_table.name, user_table.id FROM user_table, task WHERE task.id = ? AND task.assigned_id = user_table.id;");
$stmt->execute([$taskId]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function getTaskCompleterName($taskId){
global $conn;
$stmt = $conn->prepare("SELECT name FROM user_table, task WHERE task.id = ? AND task.completer_id = user_table.id;");
$stmt->execute([$taskId]);
return $stmt->fetchAll();
}
function getProjectMembersNames($project){
global $conn;
$stmt = $conn->prepare('SELECT user_table.name, user_table.id FROM user_project, user_table WHERE id_project=? AND user_table.id=user_project.id_user');
$stmt->execute([$project]);
return $stmt->fetchAll();
}
function setTaskAssigned($assignedId, $taskId){
global $conn;
$stmt = $conn->prepare('UPDATE task SET assigned_id = ? WHERE id=?;');
$stmt->execute([$assignedId,$taskId]);
}
function setTaskName($name, $taskId){
global $conn;
$stmt = $conn->prepare('UPDATE task SET name = ? WHERE id=?;');
$stmt->execute([$name,$taskId]);
}
|
{
"content_hash": "f7f7c63002049929f95cb1d0a3298bf0",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 200,
"avg_line_length": 32.403669724770644,
"alnum_prop": 0.5849377123442808,
"repo_name": "pedro-c/FEUP-LBAW",
"id": "c42b62748e9eaeac83267c3305d1f7538eee2171",
"size": "3532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "proto/database/tasks.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "176"
},
{
"name": "CSS",
"bytes": "589625"
},
{
"name": "HTML",
"bytes": "1179"
},
{
"name": "JavaScript",
"bytes": "861306"
},
{
"name": "PHP",
"bytes": "2118139"
},
{
"name": "PLpgSQL",
"bytes": "474138"
},
{
"name": "Smarty",
"bytes": "149236"
}
],
"symlink_target": ""
}
|
<!--
Copyright 2019 Google LLC
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
https://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.
-->
<SharedFlowBundle revision="1" name="cors-v1"/>
|
{
"content_hash": "717041a44af2375d692df75b159aa20b",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 80,
"avg_line_length": 74.52941176470588,
"alnum_prop": 0.3741120757695343,
"repo_name": "apigee/devrel",
"id": "61086899997e7e14800633d3bb1d88fc158a185d",
"size": "1267",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "references/common-shared-flows/cors-v1/sharedflowbundle/cors-v1.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "7447"
},
{
"name": "Gherkin",
"bytes": "71235"
},
{
"name": "HTML",
"bytes": "2830"
},
{
"name": "Handlebars",
"bytes": "1170"
},
{
"name": "Java",
"bytes": "4006"
},
{
"name": "JavaScript",
"bytes": "151777"
},
{
"name": "Shell",
"bytes": "327555"
},
{
"name": "XSLT",
"bytes": "11610"
}
],
"symlink_target": ""
}
|
import PropTypes from 'prop-types';
import React, { Children, PureComponent } from 'react';
import { arrayMove, SortableHandle } from 'react-sortable-hoc';
import SortableTableBodyInternal from './SortableTableBodyInternal';
/**
* Replaces `TableBody` with a sortable table body, (Also can be defined as `TableBody.Sortable`).
* Allows for drag and drop sorting of the table. It will use its children as the sortable
* items (`TableRow`) and the order is determined by the order of the children. You will need to
* provide a `onSortEnd({ newIndex, oldIndex})` function that you can use to change the order of
* the children. You can also use the `SortableTableBody.arrayMove(array, oldIndex, newIndex)`
* function to reorder the array of data.
*
* By default, the entire table row will be draggable. You can disable this with the
* `useDragHandle` option and then providing a sort handle (`SortableTableItemHandle` -
* also `TableItem.SortHandle`). You can define a custom sort handle by using the
* `SortableTableBody.createSortHandle`.
* Example:
* ```js
* const Handle = SortableTableBody.createSortHandle(props => (<div>Sort</div>));
* ```
*/
export default class SortableTableBody extends PureComponent {
static propTypes = {
/** Disable the drag sort ability */
disabled: PropTypes.bool,
/** The table rows */
children: PropTypes.node.isRequired,
/** On drag/sort end. returns old and new index for changing the order with. */
onSortEnd: PropTypes.func,
/** On drag/sort start */
onSortStart: PropTypes.func,
/** The class added to the body while sorting, useful to disable user-select */
sortingBodyClassName: PropTypes.string,
/** The classname of the React Portal created for the floating sort item */
sortingPortalClassName: PropTypes.string,
/** Locks which axis the row can move */
lockAxis: PropTypes.oneOf(['x', 'y', 'xy']),
/** Locks the floating sort item to the table container */
lockToContainerEdges: PropTypes.bool,
/** Use a handle like SortableTableItemHandle instead of dragging the entire row */
useDragHandle: PropTypes.bool,
/** Optional additional class names to apply at the table body level */
className: PropTypes.string,
/** Optional styles */
style: PropTypes.shape({}),
}
static defaultProps = {
disabled: false,
onSortEnd: () => {},
onSortStart: () => {},
sortingBodyClassName: 'table-v2-sorting',
sortingPortalClassName: '',
lockAxis: 'y',
lockToContainerEdges: true,
useDragHandle: false,
className: null,
style: null,
}
/**
* Move an item from oldIndex to newIndex
* arrayMove(array, oldIndex, newIndex)
*/
static arrayMove = arrayMove;
static createSortHandle = SortableHandle;
constructor(props) {
super(props);
this.state = {
items: Children.toArray(this.props.children),
};
this.onSortEnd = this.onSortEnd.bind(this);
this.onSortStart = this.onSortStart.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
items: Children.toArray(nextProps.children),
});
}
onSortEnd(attrs) {
document.body.classList.remove(this.props.sortingBodyClassName);
this.props.onSortEnd(attrs);
}
onSortStart(attrs) {
document.body.classList.add(this.props.sortingBodyClassName);
this.props.onSortStart(attrs);
}
render() {
return (
<SortableTableBodyInternal
tableBodyClassName={this.props.className}
tableBodyStyle={this.props.style}
helperClass={this.props.sortingPortalClassName}
useDragHandle={this.props.useDragHandle}
lockToContainerEdges={this.props.lockToContainerEdges}
lockAxis={this.props.lockAxis}
items={this.state.items}
onSortEnd={this.onSortEnd}
onSortStart={this.onSortStart}
disabled={this.props.disabled}
/>
);
}
}
|
{
"content_hash": "f48a827dd247b1414baea3a11640e15d",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 99,
"avg_line_length": 35.0625,
"alnum_prop": 0.6939139292080468,
"repo_name": "HarvestProfit/harvest-profit-ui",
"id": "7ff01e7a08936b9f2c7f2cfaa08f80047c0d03bc",
"size": "3927",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/table/SortableTableBody.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "157718"
},
{
"name": "SCSS",
"bytes": "30626"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<role><name>ROLE_HPC_ADMIN</name><externallyDefined>false</externallyDefined></role>
|
{
"content_hash": "901fc710f7a42bd3d6678bab46afc2b1",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 84,
"avg_line_length": 61.5,
"alnum_prop": 0.7398373983739838,
"repo_name": "ernestoongaro/jrs-extra-samples",
"id": "96a7820f14122501cc12d2332c418125aebfad4a",
"size": "123",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "HighPerformanceCars/repository/roles/ROLE_HPC_ADMIN.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "386880"
},
{
"name": "HTML",
"bytes": "57703"
},
{
"name": "Java",
"bytes": "22592"
},
{
"name": "JavaScript",
"bytes": "54996"
},
{
"name": "PHP",
"bytes": "755"
},
{
"name": "SQLPL",
"bytes": "729950"
},
{
"name": "Shell",
"bytes": "25116"
}
],
"symlink_target": ""
}
|
using KernowCode.KTest.Logging;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
namespace KernowCode.KTest.Ubaddas
{
/// <summary>
/// <para>Enables a test class to use the UBADDAS test syntax</para>
/// <para>An Enum representing the User Stories business values must be supplied</para>
/// <para></para>
/// </summary>
/// <typeparam name="TBusinessValueEnum"></typeparam>
public class StoryFeatureBase<TBusinessValueEnum>
{
/// <summary>
/// <para>Gets the name of the target application layer to test against.</para>
/// <para>Override this in your test or base test feature class</para>
/// <para>Returning null will result in using the root Persona class in the Personas namespace</para>
/// </summary>
/// <returns>Persona namespace indicating the application layer. i.e. 'Presentation' which will translate to the namespace yourProject.Personas.Presentation.thePersona class</returns>
protected virtual string ApplicationLayer()
{
return null;
}
/// <summary>
/// <para>Initial method to start new User Story and BDD syntax.</para>
/// <para>Uses test method name as the 'I Want' part of the User Story syntax.</para>
/// <para>Follow this 'SoThat' with the 'As' to specify the 'As A' part of the User Story syntax.</para>
/// </summary>
/// <param name="businessValue">Supply an enumerator that describes the business values for the User Stories</param>
/// <returns>Fluent interface providing BDD Given, When, Then syntax</returns>
protected IBase SoThat(TBusinessValueEnum businessValue)
{
var loggerFactory = LoggerFactory ?? ConfigureDefaultLoggersFactory;
var loggers = new Loggers();
loggers.AddRange(loggerFactory());
loggers.SetStartTextsToEmphasise("I want", "So that", "As", "Given", "When", "Then", "And");
return Behaviour.SoThat(businessValue.ToString(), ApplicationLayer(), null, loggers);
}
private List<ILogger> ConfigureDefaultLoggersFactory()
{
var loggers = new List<ILogger>();
loggers.Add(new ConsoleLogger(new ConsoleStringLoggerEntry(), Behaviour.LeftSectionPadding));
return loggers;
}
/// <summary>
/// <para>Create a new test output file path based on test method name located at executing assembly TestOutput folder</para>
/// <para>i.e. .../bin/Debug/kTestOutput/MyTest.html</para>
/// </summary>
/// <param name="extension">file extension to append to filename</param>
/// <returns>filepath</returns>
public static string GetTestOutputFilePath(string extension)
{
string timeStamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssffff");
return Behaviour.GetTestFilename(@"{1}\kTestOutput\{0}.{2}.{3}", GetSourceDirectory(), timeStamp, extension);
}
private static string GetSourceDirectory()
{
var uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
var path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
/// <summary>
/// Allows you to specify the test output loggers
/// </summary>
protected Func<List<ILogger>> LoggerFactory { get; set; }
}
}
|
{
"content_hash": "9750bde4d34f37c664c665049c6bd69d",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 191,
"avg_line_length": 47.12,
"alnum_prop": 0.631578947368421,
"repo_name": "KernowCode/UBADDAS",
"id": "83f85dccb8c3b5e6ad157943902ede4daad3e258",
"size": "3536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "KernowCode.KTest.Ubaddas/StoryFeatureBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "86676"
}
],
"symlink_target": ""
}
|
class MarkdAsDriverException(Exception):
"""
Wrap any error as DriverException
"""
def __init__(self, wrapped_exc):
super().__init__()
self.wrapped_exc = wrapped_exc
|
{
"content_hash": "7b445c343791c15b92a591cd7d1de676",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 40,
"avg_line_length": 28.285714285714285,
"alnum_prop": 0.601010101010101,
"repo_name": "neo4j/neo4j-python-driver",
"id": "042eab8c02dda052664bed07917dfe260864c4cf",
"size": "841",
"binary": false,
"copies": "1",
"ref": "refs/heads/5.0",
"path": "testkitbackend/exceptions.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2068"
},
{
"name": "Python",
"bytes": "1654566"
},
{
"name": "Shell",
"bytes": "4165"
}
],
"symlink_target": ""
}
|
Meteor.startup(function() {
RocketChat.ChannelSettings.addOption({
group: ['room'],
id: 'tokenpass',
template: 'channelSettings__tokenpass',
validation(data) {
if (data && data.rid) {
const room = RocketChat.models.Rooms.findOne(data.rid, { fields: { tokenpass: 1 } });
return room && room.tokenpass;
}
return false;
}
});
});
|
{
"content_hash": "9fcc3f685b8bb4ef43ed716598a3c8f5",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 89,
"avg_line_length": 22.375,
"alnum_prop": 0.6368715083798883,
"repo_name": "nishimaki10/Rocket.Chat",
"id": "635202a0f507917bb3359b0e888af5686aa62e21",
"size": "358",
"binary": false,
"copies": "6",
"ref": "refs/heads/develop",
"path": "packages/rocketchat-tokenpass/client/startup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "549"
},
{
"name": "CSS",
"bytes": "370160"
},
{
"name": "Cap'n Proto",
"bytes": "3959"
},
{
"name": "HTML",
"bytes": "369942"
},
{
"name": "JavaScript",
"bytes": "3515420"
},
{
"name": "Ruby",
"bytes": "4237"
},
{
"name": "Shell",
"bytes": "21286"
},
{
"name": "Standard ML",
"bytes": "1843"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>streams: 16 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.0 / streams - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
streams
<small>
8.10.0
<span class="label label-success">16 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-17 05:01:29 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-17 05:01:29 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.10.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/streams"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Streams"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: Streams"
"keyword: Eratosthene Sieve"
"keyword: prime numbers"
"keyword: number theory"
"keyword: primality"
"category: Mathematics/Arithmetic and Number Theory/Number theory"
]
authors: [
"François Leclerc, Christine Paulin-Mohring"
]
bug-reports: "https://github.com/coq-contribs/streams/issues"
dev-repo: "git+https://github.com/coq-contribs/streams.git"
synopsis: "Specification of Eratosthene Sieve"
description: """
Proof of Eratosthene Sieve formalised using streams
encoded as greatest fixpoints. See paper:
@InProceedings{LePa94,
author = "F. Leclerc and C. Paulin-Mohring",
title = "Programming with Streams in {Coq}. A case study : The Sieve of Eratosthenes",
editor = "H. Barendregt and T. Nipkow",
volume = 806,
series = "LNCS",
booktitle = "{Types for Proofs and Programs, Types' 93}",
year = 1994,
publisher = "Springer-Verlag"
}"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/streams/archive/v8.10.0.tar.gz"
checksum: "md5=f9db2a9ae41623c70c7c0d889833ca75"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-streams.8.10.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-streams.8.10.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>12 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-streams.8.10.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>16 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 172 K</p>
<ul>
<li>57 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Streams/GfpStreams.vo</code></li>
<li>39 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Streams/GfpStreams.glob</code></li>
<li>38 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Streams/Eratosthene.vo</code></li>
<li>17 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Streams/Eratosthene.glob</code></li>
<li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Streams/GfpStreams.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Streams/Eratosthene.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-streams.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
{
"content_hash": "e1ab6134ab93dd5569458256dd4d465e",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 159,
"avg_line_length": 42.90163934426229,
"alnum_prop": 0.5516494714049166,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "c273776fd27c96da6f42ab637945641cff7695a7",
"size": "7877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.10.0/streams/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" <?php language_attributes(); ?>> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" <?php language_attributes(); ?>> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" <?php language_attributes(); ?>> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" <?php language_attributes(); ?>> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title><?php wp_title('|', true, 'right'); bloginfo('name'); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="<?php echo get_template_directory_uri(); ?>/assets/js/vendor/modernizr-2.6.2.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,400,200,700' rel='stylesheet' type='text/css'>
<script src="<?php echo get_template_directory_uri(); ?>/assets/js/vendor/bootstrap.js"></script>
<script>window.jQuery || document.write('<script src="<?php echo get_template_directory_uri(); ?>/assets/js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
<?php wp_head(); ?>
<?php if (is_page_template('map-scores-tool-template.php')){
echo "<script type='text/javascript' src=" . "/assets/js/map-tool.js></script>";
}?>
<?php if (have_posts()) : ?>
<link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name') ?> Feed" href="<?php echo home_url() ?>/feed/">
<?php endif; ?>
</head>
|
{
"content_hash": "9dcb3b0f9c072416afd52b36b86d1a40",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 159,
"avg_line_length": 61.48,
"alnum_prop": 0.6206896551724138,
"repo_name": "dalanmiller/seatgroup-theme",
"id": "cb5b2c0a3800429c06f1f41d498aea869d7a1e72",
"size": "1537",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/head.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "25809"
},
{
"name": "PHP",
"bytes": "89460"
},
{
"name": "Perl",
"bytes": "21825"
},
{
"name": "Shell",
"bytes": "578"
}
],
"symlink_target": ""
}
|
import java.awt.Point;
/**
* This class represent the board game. It construct and initialize all the
* rooms in the board.
*
* @author sam
*
*/
public class Board {
/**
* room: array of rooms within the maps
* totalQP: sum of all player Quality Points. Once it reach a certain limits
* , year of player go up (eg. freshmen to sophomore)
*/
private Room[] room = new Room[21];
private int totalQP;
/**
* constructor: create and initialize all the rooms
*/
public Board() {
int[] connectToRoom0 = {1, 3, 4, 5};
int[] connectToRoom1 = {0, 2, 3};
int[] connectToRoom2 = {1, 3, 5, 6};
int[] connectToRoom3 = {0, 1, 2, 5};
int[] connectToRoom4 = {0, 5, 7, 12};
int[] connectToRoom5 = {0, 2, 3, 4, 6};
int[] connectToRoom6 = {2, 5, 10};
int[] connectToRoom7 = {4, 8};
int[] connectToRoom8 = {7, 9, 16};
int[] connectToRoom9 = {8, 10};
int[] connectToRoom10 = {6, 9, 15};
int[] connectToRoom11 = {12};
int[] connectToRoom12 = {4, 11, 13, 14, 15, 16};
int[] connectToRoom13 = {12};
int[] connectToRoom14 = {12, 15};
int[] connectToRoom15 = {10, 12, 14, 17, 18, 19, 20};
int[] connectToRoom16 = {8, 12};
int[] connectToRoom17 = {15};
int[] connectToRoom18 = {15};
int[] connectToRoom19 = {15};
int[] connectToRoom20 = {15};
room[0] = new Room(connectToRoom0, "George Allen Field", 0, 72, 148);
room[1] = new Room(connectToRoom1, "Japanese Garden", 1, 432, 40);
room[2] = new Room(connectToRoom2, "Student Parking", 2, 1023, 78);
room[3] = new Room(connectToRoom3, "The Pyramid", 3, 420, 274);
room[4] = new Room(connectToRoom4, "West Walkway", 4, 38, 663);
room[5] = new Room(connectToRoom5, "Recreation Center", 5, 440, 560);
room[6] = new Room(connectToRoom6, "Forbidden Parking", 6, 1116, 587);
room[7] = new Room(connectToRoom7, "library", 7, 20, 1707);
room[8] = new Room(connectToRoom8, "Union - LA 5", 8, 512, 1707);
room[9] = new Room(connectToRoom9, "Brotman Hall", 9, 1151, 1707);
room[10] = new Room(connectToRoom10, "East Walkway", 10, 1462, 989);
room[11] = new Room(connectToRoom11, "Computer Lab", 11, 170, 885);
room[12] = new Room(connectToRoom12, "North Hall", 12, 170, 1147);
room[13] = new Room(connectToRoom13, "Room of Retirement", 13, 170, 1349);
room[14] = new Room(connectToRoom14, "ECS 302", 14, 602, 885);
room[15] = new Room(connectToRoom15, "South Hall", 15, 843, 1147);
room[16] = new Room(connectToRoom16, "Elevators", 16, 605, 1349);
room[17] = new Room(connectToRoom17, "ECS 308", 17, 811, 1349);
room[18] = new Room(connectToRoom18, "EAT Club", 18, 1029, 885);
room[19] = new Room(connectToRoom19, "CECS Conference Room", 19, 1245, 885);
room[20] = new Room(connectToRoom20, "Lactation Lounge", 20, 1213, 1349);
}
/**
* get list of room that connected to i
*
* @param i number of the room to retrieve list of connected rooms from
* @return int array of connected room from the param
*/
public int[] getConnectedRoom(int i) {
return room[i].getConnectedRoom();
}
/**
* get name of the room i
*
* @param i number of room to get the name from
* @return name string of the room
*/
public String getName(int i) {
return room[i].getName();
}
/**
* get location number of room i relative the whole map
*
* @param i number of room to get location from
* @return int location of the room
*/
public int getLoc(int i) {
return room[i].getLoc();
}
/**
* get pixel position of where the room i is. This is also where we print
* token of players on the board
*
* @param i number of room to get pixel position from
* @return a Point object of where approximately the room is.
*/
public Point getPos(int i) {
return room[i].getPos();
}
}
|
{
"content_hash": "8bc8669376239d5e773e5b6281d6d773",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 78,
"avg_line_length": 34.10909090909091,
"alnum_prop": 0.6420575692963753,
"repo_name": "sopanhavuth-aka-sam/cecs343-project",
"id": "75e0caea6fb7b635b07f58dd604d247a59de115a",
"size": "3752",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "GUI/src/Board.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "Java",
"bytes": "187401"
},
{
"name": "JavaScript",
"bytes": "238700"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8" ?>
<documentation for="TbRedactorJs"
punchline="Powerful and famous WYSIWYG editor at no cost for Yii developers">
<section named="Description">
<p>This is the wrapper around the <a href="http://imperavi.com/redactor/">Redactor</a>.</p>
<p label="important">
This library is <em>NOT</em> free to use. Community license for it was generously bought by the Yii community
and so you can use this widget legally in Yii-based projects ONLY.
</p>
<p>Basic example of usage is this:</p>
<example name="basic" />
<p label="important">
Please note that the <pn>name</pn> is set to "content", which is required for Redactor plugin to fetch the original data from input
and paste it into its editor view.
If you do not set "name" or set it to any other value, the value of <pn>value</pn> property of this widget
will be completely ignored!
</p>
<p label="important">
In addition to previous note, if you have several Redactor instances on the same page, you must use the <pn>htmlOptions</pn>
property to set the HTML ID of each Redactor instance to different values.
</p>
</section>
<section named="Widget Configuration">
<p>Here's all configuration properties which you can set for <wn>TbCKEditor</wn>.</p>
<p>Most of them are common to all form input widgets.</p>
<properties>
<property name="model" type="CModel" default="null">
<p>
The data model associated with this widget.
See <yiidoc>CInputWidget.model</yiidoc>.
Either this property along with <pn>attribute</pn> should be defined, or the <pn>name</pn>.
</p>
</property>
<property name="attribute" type="string" default="null">
<p>
If you set the <pn>model</pn> attribute,
here you have to specify the name of the model property which you want to change with this widget.
See <yiidoc>CInputWidget.attribute</yiidoc>.
Either this property along with <pn>model</pn> should be defined, or the <pn>name</pn>.
</p>
</property>
<property name="name" type="string" default="null">
<p>
The value of <pn>name</pn> HTML attribute of the input element.
It must be set if you did not provide value for <pn>model</pn>.
See <yiidoc>CInputWidget.name</yiidoc>.
Either this property should be defined, or the <pn>model</pn> together with <pn>attribute</pn>.
</p>
</property>
<property name="value" type="string" default="null">
<p>
Here you can force the initial value of the input.
If <pn>model</pn> is provided, by default model's value is used.
See <yiidoc>CInputWidget.value</yiidoc>.
</p>
</property>
<property name="htmlOptions" type="array" default="array()">
<p>
HTML attributes of the input tag itself.
Please note that it is <em>not</em> the attributes of a wrapper tag around the input.
See <yiidoc>CInputWidget.htmlOptions</yiidoc>.
</p>
</property>
<property name="editorOptions" type="array" default="array()">
<p>
Options for the original library.
This value will be JSON-encoded and fed to <ln>CKEditor</ln>.
See the <a href="http://docs.ckeditor.com/">library documentation</a> for list of all possible options.
</p>
</property>
</properties>
</section>
<section named="Examples of Usage">
<subheader>With language and plugins set</subheader>
<example name="with_lang_and_plugins" />
<subheader>How to pass callbacks to Redactor</subheader>
<example name="callbacks_passing" />
</section>
</documentation>
|
{
"content_hash": "505f27adec600d1b8c67ffd6c0c40c03",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 143,
"avg_line_length": 47.79347826086956,
"alnum_prop": 0.55424152831476,
"repo_name": "OscarMesa/creditos",
"id": "124ccebede9160a9e4ef8e7eb8bbb04d558a8bbd",
"size": "4397",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protected/extensions/bootstrap/userdoc/redactorjs/redactorjs.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "463"
},
{
"name": "CSS",
"bytes": "539670"
},
{
"name": "HTML",
"bytes": "3934334"
},
{
"name": "JavaScript",
"bytes": "3466348"
},
{
"name": "PHP",
"bytes": "1657039"
},
{
"name": "Shell",
"bytes": "2534"
},
{
"name": "XSLT",
"bytes": "6325"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>DreamFactory™</title>
<meta name="page-route" content="web/index" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="author" content="DreamFactory Software, Inc.">
<meta name="language" content="en" />
<link rel="shortcut icon" href="/img/df-icon-256x256.png" />
<!-- Bootstrap 3 CSS -->
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<!-- DSP UI Styles & Code -->
<link rel="stylesheet" href="/css/df.main.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid df-navbar">
<div class="navbar-header">
<div class="pull-left df-logo"><img src="/img/logo-navbar-194x42.png"></div>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav">
<span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span
class="icon-bar"></span> <span class="icon-bar"></span>
</button>
</div>
<div id="navbar-container"></div>
</div>
</div>
<div id="page-content">
<div class="container-fluid container-inner">
<div class="alert center">
<div id="loadingFrame" class="alert center alert-warning" style="margin-top:40px; width: 500px">
<span style="font-size: 18pt;: center">Hello and Welcome to DreamFactory 2.0!</span><br><br>
<div id="loadingMsg" style="display: none;">
You will be up and ready in just few seconds.
Please wait while we setup and configure your DreamFactory instance.
<br>
<br>
<i>Please do not hit the back or refresh button while you wait here!</i>
<br><hr>
</div>
</div>
<div id="errorFrame" class="alert center alert-danger" style="margin-top:40px; width: 800px; display: none">
<span style="font-size: 14pt;">Installation failed. Please run the migration and seeder manually.</span><hr>
<div id="errorMsg"></div>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div class="container-fluid">
<span class="pull-left dsp-footer-copyright">
<p class="footer-text">© <a target="_blank" href="https://www.dreamfactory.com">DreamFactory Software, Inc.</a> 2015-<?php echo date(
'Y'
); ?>. All Rights Reserved.
</p>
</span> <span class="pull-right dsp-footer-version"><p class="footer-text">
<a href="https://github.com/dreamfactorysoftware/dsp-core/"
target="_blank">v{{$version}}</a>
</p></span>
</div>
</div>
<!-- Scripts -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
setTimeout(function(){
$.ajax({
url: '/setup_db',
async: true,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
cache: false,
processData: false,
//data: JSON.stringify(data),
beforeSend: function (xhr) {
$('#loadingMsg').slideDown();
},
success: function (json) {
if(json.success){
location.href=json.redirect_path;
} else {
$('#loadingFrame').slideUp();
$('#errorMsg').html(json.message);
$('#errorFrame').slideDown();
console.log(json)
}
},
error: function (err) {
$('#loadingFrame').slideUp();
$('#errorMsg').html(err.responseText);
$('#errorFrame').slideDown();
console.log(err)
}
});
}, 2000);
</script>
</body>
</html>
|
{
"content_hash": "b0138280a9ad14a548c475e4b6bfa139",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 150,
"avg_line_length": 37.6,
"alnum_prop": 0.5356826241134752,
"repo_name": "merhawifissehaye/dreamfactory-configured",
"id": "34793da101e4bec4b26700244d99dc5b562d3c32",
"size": "4512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/views/setup.blade.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "48778"
},
{
"name": "CSS",
"bytes": "315444"
},
{
"name": "HTML",
"bytes": "640557"
},
{
"name": "JavaScript",
"bytes": "1691689"
},
{
"name": "Nginx",
"bytes": "5552"
},
{
"name": "PHP",
"bytes": "175663"
},
{
"name": "Ruby",
"bytes": "887"
}
],
"symlink_target": ""
}
|
class RegExp
{
public:
RegExp( const char* expression, int options = 0 );
~RegExp( void );
bool Index( const char* subject, size_t* start, size_t* len );
const char* Match( const char* subject );
bool IsValidRE( void ) const;
public:
const char* pszError;
int errorOffset;
private:
char* pszMatch_;
pcre* ppcreCode_;
int pcreOptions_;
int pcreRc_;
};
//===========================================================================//
// Function inline defintions
//===========================================================================//
inline bool RegExp::IsValidRE( void ) const
{
return( ( ppcreCode_ != NULL ) ? true : false );
}
#endif
|
{
"content_hash": "2a395804c18332fdd7c365dbaf651c9b",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 79,
"avg_line_length": 21.147058823529413,
"alnum_prop": 0.47426981919332406,
"repo_name": "UGent-HES/ConnectionRouter",
"id": "ebae5d09215e2a185ef11ddca85621118b333fa2",
"size": "2032",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "printhandler/SRC/TC_Common/RegExp.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "19785938"
},
{
"name": "C++",
"bytes": "1520270"
},
{
"name": "CSS",
"bytes": "3181"
},
{
"name": "Coq",
"bytes": "18542"
},
{
"name": "HTML",
"bytes": "6400"
},
{
"name": "JavaScript",
"bytes": "59070"
},
{
"name": "Lex",
"bytes": "10434"
},
{
"name": "Makefile",
"bytes": "31309"
},
{
"name": "Objective-C",
"bytes": "5053"
},
{
"name": "Perl",
"bytes": "468062"
},
{
"name": "Perl6",
"bytes": "40822"
},
{
"name": "Python",
"bytes": "210880"
},
{
"name": "QMake",
"bytes": "4839"
},
{
"name": "Shell",
"bytes": "44904"
},
{
"name": "SourcePawn",
"bytes": "3275"
},
{
"name": "Verilog",
"bytes": "10339275"
},
{
"name": "Yacc",
"bytes": "31188"
}
],
"symlink_target": ""
}
|
dojo.addOnLoad(function(){
doh.register("dojox.mobile.test.doh.ListItem", [
{
name: "ListItem Verification",
timeout: 4000,
runTest: function(){
var d = new doh.Deferred();
setTimeout(d.getTestCallback(function(){
verifyListItem("dojox_mobile_ListItem_0", 'External View #1 (sync)', '', "mblDomButtonArrow", true, true, false, false, /i-icon-1.png/i);
verifyListItem("dojox_mobile_ListItem_1", 'External View #2 (async)', '', "mblDomButtonArrow", true, true, false);
verifyListItem("dojox_mobile_ListItem_2", 'External View #3 (sync)', '', "mblDomButtonArrow", true, true, false);
verifyListItem("dojox_mobile_ListItem_3", 'Video', 'Off', "", false, false, false);
verifyListItem("dojox_mobile_ListItem_4", 'Maps', 'VPN', "", true, false, false);
verifyListItem("dojox_mobile_ListItem_5", 'Jack Coleman', '', "", false, false, false);
verifyListItem("dojox_mobile_ListItem_6", 'Sounds', '', "mblDomButtonArrow", true, true, false);
verifyListItem("dojox_mobile_ListItem_7", 'Brightness', '', "mblDomButtonArrow", true, true, false);
verifyListItem("dojox_mobile_ListItem_8", 'Wallpaper', '', "mblDomButtonArrow", true, true, false);
verifyListItem("dojox_mobile_ListItem_9", 'XX Widget', '', "mblDomButtonBluePlus", true, true, false);
verifyListItem("dojox_mobile_ListItem_10", 'YY Widget', '', "mblDomButtonRedMinus", true, true, false);
var txt = 'See location in applications (such as Maps) using wireless networks';
verifyListItem("dojox_mobile_ListItem_11", txt, '', "mblDomButtonCheckboxOff", false, true, false, true);
txt = 'When locating, accurate to street level (uncheck to conserve battery)';
verifyListItem("dojox_mobile_ListItem_12", txt, '', "mblDomButtonCheckboxOn", false, true, false, true);
verifyListItem("dojox_mobile_ListItem_13", 'Set unlock pattern', '', "", false, false, false);
}));
return d;
}
},
{
name: "ListItem set",
timeout: 1000,
runTest: function(){
var demoWidget = dijit.byId("dojox_mobile_ListItem_0");
demoWidget.set({transition :"flip", url:"../view2.html", noArrow:true, selected:true, anchorLabel:true, rightText:"Value Changed"});
doh.assertEqual("flip", demoWidget.get("transition"));
doh.assertEqual("../view2.html", demoWidget.get("url"));
doh.assertTrue(demoWidget.get("noArrow"), 'get("noArrow")');
doh.assertTrue(demoWidget.get("selected"), 'get("selected")');
doh.assertTrue(demoWidget.get("anchorLabel"), 'get("anchorLabel")');
doh.assertEqual("Value Changed", demoWidget.get("rightText"));
verifyListItem("dojox_mobile_ListItem_0", 'External View #1 (sync)', 'Value Changed', "mblDomButtonArrow", true, true, false, false, null, true);
}
},
{
name: "ListItem set",
timeout: 1000,
runTest: function(){
var demoWidget = dijit.byId("dojox_mobile_ListItem_1");
demoWidget.set({icon :"../images/i-icon-4.png", label:"Value Changed", clickable:true, url:"../view3.html", transition :"slide", transitionDir:-1, sync:false, toggle:true, _duration:1600});
doh.assertEqual("slide", demoWidget.get("transition"));
doh.assertEqual("../view3.html", demoWidget.get("url"));
doh.assertEqual(-1, demoWidget.get("transitionDir"));
doh.assertTrue(demoWidget.get("clickable"), 'get("clickable")');
doh.assertFalse(demoWidget.get("sync"), 'get("sync")');
doh.assertTrue(demoWidget.get("toggle"), 'get("toggle")');
doh.assertEqual(1600, demoWidget.get("_duration"));
doh.assertEqual("Value Changed", demoWidget.get("label"));
verifyListItem("dojox_mobile_ListItem_1", 'Value Changed', '', "mblDomButtonArrow", true, true, false, false, /i-icon-4.png/i);
}
},
{
name: "ListItem set",
timeout: 1000,
runTest: function(){
var demoWidget = dijit.byId("dojox_mobile_ListItem_6");
demoWidget.set({iconPos :"0,116,29,29", moveTo:"bar", transition :"fade"});
doh.assertEqual("bar", demoWidget.get("moveTo"));
doh.assertEqual("0,116,29,29", demoWidget.get("iconPos"));
doh.assertEqual("fade", demoWidget.get("transition"));
verifyListItem("dojox_mobile_ListItem_6", 'Sounds', '', "mblDomButtonArrow", true, true, false, false, /i-icon-all.png/i, false, true);
}
},
{
//Todo
name: "ListItem set",
timeout: 1000,
runTest: function(){
var demoWidget = dijit.byId("dojox_mobile_ListItem_6");
demoWidget.set({href :"", hrefTarget:""});
doh.assertEqual("", demoWidget.get("href"));
doh.assertEqual("", demoWidget.get("hrefTarget"));
}
},
{
name: "ListItem set",
timeout: 1000,
runTest: function(){
var demoWidget = dijit.byId("dojox_mobile_ListItem_9");
demoWidget.set({rightIcon:"mblDomButtonRedMinus"});
verifyListItem("dojox_mobile_ListItem_9", 'XX Widget', '', "mblDomButtonRedMinus", true, true, false);
// doh.assertEqual("mblDomButtonRedMinus", demoWidget.get("icon"));
}
},
{
name: "ListItem set",
timeout: 1000,
runTest: function(){
var demoWidget = dijit.byId("dojox_mobile_ListItem_11");
demoWidget.set({rightIcon:"mblDomButtonCheckboxOn"});
var txt = 'See location in applications (such as Maps) using wireless networks';
verifyListItem("dojox_mobile_ListItem_11", txt, '', "mblDomButtonCheckboxOn", false, true, false, true);
// doh.assertEqual("mblDomButtonCheckboxOn", demoWidget.get("icon"));
}
}
]);
doh.run();
});
|
{
"content_hash": "514b26ccc0cf9558ae4f8e862ae28d38",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 193,
"avg_line_length": 45.73109243697479,
"alnum_prop": 0.6639103270856302,
"repo_name": "synico/springframework",
"id": "71820d14fb8975f64d8bc95fa41119beb2a9206e",
"size": "5442",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lobtool/src/main/webapp/resources/javascript/dojox/mobile/tests/doh/ListItem.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
import string
def sanitiseLine(line):
if line[-1:] == '\n': line = line[:-1]
if string.find(line, "##") != -1:
line = line[:string.find(line, "##")]
line = string.strip(line)
return line
def decodeFunction(featureVal):
retType, rest = string.split(featureVal, " ", 1)
nameIdent, params = string.split(rest, "(")
name, value = string.split(nameIdent, "=")
params, rest = string.split(params, ")")
param1, param2 = string.split(params, ",")[0:2]
return retType, name, value, param1, param2
def decodeEvent(featureVal):
retType, rest = string.split(featureVal, " ", 1)
nameIdent, params = string.split(rest, "(")
name, value = string.split(nameIdent, "=")
return retType, name, value
def decodeParam(p):
param = string.strip(p)
type = ""
name = ""
value = ""
if " " in param:
type, nv = string.split(param, " ")
if "=" in nv:
name, value = string.split(nv, "=")
else:
name = nv
return type, name, value
class Face:
def __init__(self):
self.order = []
self.features = {}
self.values = {}
self.events = {}
def ReadFromFile(self, name):
currentCategory = ""
currentComment = []
currentCommentFinished = 0
file = open(name)
for line in file.readlines():
line = sanitiseLine(line)
if line:
if line[0] == "#":
if line[1] == " ":
if currentCommentFinished:
currentComment = []
currentCommentFinished = 0
currentComment.append(line[2:])
else:
currentCommentFinished = 1
featureType, featureVal = string.split(line, " ", 1)
if featureType in ["fun", "get", "set"]:
retType, name, value, param1, param2 = decodeFunction(featureVal)
p1 = decodeParam(param1)
p2 = decodeParam(param2)
self.features[name] = {
"FeatureType": featureType,
"ReturnType": retType,
"Value": value,
"Param1Type": p1[0], "Param1Name": p1[1], "Param1Value": p1[2],
"Param2Type": p2[0], "Param2Name": p2[1], "Param2Value": p2[2],
"Category": currentCategory, "Comment": currentComment
}
if self.values.has_key(value):
raise "Duplicate value " + value + " " + name
self.values[value] = 1
self.order.append(name)
elif featureType == "evt":
retType, name, value = decodeEvent(featureVal)
self.features[name] = {
"FeatureType": featureType,
"ReturnType": retType,
"Value": value,
"Category": currentCategory, "Comment": currentComment
}
if self.events.has_key(value):
raise "Duplicate event " + value + " " + name
self.events[value] = 1
self.order.append(name)
elif featureType == "cat":
currentCategory = featureVal
elif featureType == "val":
name, value = string.split(featureVal, "=", 1)
self.features[name] = {
"FeatureType": featureType,
"Category": currentCategory,
"Value": value }
self.order.append(name)
elif featureType == "enu" or featureType == "lex":
name, value = string.split(featureVal, "=", 1)
self.features[name] = {
"FeatureType": featureType,
"Category": currentCategory,
"Value": value }
self.order.append(name)
|
{
"content_hash": "be3ada268d7393478c2b7352b545b044",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 71,
"avg_line_length": 31.17924528301887,
"alnum_prop": 0.5851739788199698,
"repo_name": "segafan/wme1_jankavan_tlc_edition-repo",
"id": "59ada3dce3dcc18462df9529f3866d68f90ab3a8",
"size": "3360",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/scite/scintilla/include/Face.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "91920"
},
{
"name": "Assembly",
"bytes": "154110"
},
{
"name": "Batchfile",
"bytes": "23640"
},
{
"name": "C",
"bytes": "8163065"
},
{
"name": "C#",
"bytes": "927846"
},
{
"name": "C++",
"bytes": "8758239"
},
{
"name": "CLIPS",
"bytes": "7056"
},
{
"name": "CSS",
"bytes": "2132"
},
{
"name": "Clarion",
"bytes": "4766"
},
{
"name": "DIGITAL Command Language",
"bytes": "24020"
},
{
"name": "FLUX",
"bytes": "1895"
},
{
"name": "Groff",
"bytes": "224601"
},
{
"name": "HTML",
"bytes": "3072563"
},
{
"name": "Inno Setup",
"bytes": "21811"
},
{
"name": "Lex",
"bytes": "7731"
},
{
"name": "Logos",
"bytes": "2079048"
},
{
"name": "Makefile",
"bytes": "243377"
},
{
"name": "Module Management System",
"bytes": "16278"
},
{
"name": "Objective-C",
"bytes": "75691"
},
{
"name": "PHP",
"bytes": "1007"
},
{
"name": "Pascal",
"bytes": "41721"
},
{
"name": "Perl",
"bytes": "34085"
},
{
"name": "Python",
"bytes": "48923"
},
{
"name": "SAS",
"bytes": "15827"
},
{
"name": "Shell",
"bytes": "836963"
},
{
"name": "Smalltalk",
"bytes": "2735"
},
{
"name": "TeX",
"bytes": "336604"
},
{
"name": "XSLT",
"bytes": "1834"
},
{
"name": "Yacc",
"bytes": "10988"
}
],
"symlink_target": ""
}
|
/*
* datacontext service encapsulates data access and model definition
*/
(function (){
'use strict';
angular.module('app').factory('datacontext',
['$log','$q', 'breeze', 'entityManagerFactory', 'wip-service', service]);
function service($log, $q, breeze, entityManagerFactory, wip){
var addedState = breeze.EntityState.Added;
var deletedState = breeze.EntityState.Deleted;
var manager;
var todoItemType;
var datacontext = {
addTodoItem: addTodoItem,
counts: {},
deleteTodoItem: deleteTodoItem,
getAllTodoItems: getAllTodoItems,
hasChanges: hasChanges,
loadTodoItems: loadTodoItems,
ready: ready,
reset: reset,
sync: sync
};
return datacontext;
/////////////////////////////
function ready(){
return entityManagerFactory.getEntityManager().then(haveEntityManager);
function haveEntityManager(em){
manager = em;
manager.entityChanged.subscribe(entityCountsChanged);
todoItemType = manager.metadataStore.getEntityType('TodoItem');
updateCounts();
}
}
function addTodoItem(initialValues){
return manager.createEntity(todoItemType, initialValues);
}
function deleteTodoItem(todoItem){
var aspect = todoItem.entityAspect;
if (aspect.entityState !== breeze.EntityState.Detached){
aspect.setDeleted();
}
}
function entityCountsChanged(changeArgs){
var action = changeArgs.entityAction;
if (action !== breeze.EntityAction.PropertyChange){
updateCounts();
}
}
// Get all TodoItems from the server and cache combined
function getAllTodoItems() {
// Create the query
var query = breeze.EntityQuery.from('TodoItem');
// .orderBy('text');
// .where('text', 'startsWith', 'L');
// Execute the query
return manager.executeQuery(query)
.then(success).catch(queryFailed);
function success(data){
// Interested in what server has then we are done.
var fetched = data.results;
$log.log('breeze query succeeded. fetched: '+ fetched.length);
// Blended results.
// This gets me all local changes and what the server game me.
return manager.getEntities(todoItemType);
// Normally would re-query the cache to combine cached and fetched
// but need the deleted entities too for this UI.
// For demo, we returned every cached Todo
// Warning: the cache will accumulate entities that
// have been deleted by other users until it is entirely rebuilt via 'refresh'
}
}
function hasChanges(){
return manager.hasChanges();
}
function loadTodoItems(){
wip.restore();
return getAllTodoItems();
}
function prettifyErrorMessage(message){
// When message returns the TodoItem guid id,
// try to replace with the TodoItem text which displays better
var re=/with id '([1234567890abcdef\-]*)'/i;
var match = message && message.match(re);
if (match){
var id = match[1];
var todo = id && manager.getEntityByKey('TodoItem',id);
if (todo) {
message = message.replace(re,'named "'+todo.text+'"')+" [key: "+id+"]";
}
}
return message;
}
function queryFailed(error) {
error.message = prettifyErrorMessage(error.message);
var status = error.status ? error.status + ' - ' : '';
var err = status + (error.message ? error.message : 'Unknown error; check console.log.');
err += '\nIs the server running?';
return $q.reject(err); // so downstream listener gets it.
}
// Clear everything local and reload from server.
function reset(){
wip.stop();
wip.clear();
manager.clear();
return getAllTodoItems()
.finally(function(){wip.resume();});
}
function sync(){
return manager.saveChanges()
.then(function (){
$log.log('breeze save succeeded');
wip.clear();
return getAllTodoItems();
})
.catch(saveFailed);
function saveFailed(error) {
var msg = 'Save failed: ' +
breeze.saveErrorMessageService.getErrorMessage(error);
error.message = msg;
throw error; // for downstream callers to see
}
}
function updateCounts() {
var counts = datacontext.counts;
counts.all = 0;
counts.Added = 0;
counts.Deleted = 0;
counts.Modified = 0;
counts.Unchanged = 0;
manager.getEntities().forEach(countIt);
function countIt(entity){
var state = entity.entityAspect.entityState.name;
counts[state] += 1;
counts.all += 1;
}
}
}
})();
|
{
"content_hash": "a60c8ce5ee0eaffcf45d458a1a17ed10",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 101,
"avg_line_length": 32.91860465116279,
"alnum_prop": 0.5171317555634052,
"repo_name": "Mahinga/AngularDemo",
"id": "eed94e88ac2afe5a6849c3c79196ebd580db01fd",
"size": "5662",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "todo-zumo/app/datacontext.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "12631"
},
{
"name": "CSS",
"bytes": "217825"
},
{
"name": "HTML",
"bytes": "134855"
},
{
"name": "JavaScript",
"bytes": "3123446"
},
{
"name": "PowerShell",
"bytes": "1652"
},
{
"name": "Shell",
"bytes": "8319"
}
],
"symlink_target": ""
}
|
package Rendering;
import Game.Input;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
/**
* Created by damien on 2014/08/26.
*/
public class Display extends Canvas {
private JFrame frame;
private BufferStrategy bufferStrat;
private Graphics graphics;
public Display(Input input, int width, int height, String title) {
frame = new JFrame(title);
this.setSize(width, height);
frame.add(this);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
this.createBufferStrategy(1);
bufferStrat = this.getBufferStrategy();
graphics = bufferStrat.getDrawGraphics();
addKeyListener(input);
addMouseListener(input);
addMouseMotionListener(input);
requestFocus();
frame.setVisible(true);
}
public void swapBuffers(BufferedImage image) {
graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
bufferStrat.show();
}
public JFrame getFrame() {
return frame;
}
}
|
{
"content_hash": "544eaa8c515b5438a19d51e5c6d311b1",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 83,
"avg_line_length": 24.46938775510204,
"alnum_prop": 0.6538782318598833,
"repo_name": "privatesimmons/Engine",
"id": "01ded542dbf51e5a8eef8c5d53a91ac9a24c7304",
"size": "1199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Rendering/Display.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "15652"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>User agent detail - Alcatel-OT-C750/1.0 UP.Browser/7.1 (GUI) MMP/2.0</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../circle.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Alcatel-OT-C750/1.0 UP.Browser/7.1 (GUI) MMP/2.0
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-C750</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a>
<!-- Modal Structure -->
<div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">Array
(
[user_agent_string] => Alcatel-OT-C750/1.0 UP.Browser/7.1 (GUI) MMP/2.0
[family] => Alcatel OT-C750
[brand] => Alcatel
[model] => OT-C750
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Openwave Mobile Browser 7.1</td><td> </td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.024</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a>
<!-- Modal Structure -->
<div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapFull result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^.* up\.browser\/7\.1.*$/
[browser_name_pattern] => * up.browser/7.1*
[parent] => Openwave Mobile Browser 7.1
[comment] => Openwave Mobile Browser 7.1
[browser] => Openwave Mobile Browser
[browser_type] => Browser
[browser_bits] => 0
[browser_maker] => Myriad Group
[browser_modus] => unknown
[version] => 7.1
[majorver] => 7
[minorver] => 1
[platform] => unknown
[platform_version] => unknown
[platform_description] => unknown
[platform_bits] => 0
[platform_maker] => unknown
[alpha] =>
[beta] =>
[win16] =>
[win32] =>
[win64] =>
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[javascript] => 1
[vbscript] =>
[javaapplets] =>
[activexcontrols] =>
[ismobiledevice] => 1
[istablet] =>
[issyndicationreader] =>
[crawler] =>
[isfake] =>
[isanonymized] =>
[ismodified] =>
[cssversion] => 0
[aolversion] => 0
[device_name] => general Mobile Phone
[device_maker] => unknown
[device_type] => Mobile Phone
[device_pointing_method] => unknown
[device_code_name] => general Mobile Phone
[device_brand_name] => unknown
[renderingengine_name] => unknown
[renderingengine_version] => unknown
[renderingengine_description] => unknown
[renderingengine_maker] => unknown
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Openwave Mobile Browser 7.1</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.059</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a>
<!-- Modal Structure -->
<div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^.* up\.browser\/7\.1.*$/
[browser_name_pattern] => * up.browser/7.1*
[parent] => Openwave Mobile Browser 7.1
[comment] => Openwave Mobile Browser 7.1
[browser] => Openwave Mobile Browser
[browser_type] => unknown
[browser_bits] => 0
[browser_maker] => Myriad Group
[browser_modus] => unknown
[version] => 7.1
[majorver] => 7
[minorver] => 1
[platform] => unknown
[platform_version] => unknown
[platform_description] => unknown
[platform_bits] => 0
[platform_maker] => unknown
[alpha] => false
[beta] => false
[win16] => false
[win32] => false
[win64] => false
[frames] => false
[iframes] => false
[tables] => false
[cookies] => false
[backgroundsounds] => false
[javascript] => false
[vbscript] => false
[javaapplets] => false
[activexcontrols] => false
[ismobiledevice] => 1
[istablet] =>
[issyndicationreader] => false
[crawler] =>
[isfake] => false
[isanonymized] => false
[ismodified] => false
[cssversion] => 0
[aolversion] => 0
[device_name] => unknown
[device_maker] => unknown
[device_type] => Mobile Phone
[device_pointing_method] => unknown
[device_code_name] => unknown
[device_brand_name] => unknown
[renderingengine_name] => unknown
[renderingengine_version] => unknown
[renderingengine_description] => unknown
[renderingengine_maker] => unknown
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>Alcatel-OT-C750 1.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a>
<!-- Modal Structure -->
<div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>DonatjUAParser result detail</h4>
<p><pre><code class="php">Array
(
[platform] =>
[browser] => Alcatel-OT-C750
[version] => 1.0
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a>
<!-- Modal Structure -->
<div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>JenssegersAgent result detail</h4>
<p><pre><code class="php">Array
(
[browserName] =>
[browserVersion] =>
[osName] =>
[osVersion] =>
[deviceModel] => Alcatel
[isMobile] => 1
[isRobot] =>
[botName] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Openwave Mobile Browser 7.1</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>One Touch C750</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.20401</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a>
<!-- Modal Structure -->
<div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>NeutrinoApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[mobile_screen_height] => 160
[is_mobile] => 1
[type] => mobile-browser
[mobile_brand] => Alcatel
[mobile_model] => One Touch C750
[version] => 7.1
[is_android] =>
[browser_name] => Openwave Mobile Browser
[operating_system_family] => unknown
[operating_system_version] =>
[is_ios] =>
[producer] => Openwave Systems Inc.
[operating_system] => unknown
[mobile_screen_width] => 128
[mobile_browser] => Openwave Mobile Browser
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>Openwave Mobile Browser 7.1</td><td> </td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-C750</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.003</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a>
<!-- Modal Structure -->
<div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>PiwikDeviceDetector result detail</h4>
<p><pre><code class="php">Array
(
[client] => Array
(
[type] => browser
[name] => Openwave Mobile Browser
[short_name] => OV
[version] => 7.1
[engine] =>
)
[operatingSystem] => Array
(
)
[device] => Array
(
[brand] => AL
[brandName] => Alcatel
[model] => OT-C750
[device] => 1
[deviceName] => smartphone
)
[bot] =>
[extra] => Array
(
[isBot] =>
[isBrowser] => 1
[isFeedReader] =>
[isMobileApp] =>
[isPIM] =>
[isLibrary] =>
[isMediaPlayer] =>
[isCamera] =>
[isCarBrowser] =>
[isConsole] =>
[isFeaturePhone] =>
[isPhablet] =>
[isPortableMediaPlayer] =>
[isSmartDisplay] =>
[isSmartphone] => 1
[isTablet] =>
[isTV] =>
[isDesktop] =>
[isMobile] => 1
[isTouchEnabled] =>
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-C750</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a>
<!-- Modal Structure -->
<div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">UAParser\Result\Client Object
(
[ua] => UAParser\Result\UserAgent Object
(
[major] =>
[minor] =>
[patch] =>
[family] => Other
)
[os] => UAParser\Result\OperatingSystem Object
(
[major] =>
[minor] =>
[patch] =>
[patchMinor] =>
[family] => Other
)
[device] => UAParser\Result\Device Object
(
[brand] => Alcatel
[model] => OT-C750
[family] => Alcatel OT-C750
)
[originalUserAgent] => Alcatel-OT-C750/1.0 UP.Browser/7.1 (GUI) MMP/2.0
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td> </td><td> </td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.15101</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a>
<!-- Modal Structure -->
<div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UserAgentApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[platform_name] => Alcatel
[platform_version] => 750
[platform_type] => Mobile
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Openwave Mobile Browser 7.1</td><td> </td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.23601</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a>
<!-- Modal Structure -->
<div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhatIsMyBrowserCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[operating_system_name] =>
[simple_sub_description_string] =>
[simple_browser_string] => Openwave Mobile Browser 7.1
[browser_version] => 7.1
[extra_info] => Array
(
)
[operating_platform] =>
[extra_info_table] => Array
(
)
[layout_engine_name] =>
[detected_addons] => Array
(
)
[operating_system_flavour_code] =>
[hardware_architecture] =>
[operating_system_flavour] =>
[operating_system_frameworks] => Array
(
)
[browser_name_code] => openwave-mobile-browser
[operating_system_version] =>
[simple_operating_platform_string] =>
[is_abusive] =>
[layout_engine_version] =>
[browser_capabilities] => Array
(
[0] => MMP v2.0
)
[operating_platform_vendor_name] =>
[operating_system] =>
[operating_system_version_full] =>
[operating_platform_code] =>
[browser_name] => Openwave Mobile Browser
[operating_system_name_code] =>
[user_agent] => Alcatel-OT-C750/1.0 UP.Browser/7.1 (GUI) MMP/2.0
[browser_version_full] => 7.1
[browser] => Openwave Mobile Browser 7.1
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td>Openwave 7.1</td><td> </td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>One Touch C750</td><td>mobile:feature</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.003</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a>
<!-- Modal Structure -->
<div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[name] => Openwave
[version] => 7.1
[type] => browser
)
[device] => Array
(
[type] => mobile
[subtype] => feature
[manufacturer] => Alcatel
[model] => One Touch C750
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>One Touch C750</td><td>Feature Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.019</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a>
<!-- Modal Structure -->
<div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Wurfl result detail</h4>
<p><pre><code class="php">Array
(
[virtual] => Array
(
[is_android] => false
[is_ios] => false
[is_windows_phone] => false
[is_app] => false
[is_full_desktop] => false
[is_largescreen] => false
[is_mobile] => true
[is_robot] => false
[is_smartphone] => false
[is_touchscreen] => false
[is_wml_preferred] => false
[is_xhtmlmp_preferred] => true
[is_html_preferred] => false
[advertised_device_os] =>
[advertised_device_os_version] =>
[advertised_browser] =>
[advertised_browser_version] =>
[complete_device_name] => Alcatel One Touch C750
[device_name] => Alcatel One Touch C750
[form_factor] => Feature Phone
[is_phone] => true
[is_app_webview] => false
)
[all] => Array
(
[brand_name] => Alcatel
[model_name] => One Touch C750
[unique] => true
[ununiqueness_handler] =>
[is_wireless_device] => true
[device_claims_web_support] => false
[has_qwerty_keyboard] => false
[can_skip_aligned_link_row] => true
[uaprof] => http://www-ccpp-mpd.alcatel.com/files/ALCATEL-E5_cE5c_1.0.rdf
[uaprof2] =>
[uaprof3] =>
[nokia_series] => 0
[nokia_edition] => 0
[device_os] =>
[mobile_browser] => Openwave Mobile Browser
[mobile_browser_version] => 7.1
[device_os_version] =>
[pointing_method] =>
[release_date] => 2009_november
[marketing_name] =>
[model_extra_info] =>
[nokia_feature_pack] => 0
[can_assign_phone_number] => true
[is_tablet] => false
[manufacturer_name] =>
[is_bot] => false
[is_google_glass] => false
[proportional_font] => true
[built_in_back_button_support] => true
[card_title_support] => false
[softkey_support] => true
[table_support] => true
[numbered_menus] => true
[menu_with_select_element_recommended] => true
[menu_with_list_of_links_recommended] => false
[icons_on_menu_items_support] => true
[break_list_of_links_with_br_element_recommended] => false
[access_key_support] => true
[wrap_mode_support] => true
[times_square_mode_support] => true
[deck_prefetch_support] => true
[elective_forms_recommended] => false
[wizards_recommended] => true
[image_as_link_support] => false
[insert_br_element_after_widget_recommended] => false
[wml_can_display_images_and_text_on_same_line] => false
[wml_displays_image_in_center] => false
[opwv_wml_extensions_support] => true
[wml_make_phone_call_string] => wtai://wp/mc;
[chtml_display_accesskey] => false
[emoji] => false
[chtml_can_display_images_and_text_on_same_line] => false
[chtml_displays_image_in_center] => false
[imode_region] => none
[chtml_make_phone_call_string] => tel:
[chtml_table_support] => false
[xhtml_honors_bgcolor] => false
[xhtml_supports_forms_in_table] => false
[xhtml_support_wml2_namespace] => false
[xhtml_autoexpand_select] => true
[xhtml_select_as_dropdown] => false
[xhtml_select_as_radiobutton] => false
[xhtml_select_as_popup] => false
[xhtml_display_accesskey] => false
[xhtml_supports_invisible_text] => true
[xhtml_supports_inline_input] => true
[xhtml_supports_monospace_font] => true
[xhtml_supports_table_for_layout] => true
[xhtml_supports_css_cell_table_coloring] => true
[xhtml_format_as_css_property] => true
[xhtml_format_as_attribute] => true
[xhtml_nowrap_mode] => true
[xhtml_marquee_as_css_property] => true
[xhtml_readable_background_color1] => #99CCFF
[xhtml_readable_background_color2] => #FFFFFF
[xhtml_allows_disabled_form_elements] => true
[xhtml_document_title_support] => true
[xhtml_preferred_charset] => iso8859
[opwv_xhtml_extensions_support] => true
[xhtml_make_phone_call_string] => wtai://wp/mc;
[xhtmlmp_preferred_mime_type] => application/vnd.wap.xhtml+xml
[xhtml_table_support] => true
[xhtml_send_sms_string] => none
[xhtml_send_mms_string] => none
[xhtml_file_upload] => supported
[cookie_support] => true
[accept_third_party_cookie] => false
[xhtml_supports_iframe] => none
[xhtml_avoid_accesskeys] => false
[xhtml_can_embed_video] => none
[ajax_support_javascript] => false
[ajax_manipulate_css] => false
[ajax_support_getelementbyid] => false
[ajax_support_inner_html] => false
[ajax_xhr_type] => none
[ajax_manipulate_dom] => false
[ajax_support_events] => false
[ajax_support_event_listener] => false
[ajax_preferred_geoloc_api] => none
[xhtml_support_level] => 3
[preferred_markup] => html_wi_oma_xhtmlmp_1_0
[wml_1_1] => true
[wml_1_2] => true
[wml_1_3] => true
[html_wi_w3_xhtmlbasic] => true
[html_wi_oma_xhtmlmp_1_0] => true
[html_wi_imode_html_1] => true
[html_wi_imode_html_2] => true
[html_wi_imode_html_3] => true
[html_wi_imode_html_4] => false
[html_wi_imode_html_5] => false
[html_wi_imode_htmlx_1] => true
[html_wi_imode_htmlx_1_1] => false
[html_wi_imode_compact_generic] => true
[html_web_3_2] => false
[html_web_4_0] => false
[voicexml] => false
[multipart_support] => true
[total_cache_disable_support] => false
[time_to_live_support] => true
[resolution_width] => 128
[resolution_height] => 160
[columns] => 14
[max_image_width] => 120
[max_image_height] => 130
[rows] => 7
[physical_screen_width] => 27
[physical_screen_height] => 27
[dual_orientation] => false
[density_class] => 1.0
[wbmp] => true
[bmp] => true
[epoc_bmp] => false
[gif_animated] => true
[jpg] => true
[png] => true
[tiff] => false
[transparent_png_alpha] => false
[transparent_png_index] => false
[svgt_1_1] => false
[svgt_1_1_plus] => false
[greyscale] => false
[gif] => true
[colors] => 65536
[webp_lossy_support] => false
[webp_lossless_support] => false
[post_method_support] => true
[basic_authentication_support] => true
[empty_option_value_support] => false
[emptyok] => false
[nokia_voice_call] => false
[wta_voice_call] => true
[wta_phonebook] => false
[wta_misc] => false
[wta_pdc] => false
[https_support] => true
[phone_id_provided] => false
[max_data_rate] => 40
[wifi] => false
[sdio] => false
[vpn] => false
[has_cellular_radio] => true
[max_deck_size] => 15000
[max_url_length_in_requests] => 256
[max_url_length_homepage] => 0
[max_url_length_bookmark] => 0
[max_url_length_cached_page] => 0
[max_no_of_connection_settings] => 0
[max_no_of_bookmarks] => 0
[max_length_of_username] => 0
[max_length_of_password] => 0
[max_object_size] => 0
[downloadfun_support] => false
[directdownload_support] => true
[inline_support] => false
[oma_support] => true
[ringtone] => false
[ringtone_3gpp] => false
[ringtone_midi_monophonic] => false
[ringtone_midi_polyphonic] => false
[ringtone_imelody] => false
[ringtone_digiplug] => false
[ringtone_compactmidi] => false
[ringtone_mmf] => false
[ringtone_rmf] => false
[ringtone_xmf] => false
[ringtone_amr] => false
[ringtone_awb] => false
[ringtone_aac] => false
[ringtone_wav] => false
[ringtone_mp3] => false
[ringtone_spmidi] => false
[ringtone_qcelp] => false
[ringtone_voices] => 1
[ringtone_df_size_limit] => 0
[ringtone_directdownload_size_limit] => 0
[ringtone_inline_size_limit] => 0
[ringtone_oma_size_limit] => 0
[wallpaper] => false
[wallpaper_max_width] => 0
[wallpaper_max_height] => 0
[wallpaper_preferred_width] => 0
[wallpaper_preferred_height] => 0
[wallpaper_resize] => none
[wallpaper_wbmp] => false
[wallpaper_bmp] => false
[wallpaper_gif] => false
[wallpaper_jpg] => false
[wallpaper_png] => false
[wallpaper_tiff] => false
[wallpaper_greyscale] => false
[wallpaper_colors] => 2
[wallpaper_df_size_limit] => 0
[wallpaper_directdownload_size_limit] => 0
[wallpaper_inline_size_limit] => 0
[wallpaper_oma_size_limit] => 0
[screensaver] => false
[screensaver_max_width] => 0
[screensaver_max_height] => 0
[screensaver_preferred_width] => 0
[screensaver_preferred_height] => 0
[screensaver_resize] => none
[screensaver_wbmp] => false
[screensaver_bmp] => false
[screensaver_gif] => false
[screensaver_jpg] => false
[screensaver_png] => false
[screensaver_greyscale] => false
[screensaver_colors] => 2
[screensaver_df_size_limit] => 0
[screensaver_directdownload_size_limit] => 0
[screensaver_inline_size_limit] => 0
[screensaver_oma_size_limit] => 0
[picture] => false
[picture_max_width] => 0
[picture_max_height] => 0
[picture_preferred_width] => 0
[picture_preferred_height] => 0
[picture_resize] => none
[picture_wbmp] => false
[picture_bmp] => false
[picture_gif] => false
[picture_jpg] => false
[picture_png] => false
[picture_greyscale] => false
[picture_colors] => 2
[picture_df_size_limit] => 0
[picture_directdownload_size_limit] => 0
[picture_inline_size_limit] => 0
[picture_oma_size_limit] => 0
[video] => false
[oma_v_1_0_forwardlock] => true
[oma_v_1_0_combined_delivery] => true
[oma_v_1_0_separate_delivery] => true
[streaming_video] => false
[streaming_3gpp] => false
[streaming_mp4] => false
[streaming_mov] => false
[streaming_video_size_limit] => 0
[streaming_real_media] => none
[streaming_flv] => false
[streaming_3g2] => false
[streaming_vcodec_h263_0] => -1
[streaming_vcodec_h263_3] => -1
[streaming_vcodec_mpeg4_sp] => -1
[streaming_vcodec_mpeg4_asp] => -1
[streaming_vcodec_h264_bp] => -1
[streaming_acodec_amr] => none
[streaming_acodec_aac] => none
[streaming_wmv] => none
[streaming_preferred_protocol] => rtsp
[streaming_preferred_http_protocol] => none
[wap_push_support] => true
[connectionless_service_indication] => true
[connectionless_service_load] => false
[connectionless_cache_operation] => true
[connectionoriented_unconfirmed_service_indication] => true
[connectionoriented_unconfirmed_service_load] => true
[connectionoriented_unconfirmed_cache_operation] => true
[connectionoriented_confirmed_service_indication] => true
[connectionoriented_confirmed_service_load] => true
[connectionoriented_confirmed_cache_operation] => true
[utf8_support] => true
[ascii_support] => false
[iso8859_support] => false
[expiration_date] => true
[j2me_cldc_1_0] => true
[j2me_cldc_1_1] => true
[j2me_midp_1_0] => true
[j2me_midp_2_0] => true
[doja_1_0] => false
[doja_1_5] => false
[doja_2_0] => false
[doja_2_1] => false
[doja_2_2] => false
[doja_3_0] => false
[doja_3_5] => false
[doja_4_0] => false
[j2me_jtwi] => false
[j2me_mmapi_1_0] => false
[j2me_mmapi_1_1] => false
[j2me_wmapi_1_0] => false
[j2me_wmapi_1_1] => false
[j2me_wmapi_2_0] => false
[j2me_btapi] => false
[j2me_3dapi] => false
[j2me_locapi] => false
[j2me_nokia_ui] => false
[j2me_motorola_lwt] => false
[j2me_siemens_color_game] => false
[j2me_siemens_extension] => false
[j2me_heap_size] => 0
[j2me_max_jar_size] => 0
[j2me_storage_size] => 0
[j2me_max_record_store_size] => 0
[j2me_screen_width] => 0
[j2me_screen_height] => 0
[j2me_canvas_width] => 0
[j2me_canvas_height] => 0
[j2me_bits_per_pixel] => 0
[j2me_audio_capture_enabled] => false
[j2me_video_capture_enabled] => false
[j2me_photo_capture_enabled] => false
[j2me_capture_image_formats] => none
[j2me_http] => false
[j2me_https] => false
[j2me_socket] => false
[j2me_udp] => false
[j2me_serial] => false
[j2me_gif] => false
[j2me_gif89a] => false
[j2me_jpg] => false
[j2me_png] => false
[j2me_bmp] => false
[j2me_bmp3] => false
[j2me_wbmp] => false
[j2me_midi] => false
[j2me_wav] => false
[j2me_amr] => false
[j2me_mp3] => false
[j2me_mp4] => false
[j2me_imelody] => false
[j2me_rmf] => false
[j2me_au] => false
[j2me_aac] => false
[j2me_realaudio] => false
[j2me_xmf] => false
[j2me_wma] => false
[j2me_3gpp] => false
[j2me_h263] => false
[j2me_svgt] => false
[j2me_mpeg4] => false
[j2me_realvideo] => false
[j2me_real8] => false
[j2me_realmedia] => false
[j2me_left_softkey_code] => 0
[j2me_right_softkey_code] => 0
[j2me_middle_softkey_code] => 0
[j2me_select_key_code] => 0
[j2me_return_key_code] => 0
[j2me_clear_key_code] => 0
[j2me_datefield_no_accepts_null_date] => false
[j2me_datefield_broken] => false
[receiver] => false
[sender] => false
[mms_max_size] => 102400
[mms_max_height] => 640
[mms_max_width] => 640
[built_in_recorder] => false
[built_in_camera] => false
[mms_jpeg_baseline] => true
[mms_jpeg_progressive] => false
[mms_gif_static] => true
[mms_gif_animated] => false
[mms_png] => true
[mms_bmp] => true
[mms_wbmp] => true
[mms_amr] => true
[mms_wav] => true
[mms_midi_monophonic] => true
[mms_midi_polyphonic] => false
[mms_midi_polyphonic_voices] => 0
[mms_spmidi] => true
[mms_mmf] => false
[mms_mp3] => false
[mms_evrc] => false
[mms_qcelp] => false
[mms_ota_bitmap] => false
[mms_nokia_wallpaper] => false
[mms_nokia_operatorlogo] => false
[mms_nokia_3dscreensaver] => false
[mms_nokia_ringingtone] => false
[mms_rmf] => false
[mms_xmf] => false
[mms_symbian_install] => false
[mms_jar] => false
[mms_jad] => false
[mms_vcard] => true
[mms_vcalendar] => false
[mms_wml] => false
[mms_wbxml] => false
[mms_wmlc] => false
[mms_video] => false
[mms_mp4] => false
[mms_3gpp] => false
[mms_3gpp2] => false
[mms_max_frame_rate] => 0
[nokiaring] => false
[picturemessage] => false
[operatorlogo] => false
[largeoperatorlogo] => false
[callericon] => false
[nokiavcard] => false
[nokiavcal] => false
[sckl_ringtone] => false
[sckl_operatorlogo] => false
[sckl_groupgraphic] => false
[sckl_vcard] => false
[sckl_vcalendar] => false
[text_imelody] => false
[ems] => false
[ems_variablesizedpictures] => false
[ems_imelody] => false
[ems_odi] => false
[ems_upi] => false
[ems_version] => 0
[siemens_ota] => false
[siemens_logo_width] => 101
[siemens_logo_height] => 29
[siemens_screensaver_width] => 101
[siemens_screensaver_height] => 50
[gprtf] => false
[sagem_v1] => false
[sagem_v2] => false
[panasonic] => false
[sms_enabled] => true
[wav] => true
[mmf] => false
[smf] => false
[mld] => false
[midi_monophonic] => true
[midi_polyphonic] => false
[sp_midi] => true
[rmf] => false
[xmf] => false
[compactmidi] => false
[digiplug] => false
[nokia_ringtone] => false
[imelody] => false
[au] => false
[amr] => true
[awb] => false
[aac] => false
[mp3] => false
[voices] => 1
[qcelp] => false
[evrc] => false
[flash_lite_version] =>
[fl_wallpaper] => false
[fl_screensaver] => false
[fl_standalone] => false
[fl_browser] => false
[fl_sub_lcd] => false
[full_flash_support] => false
[css_supports_width_as_percentage] => true
[css_border_image] => none
[css_rounded_corners] => none
[css_gradient] => none
[css_spriting] => false
[css_gradient_linear] => none
[is_transcoder] => false
[transcoder_ua_header] => user-agent
[rss_support] => false
[pdf_support] => false
[progressive_download] => false
[playback_vcodec_h263_0] => -1
[playback_vcodec_h263_3] => -1
[playback_vcodec_mpeg4_sp] => -1
[playback_vcodec_mpeg4_asp] => -1
[playback_vcodec_h264_bp] => -1
[playback_real_media] => none
[playback_3gpp] => false
[playback_3g2] => false
[playback_mp4] => false
[playback_mov] => false
[playback_acodec_amr] => none
[playback_acodec_aac] => none
[playback_df_size_limit] => 0
[playback_directdownload_size_limit] => 0
[playback_inline_size_limit] => 0
[playback_oma_size_limit] => 0
[playback_acodec_qcelp] => false
[playback_wmv] => none
[hinted_progressive_download] => false
[html_preferred_dtd] => xhtml_mp1
[viewport_supported] => false
[viewport_width] =>
[viewport_userscalable] =>
[viewport_initial_scale] =>
[viewport_maximum_scale] =>
[viewport_minimum_scale] =>
[mobileoptimized] => false
[handheldfriendly] => false
[canvas_support] => none
[image_inlining] => false
[is_smarttv] => false
[is_console] => false
[nfc_support] => false
[ux_full_desktop] => false
[jqm_grade] => none
[is_sencha_touch_ok] => false
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>Openwave Mobile Browser 7.1</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a>
<!-- Modal Structure -->
<div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Zsxsoft result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[link] => http://www.openwave.com/
[title] => Openwave Mobile Browser 7.1
[code] => openwave
[version] => 7.1
[name] => Openwave Mobile Browser
[image] => img/16/browser/openwave.png
)
[os] => Array
(
[link] =>
[name] =>
[version] =>
[code] => null
[x64] =>
[title] =>
[type] => os
[dir] => os
[image] => img/16/os/null.png
)
[device] => Array
(
[link] => #
[title] => Unknown
[code] => null
[dir] => browser
[type] => os
[image] => img/16/browser/null.png
)
[platform] => Array
(
[link] => #
[title] => Unknown
[code] => null
[dir] => browser
[type] => os
[image] => img/16/browser/null.png
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr></table>
</div>
<div class="section">
<h1 class="header center orange-text">About this comparison</h1>
<div class="row center">
<h5 class="header light">
The primary goal of this project is simple<br />
I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br />
<br />
The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br />
<br />
You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br />
<br />
The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a>
</h5>
</div>
</div>
<div class="card">
<div class="card-content">
Comparison created <i>2016-05-10 08:03:29</i> | by
<a href="https://github.com/ThaDafinser">ThaDafinser</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script>
<script>
$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});
</script>
</body>
</html>
|
{
"content_hash": "6a48cb100f79a33e29d13b51be65f64b",
"timestamp": "",
"source": "github",
"line_count": 1183,
"max_line_length": 962,
"avg_line_length": 39.828402366863905,
"alnum_prop": 0.5285990194621899,
"repo_name": "ThaDafinser/UserAgentParserComparison",
"id": "96df4e6eb5f6858b83fad456c5fd72a41f600f7d",
"size": "47118",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "v5/user-agent-detail/9a/90/9a90c3e0-af15-49e4-ac51-721358e4532c.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2060859160"
}
],
"symlink_target": ""
}
|
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.Statements
{
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime;
using System.Runtime.Collections;
using System.Windows.Markup;
[ContentProperty("Cases")]
public sealed class FlowSwitch<T> : FlowNode, IFlowSwitch
{
const string DefaultDisplayName = "Switch";
internal IDictionary<T, FlowNode> cases;
CompletionCallback<T> onSwitchCompleted;
string displayName;
public FlowSwitch()
{
this.cases = new NullableKeyDictionary<T, FlowNode>();
this.displayName = FlowSwitch<T>.DefaultDisplayName;
}
[DefaultValue(null)]
public Activity<T> Expression
{
get;
set;
}
[DefaultValue(null)]
public FlowNode Default
{
get;
set;
}
[Fx.Tag.KnownXamlExternal]
public IDictionary<T, FlowNode> Cases
{
get
{
return this.cases;
}
}
[DefaultValue(FlowSwitch<T>.DefaultDisplayName)]
public string DisplayName
{
get
{
return this.displayName;
}
set
{
this.displayName = value;
}
}
internal override void OnOpen(Flowchart owner, NativeActivityMetadata metadata)
{
if (this.Expression == null)
{
metadata.AddValidationError(SR.FlowSwitchRequiresExpression(owner.DisplayName));
}
}
internal override void GetConnectedNodes(IList<FlowNode> connections)
{
foreach (KeyValuePair<T, FlowNode> item in this.Cases)
{
connections.Add(item.Value);
}
if (this.Default != null)
{
connections.Add(this.Default);
}
}
internal override Activity ChildActivity
{
get { return Expression; }
}
bool IFlowSwitch.Execute(NativeActivityContext context, Flowchart parent)
{
context.ScheduleActivity(Expression, this.GetSwitchCompletedCallback(parent));
return false;
}
FlowNode IFlowSwitch.GetNextNode(object value)
{
FlowNode result;
T newValue = (T)value;
if (Cases.TryGetValue(newValue, out result))
{
if (TD.FlowchartSwitchCaseIsEnabled())
{
TD.FlowchartSwitchCase(this.Owner.DisplayName, newValue.ToString());
}
return result;
}
else
{
if (this.Default != null)
{
if (TD.FlowchartSwitchDefaultIsEnabled())
{
TD.FlowchartSwitchDefault(this.Owner.DisplayName);
}
}
else
{
if (TD.FlowchartSwitchCaseNotFoundIsEnabled())
{
TD.FlowchartSwitchCaseNotFound(this.Owner.DisplayName);
}
}
return this.Default;
}
}
CompletionCallback<T> GetSwitchCompletedCallback(Flowchart parent)
{
if (onSwitchCompleted == null)
{
onSwitchCompleted = new CompletionCallback<T>(parent.OnSwitchCompleted<T>);
}
return onSwitchCompleted;
}
}
}
|
{
"content_hash": "9edac15a5d9a1f5b128fb1946fa97c39",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 96,
"avg_line_length": 28.74264705882353,
"alnum_prop": 0.4878485546175492,
"repo_name": "mono/referencesource",
"id": "8ddced5977121eb8a559f4a359ca6c36fb887a2e",
"size": "3911",
"binary": false,
"copies": "15",
"ref": "refs/heads/mono",
"path": "System.Activities/System/Activities/Statements/FlowSwitch.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "155045910"
}
],
"symlink_target": ""
}
|
"""Bijector base."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
import contextlib
import re
import numpy as np
import six
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.util.tf_export import tf_export
__all__ = [
"Bijector",
]
class _Mapping(collections.namedtuple(
"_Mapping", ["x", "y", "ildj", "kwargs"])):
"""Helper class to make it easier to manage caching in `Bijector`."""
def __new__(cls, x=None, y=None, ildj=None, kwargs=None):
"""Custom __new__ so namedtuple items have defaults.
Args:
x: `Tensor`. Forward.
y: `Tensor`. Inverse.
ildj: `Tensor`. Inverse log det Jacobian.
kwargs: Python dictionary. Extra args supplied to
forward/inverse/etc functions.
Returns:
mapping: New instance of _Mapping.
"""
return super(_Mapping, cls).__new__(cls, x, y, ildj, kwargs)
@property
def x_key(self):
"""Returns key used for caching Y=g(X)."""
return (self.x,) + self._deep_tuple(tuple(sorted(self.kwargs.items())))
@property
def y_key(self):
"""Returns key used for caching X=g^{-1}(Y)."""
return (self.y,) + self._deep_tuple(tuple(sorted(self.kwargs.items())))
def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None):
"""Returns new _Mapping with args merged with self.
Args:
x: `Tensor`. Forward.
y: `Tensor`. Inverse.
ildj: `Tensor`. Inverse log det Jacobian.
kwargs: Python dictionary. Extra args supplied to
forward/inverse/etc functions.
mapping: Instance of _Mapping to merge. Can only be specified if no other
arg is specified.
Returns:
mapping: New instance of `_Mapping` which has inputs merged with self.
Raises:
ValueError: if mapping and any other arg is not `None`.
"""
if mapping is None:
mapping = _Mapping(x=x, y=y, ildj=ildj, kwargs=kwargs)
elif not all(arg is None for arg in [x, y, ildj, kwargs]):
raise ValueError("Cannot specify mapping and individual args.")
return _Mapping(
x=self._merge(self.x, mapping.x),
y=self._merge(self.y, mapping.y),
ildj=self._merge(self.ildj, mapping.ildj),
kwargs=self._merge(self.kwargs, mapping.kwargs))
def _merge(self, old, new):
"""Helper to merge which handles merging one value."""
if old is None:
return new
elif new is not None and old != new:
raise ValueError("Incompatible values: %s != %s" % (old, new))
return old
def _deep_tuple(self, x):
"""Converts lists of lists to tuples of tuples."""
return (tuple(map(self._deep_tuple, x))
if isinstance(x, (list, tuple)) else x)
@six.add_metaclass(abc.ABCMeta)
@tf_export("distributions.bijectors.Bijector")
class Bijector(object):
"""Interface for transformations of a `Distribution` sample.
Bijectors can be used to represent any differentiable and injective
(one to one) function defined on an open subset of `R^n`. Some non-injective
transformations are also supported (see "Non Injective Transforms" below).
#### Mathematical Details
A `Bijector` implements a
[diffeomorphism](https://en.wikipedia.org/wiki/Diffeomorphism), i.e., a
bijective, differentiable function. A `Bijector` is used by
`TransformedDistribution` but can be generally used for transforming a
`Distribution` generated `Tensor`. A `Bijector` is characterized by three
operations:
1. Forward Evaluation
Useful for turning one random outcome into another random outcome from a
different distribution.
2. Inverse Evaluation
Useful for "reversing" a transformation to compute one probability in
terms of another.
3. (log o det o Jacobian o inverse)(x)
"The log of the determinant of the matrix of all first-order partial
derivatives of the inverse function."
Useful for inverting a transformation to compute one probability in terms
of another. Geometrically, the det(Jacobian) is the volume of the
transformation and is used to scale the probability.
By convention, transformations of random variables are named in terms of the
forward transformation. The forward transformation creates samples, the
inverse is useful for computing probabilities.
#### Example Uses
- Basic properties:
```python
x = ... # A tensor.
# Evaluate forward transformation.
fwd_x = my_bijector.forward(x)
x == my_bijector.inverse(fwd_x)
x != my_bijector.forward(fwd_x) # Not equal because x != g(g(x)).
```
- Computing a log-likelihood:
```python
def transformed_log_prob(bijector, log_prob, x):
return (bijector.inverse_log_det_jacobian(x) +
log_prob(bijector.inverse(x)))
```
- Transforming a random outcome:
```python
def transformed_sample(bijector, x):
return bijector.forward(x)
```
#### Example Bijectors
- "Exponential"
```none
Y = g(X) = exp(X)
X ~ Normal(0, 1) # Univariate.
```
Implies:
```none
g^{-1}(Y) = log(Y)
|Jacobian(g^{-1})(y)| = 1 / y
Y ~ LogNormal(0, 1), i.e.,
prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
= (1 / y) Normal(log(y); 0, 1)
```
Here is an example of how one might implement the `Exp` bijector:
```python
class Exp(Bijector):
def __init__(self, event_ndims=0, validate_args=False, name="exp"):
super(Exp, self).__init__(
event_ndims=event_ndims, validate_args=validate_args, name=name)
def _forward(self, x):
return math_ops.exp(x)
def _inverse(self, y):
return math_ops.log(y)
def _inverse_log_det_jacobian(self, y):
return -self._forward_log_det_jacobian(self._inverse(y))
def _forward_log_det_jacobian(self, x):
if self.event_ndims is None:
raise ValueError("Jacobian requires known event_ndims.")
event_dims = array_ops.shape(x)[-self.event_ndims:]
return math_ops.reduce_sum(x, axis=event_dims)
```
- "Affine"
```none
Y = g(X) = sqrtSigma * X + mu
X ~ MultivariateNormal(0, I_d)
```
Implies:
```none
g^{-1}(Y) = inv(sqrtSigma) * (Y - mu)
|Jacobian(g^{-1})(y)| = det(inv(sqrtSigma))
Y ~ MultivariateNormal(mu, sqrtSigma) , i.e.,
prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
= det(sqrtSigma)^(-d) *
MultivariateNormal(inv(sqrtSigma) * (y - mu); 0, I_d)
```
#### Jacobian
The Jacobian is a reduction over event dims. To see this, consider the `Exp`
`Bijector` applied to a `Tensor` which has sample, batch, and event (S, B, E)
shape semantics. Suppose the `Tensor`'s partitioned-shape is `(S=[4], B=[2],
E=[3, 3])`. The shape of the `Tensor` returned by `forward` and `inverse` is
unchanged, i.e., `[4, 2, 3, 3]`. However the shape returned by
`inverse_log_det_jacobian` is `[4, 2]` because the Jacobian is a reduction
over the event dimensions.
It is sometimes useful to implement the inverse Jacobian as the negative
forward Jacobian. For example,
```python
def _inverse_log_det_jacobian(self, y):
return -self._forward_log_det_jac(self._inverse(y)) # Note negation.
```
The correctness of this approach can be seen from the following claim.
- Claim:
Assume `Y = g(X)` is a bijection whose derivative exists and is nonzero
for its domain, i.e., `dY/dX = d/dX g(X) != 0`. Then:
```none
(log o det o jacobian o g^{-1})(Y) = -(log o det o jacobian o g)(X)
```
- Proof:
From the bijective, nonzero differentiability of `g`, the
[inverse function theorem](
https://en.wikipedia.org/wiki/Inverse_function_theorem)
implies `g^{-1}` is differentiable in the image of `g`.
Applying the chain rule to `y = g(x) = g(g^{-1}(y))` yields
`I = g'(g^{-1}(y))*g^{-1}'(y)`.
The same theorem also implies `g^{-1}'` is non-singular therefore:
`inv[ g'(g^{-1}(y)) ] = g^{-1}'(y)`.
The claim follows from [properties of determinant](
https://en.wikipedia.org/wiki/Determinant#Multiplicativity_and_matrix_groups).
Generally its preferable to directly implement the inverse Jacobian. This
should have superior numerical stability and will often share subgraphs with
the `_inverse` implementation.
#### Subclass Requirements
- Subclasses typically implement:
- `_forward`,
- `_inverse`,
- `_inverse_log_det_jacobian`,
- `_forward_log_det_jacobian` (optional).
The `_forward_log_det_jacobian` is called when the bijector is inverted via
the `Invert` bijector. If undefined, a slightly less efficiently
calculation, `-1 * _inverse_log_det_jacobian`, is used.
If the bijector changes the shape of the input, you must also implement:
- _forward_event_shape_tensor,
- _forward_event_shape (optional),
- _inverse_event_shape_tensor,
- _inverse_event_shape (optional).
By default the event-shape is assumed unchanged from input.
- If the `Bijector`'s use is limited to `TransformedDistribution` (or friends
like `QuantizedDistribution`) then depending on your use, you may not need
to implement all of `_forward` and `_inverse` functions.
Examples:
1. Sampling (e.g., `sample`) only requires `_forward`.
2. Probability functions (e.g., `prob`, `cdf`, `survival`) only require
`_inverse` (and related).
3. Only calling probability functions on the output of `sample` means
`_inverse` can be implemented as a cache lookup.
See "Example Uses" [above] which shows how these functions are used to
transform a distribution. (Note: `_forward` could theoretically be
implemented as a cache lookup but this would require controlling the
underlying sample generation mechanism.)
#### Non Injective Transforms
**WARNING** Handing of non-injective transforms is subject to change.
Non injective maps `g` are supported, provided their domain `D` can be
partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
ignoring sets of measure zero, the restriction of `g` to each subset is a
differentiable bijection onto `g(D)`. In particular, this imples that for
`y in g(D)`, the set inverse, i.e. `g^{-1}(y) = {x in D : g(x) = y}`, always
contains exactly `k` distinct points.
The property, `_is_injective` is set to `False` to indicate that the bijector
is not injective, yet satisfies the above condition.
The usual bijector API is modified in the case `_is_injective is False` (see
method docstrings for specifics). Here we show by example the `AbsoluteValue`
bijector. In this case, the domain `D = (-inf, inf)`, can be partitioned
into `D1 = (-inf, 0)`, `D2 = {0}`, and `D3 = (0, inf)`. Let `gi` be the
restriction of `g` to `Di`, then both `g1` and `g3` are bijections onto
`(0, inf)`, with `g1^{-1}(y) = -y`, and `g3^{-1}(y) = y`. We will use
`g1` and `g3` to define bijector methods over `D1` and `D3`. `D2 = {0}` is
an oddball in that `g2` is one to one, and the derivative is not well defined.
Fortunately, when considering transformations of probability densities
(e.g. in `TransformedDistribution`), sets of measure zero have no effect in
theory, and only a small effect in 32 or 64 bit precision. For that reason,
we define `inverse(0)` and `inverse_log_det_jacobian(0)` both as `[0, 0]`,
which is convenient and results in a left-semicontinuous pdf.
```python
abs = tf.contrib.distributions.bijectors.AbsoluteValue()
abs.forward(-1.)
==> 1.
abs.forward(1.)
==> 1.
abs.inverse(1.)
==> (-1., 1.)
# The |dX/dY| is constant, == 1. So Log|dX/dY| == 0.
abs.inverse_log_det_jacobian(1.)
==> (0., 0.)
# Special case handling of 0.
abs.inverse(0.)
==> (0., 0.)
abs.inverse_log_det_jacobian(0.)
==> (0., 0.)
```
"""
@abc.abstractmethod
def __init__(self,
event_ndims=None,
graph_parents=None,
is_constant_jacobian=False,
validate_args=False,
dtype=None,
name=None):
"""Constructs Bijector.
A `Bijector` transforms random variables into new random variables.
Examples:
```python
# Create the Y = g(X) = X transform which operates on vector events.
identity = Identity(event_ndims=1)
# Create the Y = g(X) = exp(X) transform which operates on matrices.
exp = Exp(event_ndims=2)
```
See `Bijector` subclass docstring for more details and specific examples.
Args:
event_ndims: number of dimensions associated with event coordinates.
graph_parents: Python list of graph prerequisites of this `Bijector`.
is_constant_jacobian: Python `bool` indicating that the Jacobian is not a
function of the input.
validate_args: Python `bool`, default `False`. Whether to validate input
with asserts. If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
dtype: `tf.dtype` supported by this `Bijector`. `None` means dtype is not
enforced.
name: The name to give Ops created by the initializer.
Raises:
ValueError: If a member of `graph_parents` is not a `Tensor`.
"""
self._event_ndims = (
ops.convert_to_tensor(event_ndims, dtype=dtypes.int32)
if event_ndims is not None else None)
self._graph_parents = graph_parents or []
self._is_constant_jacobian = is_constant_jacobian
self._validate_args = validate_args
self._dtype = dtype
self._from_y = {}
self._from_x = {}
# Using abbreviation ildj for "inverse log det Jacobian."
# This variable is not `None` iff is_constant_jacobian is `True`.
self._constant_ildj = None
if name:
self._name = name
else:
# We want the default convention to be snake_case rather than CamelCase
# since `Chain` uses bijector.name as the kwargs dictionary key.
def camel_to_snake(name):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
self._name = camel_to_snake(type(self).__name__.lstrip("_"))
for i, t in enumerate(self._graph_parents):
if t is None or not tensor_util.is_tensor(t):
raise ValueError("Graph parent item %d is not a Tensor; %s." % (i, t))
@property
def event_ndims(self):
"""Returns then number of event dimensions this bijector operates on."""
return self._event_ndims
@property
def graph_parents(self):
"""Returns this `Bijector`'s graph_parents as a Python list."""
return self._graph_parents
@property
def is_constant_jacobian(self):
"""Returns true iff the Jacobian is not a function of x.
Note: Jacobian is either constant for both forward and inverse or neither.
Returns:
is_constant_jacobian: Python `bool`.
"""
return self._is_constant_jacobian
@property
def _is_injective(self):
"""Returns true iff the forward map `g` is injective (one-to-one function).
**WARNING** This hidden property and its behavior are subject to change.
Note: Non-injective maps `g` are supported, provided their domain `D` can
be partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
ignoring sets of measure zero, the restriction of `g` to each subset is a
differentiable bijection onto `g(D)`.
Returns:
is_injective: Python `bool`.
"""
return True
@property
def validate_args(self):
"""Returns True if Tensor arguments will be validated."""
return self._validate_args
@property
def dtype(self):
"""dtype of `Tensor`s transformable by this distribution."""
return self._dtype
@property
def name(self):
"""Returns the string name of this `Bijector`."""
return self._name
def _forward_event_shape_tensor(self, input_shape):
"""Subclass implementation for `forward_event_shape_tensor` function."""
# By default, we assume event_shape is unchanged.
return input_shape
def forward_event_shape_tensor(self,
input_shape,
name="forward_event_shape_tensor"):
"""Shape of a single sample from a single batch as an `int32` 1D `Tensor`.
Args:
input_shape: `Tensor`, `int32` vector indicating event-portion shape
passed into `forward` function.
name: name to give to the op
Returns:
forward_event_shape_tensor: `Tensor`, `int32` vector indicating
event-portion shape after applying `forward`.
"""
with self._name_scope(name, [input_shape]):
input_shape = ops.convert_to_tensor(input_shape, dtype=dtypes.int32,
name="input_shape")
return self._forward_event_shape_tensor(input_shape)
def _forward_event_shape(self, input_shape):
"""Subclass implementation for `forward_event_shape` public function."""
# By default, we assume event_shape is unchanged.
return input_shape
def forward_event_shape(self, input_shape):
"""Shape of a single sample from a single batch as a `TensorShape`.
Same meaning as `forward_event_shape_tensor`. May be only partially defined.
Args:
input_shape: `TensorShape` indicating event-portion shape passed into
`forward` function.
Returns:
forward_event_shape_tensor: `TensorShape` indicating event-portion shape
after applying `forward`. Possibly unknown.
"""
return self._forward_event_shape(tensor_shape.TensorShape(input_shape))
def _inverse_event_shape_tensor(self, output_shape):
"""Subclass implementation for `inverse_event_shape_tensor` function."""
# By default, we assume event_shape is unchanged.
return output_shape
def inverse_event_shape_tensor(self,
output_shape,
name="inverse_event_shape_tensor"):
"""Shape of a single sample from a single batch as an `int32` 1D `Tensor`.
Args:
output_shape: `Tensor`, `int32` vector indicating event-portion shape
passed into `inverse` function.
name: name to give to the op
Returns:
inverse_event_shape_tensor: `Tensor`, `int32` vector indicating
event-portion shape after applying `inverse`.
"""
with self._name_scope(name, [output_shape]):
output_shape = ops.convert_to_tensor(output_shape, dtype=dtypes.int32,
name="output_shape")
return self._inverse_event_shape_tensor(output_shape)
def _inverse_event_shape(self, output_shape):
"""Subclass implementation for `inverse_event_shape` public function."""
# By default, we assume event_shape is unchanged.
return tensor_shape.TensorShape(output_shape)
def inverse_event_shape(self, output_shape):
"""Shape of a single sample from a single batch as a `TensorShape`.
Same meaning as `inverse_event_shape_tensor`. May be only partially defined.
Args:
output_shape: `TensorShape` indicating event-portion shape passed into
`inverse` function.
Returns:
inverse_event_shape_tensor: `TensorShape` indicating event-portion shape
after applying `inverse`. Possibly unknown.
"""
return self._inverse_event_shape(output_shape)
def _forward(self, x):
"""Subclass implementation for `forward` public function."""
raise NotImplementedError("forward not implemented.")
def _call_forward(self, x, name, **kwargs):
with self._name_scope(name, [x]):
x = ops.convert_to_tensor(x, name="x")
self._maybe_assert_dtype(x)
if not self._is_injective: # No caching for non-injective
return self._forward(x, **kwargs)
mapping = self._lookup(x=x, kwargs=kwargs)
if mapping.y is not None:
return mapping.y
mapping = mapping.merge(y=self._forward(x, **kwargs))
self._cache(mapping)
return mapping.y
def forward(self, x, name="forward"):
"""Returns the forward `Bijector` evaluation, i.e., X = g(Y).
Args:
x: `Tensor`. The input to the "forward" evaluation.
name: The name to give this op.
Returns:
`Tensor`.
Raises:
TypeError: if `self.dtype` is specified and `x.dtype` is not
`self.dtype`.
NotImplementedError: if `_forward` is not implemented.
"""
return self._call_forward(x, name)
def _inverse(self, y):
"""Subclass implementation for `inverse` public function."""
raise NotImplementedError("inverse not implemented")
def _call_inverse(self, y, name, **kwargs):
with self._name_scope(name, [y]):
y = ops.convert_to_tensor(y, name="y")
self._maybe_assert_dtype(y)
if not self._is_injective: # No caching for non-injective
return self._inverse(y, **kwargs)
mapping = self._lookup(y=y, kwargs=kwargs)
if mapping.x is not None:
return mapping.x
mapping = mapping.merge(x=self._inverse(y, **kwargs))
self._cache(mapping)
return mapping.x
def inverse(self, y, name="inverse"):
"""Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y).
Args:
y: `Tensor`. The input to the "inverse" evaluation.
name: The name to give this op.
Returns:
`Tensor`, if this bijector is injective.
If not injective, returns the k-tuple containing the unique
`k` points `(x1, ..., xk)` such that `g(xi) = y`.
Raises:
TypeError: if `self.dtype` is specified and `y.dtype` is not
`self.dtype`.
NotImplementedError: if `_inverse` is not implemented.
"""
return self._call_inverse(y, name)
def _inverse_log_det_jacobian(self, y):
"""Subclass implementation of `inverse_log_det_jacobian` public function."""
raise NotImplementedError("inverse_log_det_jacobian not implemented.")
def _call_inverse_log_det_jacobian(self, y, name, **kwargs):
with self._name_scope(name, [y]):
if self._constant_ildj is not None:
return self._constant_ildj
y = ops.convert_to_tensor(y, name="y")
self._maybe_assert_dtype(y)
if not self._is_injective: # No caching for non-injective
return self._inverse_log_det_jacobian(y, **kwargs)
mapping = self._lookup(y=y, kwargs=kwargs)
if mapping.ildj is not None:
return mapping.ildj
try:
x = None # Not needed; leave cache as is.
ildj = self._inverse_log_det_jacobian(y, **kwargs)
except NotImplementedError as original_exception:
try:
x = mapping.x if mapping.x is not None else self._inverse(y, **kwargs)
ildj = -self._forward_log_det_jacobian(x, **kwargs)
except NotImplementedError:
raise original_exception
mapping = mapping.merge(x=x, ildj=ildj)
self._cache(mapping)
if self.is_constant_jacobian:
self._constant_ildj = mapping.ildj
return mapping.ildj
def inverse_log_det_jacobian(self, y, name="inverse_log_det_jacobian"):
"""Returns the (log o det o Jacobian o inverse)(y).
Mathematically, returns: `log(det(dX/dY))(Y)`. (Recall that: `X=g^{-1}(Y)`.)
Note that `forward_log_det_jacobian` is the negative of this function,
evaluated at `g^{-1}(y)`.
Args:
y: `Tensor`. The input to the "inverse" Jacobian evaluation.
name: The name to give this op.
Returns:
`Tensor`, if this bijector is injective.
If not injective, returns the tuple of local log det
Jacobians, `log(det(Dg_i^{-1}(y)))`, where `g_i` is the restriction
of `g` to the `ith` partition `Di`.
Raises:
TypeError: if `self.dtype` is specified and `y.dtype` is not
`self.dtype`.
NotImplementedError: if `_inverse_log_det_jacobian` is not implemented.
"""
return self._call_inverse_log_det_jacobian(y, name)
def _forward_log_det_jacobian(self, x):
"""Subclass implementation of `forward_log_det_jacobian`."""
raise NotImplementedError(
"forward_log_det_jacobian not implemented.")
def _call_forward_log_det_jacobian(self, x, name, **kwargs):
with self._name_scope(name, [x]):
if self._constant_ildj is not None:
# Need "-1. *" to avoid invalid-unary-operand-type linter warning.
return -1. * self._constant_ildj
x = ops.convert_to_tensor(x, name="x")
self._maybe_assert_dtype(x)
if not self._is_injective:
return self._forward_log_det_jacobian(x, **kwargs) # No caching.
mapping = self._lookup(x=x, kwargs=kwargs)
if mapping.ildj is not None:
return -mapping.ildj
try:
y = None # Not needed; leave cache as is.
ildj = -self._forward_log_det_jacobian(x, **kwargs)
except NotImplementedError as original_exception:
try:
y = mapping.y if mapping.y is not None else self._forward(x, **kwargs)
ildj = self._inverse_log_det_jacobian(y, **kwargs)
except NotImplementedError:
raise original_exception
mapping = mapping.merge(y=y, ildj=ildj)
self._cache(mapping)
if self.is_constant_jacobian:
self._constant_ildj = mapping.ildj
return -mapping.ildj
def forward_log_det_jacobian(self, x, name="forward_log_det_jacobian"):
"""Returns both the forward_log_det_jacobian.
Args:
x: `Tensor`. The input to the "forward" Jacobian evaluation.
name: The name to give this op.
Returns:
`Tensor`, if this bijector is injective.
If not injective this is not implemented.
Raises:
TypeError: if `self.dtype` is specified and `y.dtype` is not
`self.dtype`.
NotImplementedError: if neither `_forward_log_det_jacobian`
nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented, or
this is a non-injective bijector.
"""
if not self._is_injective:
raise NotImplementedError(
"forward_log_det_jacobian cannot be implemented for non-injective "
"transforms.")
return self._call_forward_log_det_jacobian(x, name)
@contextlib.contextmanager
def _name_scope(self, name=None, values=None):
"""Helper function to standardize op scope."""
with ops.name_scope(self.name):
with ops.name_scope(
name, values=(values or []) + self.graph_parents) as scope:
yield scope
def _maybe_assert_dtype(self, x):
"""Helper to check dtype when self.dtype is known."""
if self.dtype is not None and self.dtype.base_dtype != x.dtype.base_dtype:
raise TypeError("Input had dtype %s but expected %s." %
(self.dtype, x.dtype))
def _cache(self, mapping):
"""Helper which stores mapping info in forward/inverse dicts."""
if self._constant_ildj is not None:
# Fold in ildj if known constant Jacobian.
mapping = mapping.merge(ildj=self._constant_ildj)
# Merging from lookup is an added check that we're not overwriting anything
# which is not None.
mapping = mapping.merge(mapping=self._lookup(
mapping.x, mapping.y, mapping.kwargs))
if mapping.x is None and mapping.y is None:
raise ValueError("Caching expects at least one of (x,y) to be known, "
"i.e., not None.")
self._from_x[mapping.x_key] = mapping
self._from_y[mapping.y_key] = mapping
def _lookup(self, x=None, y=None, kwargs=None):
"""Helper which retrieves mapping info from forward/inverse dicts."""
mapping = _Mapping(x=x, y=y, kwargs=kwargs)
# Since _cache requires both x,y to be set, we only need to do one cache
# lookup since the mapping is always in both or neither.
if mapping.x is not None:
return self._from_x.get(mapping.x_key, mapping)
if mapping.y is not None:
return self._from_y.get(mapping.y_key, mapping)
return mapping
def _event_dims_tensor(self, sample):
"""Return a 1D `int32` tensor: `range(rank(sample))[-event_ndims:]`."""
if self.event_ndims is None:
raise ValueError("Jacobian cannot be computed with unknown event_ndims")
static_event_ndims = tensor_util.constant_value(self.event_ndims)
static_rank = sample.get_shape().ndims
if static_event_ndims is not None and static_rank is not None:
return ops.convert_to_tensor(
static_rank + np.arange(-static_event_ndims, 0).astype(np.int32))
if static_event_ndims is not None:
event_range = np.arange(-static_event_ndims, 0).astype(np.int32)
else:
event_range = math_ops.range(-self.event_ndims, 0, dtype=dtypes.int32)
if static_rank is not None:
return event_range + static_rank
else:
return event_range + array_ops.rank(sample)
|
{
"content_hash": "1ddbb5f3441919d229db3ce89720d274",
"timestamp": "",
"source": "github",
"line_count": 813,
"max_line_length": 80,
"avg_line_length": 35.779827798277985,
"alnum_prop": 0.6465674309876586,
"repo_name": "rabipanda/tensorflow",
"id": "44d64070ce48c0c115ea7edb1237124bc6698e90",
"size": "29778",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tensorflow/python/ops/distributions/bijector_impl.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9008"
},
{
"name": "C",
"bytes": "332772"
},
{
"name": "C++",
"bytes": "36554246"
},
{
"name": "CMake",
"bytes": "190994"
},
{
"name": "Go",
"bytes": "1058787"
},
{
"name": "HTML",
"bytes": "4680032"
},
{
"name": "Java",
"bytes": "543556"
},
{
"name": "Jupyter Notebook",
"bytes": "1940884"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "49545"
},
{
"name": "Objective-C",
"bytes": "12456"
},
{
"name": "Objective-C++",
"bytes": "94526"
},
{
"name": "PHP",
"bytes": "1487"
},
{
"name": "Perl",
"bytes": "6179"
},
{
"name": "Perl 6",
"bytes": "1357"
},
{
"name": "PureBasic",
"bytes": "24932"
},
{
"name": "Python",
"bytes": "32129142"
},
{
"name": "Ruby",
"bytes": "547"
},
{
"name": "Shell",
"bytes": "412473"
}
],
"symlink_target": ""
}
|
using Xunit;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.IO
{
/// <summary>Base class for test classes the use temporary files that need to be cleaned up.</summary>
public abstract class FileCleanupTestBase : IDisposable
{
/// <summary>Initialize the test class base. This creates the associated test directory.</summary>
protected FileCleanupTestBase()
{
// Use a unique test directory per test class. The test directory lives in the user's temp directory,
// and includes both the name of the test class and a random string. The test class name is included
// so that it can be easily correlated if necessary, and the random string to helps avoid conflicts if
// the same test should be run concurrently with itself (e.g. if a [Fact] method lives on a base class)
// or if some stray files were left over from a previous run.
// Make 3 attempts since we have seen this on rare occasions fail with access denied, perhaps due to machine
// configuration, and it doesn't make sense to fail arbitrary tests for this reason.
string failure = string.Empty;
for (int i = 0; i <= 2; i++)
{
TestDirectory = Path.Combine(Path.GetTempPath(), GetType().Name + "_" + Path.GetRandomFileName());
try
{
Directory.CreateDirectory(TestDirectory);
break;
}
catch (Exception ex)
{
failure += ex.ToString() + Environment.NewLine;
Thread.Sleep(10); // Give a transient condition like antivirus/indexing a chance to go away
}
}
Assert.True(Directory.Exists(TestDirectory), $"FileCleanupTestBase failed to create {TestDirectory}. {failure}");
}
/// <summary>Delete the associated test directory.</summary>
~FileCleanupTestBase()
{
Dispose(false);
}
/// <summary>Delete the associated test directory.</summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>Delete the associated test directory.</summary>
protected virtual void Dispose(bool disposing)
{
// No managed resources to clean up, so disposing is ignored.
try { Directory.Delete(TestDirectory, recursive: true); }
catch { } // avoid exceptions escaping Dispose
}
/// <summary>Gets the test directory into which all files and directories created by tests should be stored.</summary>
protected string TestDirectory { get; }
/// <summary>Gets a test file full path that is associated with the call site.</summary>
/// <param name="index">An optional index value to use as a suffix on the file name. Typically a loop index.</param>
/// <param name="memberName">The member name of the function calling this method.</param>
/// <param name="lineNumber">The line number of the function calling this method.</param>
protected string GetTestFilePath(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) =>
Path.Combine(TestDirectory, GetTestFileName(index, memberName, lineNumber));
/// <summary>Gets a test file name that is associated with the call site.</summary>
/// <param name="index">An optional index value to use as a suffix on the file name. Typically a loop index.</param>
/// <param name="memberName">The member name of the function calling this method.</param>
/// <param name="lineNumber">The line number of the function calling this method.</param>
protected string GetTestFileName(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) =>
string.Format(index.HasValue ? "{0}_{1}_{2}" : "{0}_{1}", memberName ?? "TestBase", lineNumber, index.GetValueOrDefault());
}
}
|
{
"content_hash": "f18521ff6720039f2b2fc9ac3dbfdf03",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 146,
"avg_line_length": 52.74683544303797,
"alnum_prop": 0.6299496040316774,
"repo_name": "Petermarcu/corefx",
"id": "6e218ae3311bac3e64c24f45492da8036cf107e0",
"size": "4371",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/Common/tests/System/IO/FileCleanupTestBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "903"
},
{
"name": "ASP",
"bytes": "1687"
},
{
"name": "Batchfile",
"bytes": "23904"
},
{
"name": "C",
"bytes": "1113487"
},
{
"name": "C#",
"bytes": "132229022"
},
{
"name": "C++",
"bytes": "710301"
},
{
"name": "CMake",
"bytes": "63838"
},
{
"name": "DIGITAL Command Language",
"bytes": "26402"
},
{
"name": "Groovy",
"bytes": "35193"
},
{
"name": "HTML",
"bytes": "653"
},
{
"name": "Makefile",
"bytes": "9085"
},
{
"name": "Objective-C",
"bytes": "9948"
},
{
"name": "OpenEdge ABL",
"bytes": "139178"
},
{
"name": "Perl",
"bytes": "3895"
},
{
"name": "PowerShell",
"bytes": "42677"
},
{
"name": "Python",
"bytes": "1535"
},
{
"name": "Roff",
"bytes": "4236"
},
{
"name": "Shell",
"bytes": "74492"
},
{
"name": "Visual Basic",
"bytes": "827869"
},
{
"name": "XSLT",
"bytes": "462336"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_202) on Sat Aug 31 14:06:17 COT 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WaitingSupport</title>
<meta name="date" content="2019-08-31">
<meta name="keywords" content="com.github.epadronu.balin.core.WaitingSupport interface">
<meta name="keywords" content="getDriver()">
<meta name="keywords" content="getConfigurationSetup()">
<meta name="keywords" content="waitFor()">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="WaitingSupport";
}
}
catch(err) {
}
//-->
var methods = {"i0":18,"i1":18,"i2":18};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/github/epadronu/balin/core/Page.html" title="class in com.github.epadronu.balin.core"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/github/epadronu/balin/core/WaitingSupport.html" target="_top">Frames</a></li>
<li><a href="WaitingSupport.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: </li>
<li><a href="#nested.class.summary">Nested</a> | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </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">com.github.epadronu.balin.core</div>
<h2 title="Interface WaitingSupport" class="title">Interface WaitingSupport</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Subinterfaces:</dt>
<dd><a href="../../../../../com/github/epadronu/balin/core/Browser.html" title="interface in com.github.epadronu.balin.core">Browser</a></dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../com/github/epadronu/balin/core/Component.html" title="class in com.github.epadronu.balin.core">Component</a>, <a href="../../../../../com/github/epadronu/balin/core/Page.html" title="class in com.github.epadronu.balin.core">Page</a></dd>
</dl>
<hr>
<br>
<pre>public <span class="typeNameLabel">WaitingSupport</span></pre>
<div class="block"><p><p>Describes the <code>waitFor</code> method support, which aims to ease the use of
<a href="https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html">WebDriverWait</a>.</p></p><p><p><code><pre>// Given the selector of an element that should be present
val locator = By.cssSelector(".global-header-logo")
try {
Browser.drive(driverFactory) {
// When I navigate to the Kotlin's page URL
to("https://kotlinlang.org/")
// And I wait for the element located by such selector to be present
waitFor { ExpectedConditions.presenceOfElementLocated(locator) }
}
} catch (ignore: TimeoutException) {
// Then I should wait until the element appears in the page
fail("An unexpected exception was thrown")
}</pre></code></p></p></div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html">WebDriverWait</a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Interface and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/github/epadronu/balin/core/WaitingSupport.DefaultImpls.html" title="class in com.github.epadronu.balin.core">WaitingSupport.DefaultImpls</a></span></code>
<div class="block">Describes the <code>waitFor</code> method support, which aims to ease the use of
<a href="https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html">WebDriverWait</a>.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../com/github/epadronu/balin/config/ConfigurationSetup.html" title="type parameter in ConfigurationSetup">ConfigurationSetup</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/github/epadronu/balin/core/WaitingSupport.html#getConfigurationSetup--">getConfigurationSetup</a></span>()</code>
<div class="block">The configuration setup used to customized Balin's behavior.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>org.openqa.selenium.WebDriver</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/github/epadronu/balin/core/WaitingSupport.html#getDriver--">getDriver</a></span>()</code>
<div class="block">The driver to be used when evaluating <code>isTrue</code> in <a href="../../../../../com/github/epadronu/balin/core/WaitingSupport.html#waitFor-timeOutInSeconds-sleepInMillis-isTrue-"><code>waitFor</code></a>.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><T> T</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/github/epadronu/balin/core/WaitingSupport.html#waitFor-timeOutInSeconds-sleepInMillis-isTrue-">waitFor</a></span>(long timeOutInSeconds,
long sleepInMillis,
kotlin.jvm.functions.Function0<? extends org.openqa.selenium.support.ui.ExpectedCondition<T>> isTrue)</code>
<div class="block">Repeatedly applies the underlying driver to the given function until
one of the following occurs:</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="getDriver--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDriver</h4>
<pre>@NotNull
org.openqa.selenium.WebDriver getDriver()</pre>
<div class="block"><p><p>The driver to be used when evaluating <code>isTrue</code> in <a href="../../../../../com/github/epadronu/balin/core/WaitingSupport.html#waitFor-timeOutInSeconds-sleepInMillis-isTrue-"><code>waitFor</code></a>.</p></p></div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../com/github/epadronu/balin/core/WaitingSupport.html#waitFor-timeOutInSeconds-sleepInMillis-isTrue-"><code>waitFor</code></a></dd>
</dl>
</li>
</ul>
<a name="getConfigurationSetup--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getConfigurationSetup</h4>
<pre>@NotNull
<a href="../../../../../com/github/epadronu/balin/config/ConfigurationSetup.html" title="type parameter in ConfigurationSetup">ConfigurationSetup</a> getConfigurationSetup()</pre>
<div class="block"><p><p>The configuration setup used to customized Balin's behavior.</p></p></div>
</li>
</ul>
<a name="waitFor-timeOutInSeconds-sleepInMillis-isTrue-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>waitFor</h4>
<pre><T> T waitFor(long timeOutInSeconds,
long sleepInMillis,
@NotNull
kotlin.jvm.functions.Function0<? extends org.openqa.selenium.support.ui.ExpectedCondition<T>> isTrue)</pre>
<div class="block"><p><p>Repeatedly applies the underlying driver to the given function until
one of the following occurs:</p></p><p><p><ol><li><p>the function returns neither null nor false</p></li><li><p>the function throws an unignored exception</p></li><li><p>the timeout expires</p></li><li><p>the current thread is interrupted</p></li></ol></p></p></div>
<dl>
<dt><span class="paramLabel">Type Parameters:</span></dt>
<dd><code>T</code> - <p>the function's expected return type.</p></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>timeOutInSeconds</code> - the timeout in seconds when an expectation is called.</dd>
<dd><code>sleepInMillis</code> - the duration in milliseconds to sleep between polls.</dd>
<dd><code>isTrue</code> - the parameter to pass to the ExpectedCondition.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The function's return value if the function returned something different from null or false before the timeout expired.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/github/epadronu/balin/core/Page.html" title="class in com.github.epadronu.balin.core"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/github/epadronu/balin/core/WaitingSupport.html" target="_top">Frames</a></li>
<li><a href="WaitingSupport.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: </li>
<li><a href="#nested.class.summary">Nested</a> | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"content_hash": "259d07a5a2738ea6b17eecf1f147fa4a",
"timestamp": "",
"source": "github",
"line_count": 332,
"max_line_length": 391,
"avg_line_length": 41.94578313253012,
"alnum_prop": 0.6595576619273301,
"repo_name": "EPadronU/balin",
"id": "30d78c475b29d5a009bdab8b136753bf3d8cbb0b",
"size": "13926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/java/api/com/github/epadronu/balin/core/WaitingSupport.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3880"
},
{
"name": "Kotlin",
"bytes": "173621"
}
],
"symlink_target": ""
}
|
import pytest
from parameterized import parameterized
from airflow.plugins_manager import AirflowPlugin
from airflow.security import permissions
from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
from tests.test_utils.config import conf_vars
from tests.test_utils.mock_plugins import mock_plugin_manager
@pytest.fixture(scope="module")
def configured_app(minimal_app_for_api):
app = minimal_app_for_api
create_user(
app, # type: ignore
username="test",
role_name="Test",
permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_PLUGIN)],
)
create_user(app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore
yield app
delete_user(app, username="test") # type: ignore
delete_user(app, username="test_no_permissions") # type: ignore
class TestPluginsEndpoint:
@pytest.fixture(autouse=True)
def setup_attrs(self, configured_app) -> None:
"""
Setup For XCom endpoint TC
"""
self.app = configured_app
self.client = self.app.test_client() # type:ignore
class TestGetPlugins(TestPluginsEndpoint):
def test_get_plugins_return_200(self):
mock_plugin = AirflowPlugin()
mock_plugin.name = "test_plugin"
with mock_plugin_manager(plugins=[mock_plugin]):
response = self.client.get("api/v1/plugins", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert response.json == {
'plugins': [
{
'appbuilder_menu_items': [],
'appbuilder_views': [],
'executors': [],
'flask_blueprints': [],
'global_operator_extra_links': [],
'hooks': [],
'macros': [],
'operator_extra_links': [],
'source': None,
'name': 'test_plugin',
}
],
'total_entries': 1,
}
def test_get_plugins_works_with_more_plugins(self):
mock_plugin = AirflowPlugin()
mock_plugin.name = "test_plugin"
mock_plugin_2 = AirflowPlugin()
mock_plugin_2.name = "test_plugin2"
with mock_plugin_manager(plugins=[mock_plugin, mock_plugin_2]):
response = self.client.get("api/v1/plugins", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert response.json["total_entries"] == 2
def test_get_plugins_return_200_if_no_plugins(self):
with mock_plugin_manager(plugins=[]):
response = self.client.get("api/v1/plugins", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
def test_should_raises_401_unauthenticated(self):
response = self.client.get("/api/v1/plugins")
assert_401(response)
def test_should_raise_403_forbidden(self):
response = self.client.get(
"/api/v1/plugins", environ_overrides={'REMOTE_USER': "test_no_permissions"}
)
assert response.status_code == 403
class TestGetPluginsPagination(TestPluginsEndpoint):
@parameterized.expand(
[
("/api/v1/plugins?limit=1", ['TEST_PLUGIN_1']),
("/api/v1/plugins?limit=2", ['TEST_PLUGIN_1', "TEST_PLUGIN_2"]),
(
"/api/v1/plugins?offset=5",
[
"TEST_PLUGIN_6",
"TEST_PLUGIN_7",
"TEST_PLUGIN_8",
"TEST_PLUGIN_9",
"TEST_PLUGIN_10",
],
),
(
"/api/v1/plugins?offset=0",
[
"TEST_PLUGIN_1",
"TEST_PLUGIN_2",
"TEST_PLUGIN_3",
"TEST_PLUGIN_4",
"TEST_PLUGIN_5",
"TEST_PLUGIN_6",
"TEST_PLUGIN_7",
"TEST_PLUGIN_8",
"TEST_PLUGIN_9",
"TEST_PLUGIN_10",
],
),
("/api/v1/plugins?limit=1&offset=5", ["TEST_PLUGIN_6"]),
("/api/v1/plugins?limit=1&offset=1", ["TEST_PLUGIN_2"]),
(
"/api/v1/plugins?limit=2&offset=2",
["TEST_PLUGIN_3", "TEST_PLUGIN_4"],
),
]
)
def test_handle_limit_offset(self, url, expected_plugin_names):
plugins = self._create_plugins(10)
with mock_plugin_manager(plugins=plugins):
response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert response.json["total_entries"] == 10
plugin_names = [plugin['name'] for plugin in response.json['plugins'] if plugin]
assert plugin_names == expected_plugin_names
def test_should_respect_page_size_limit_default(self):
plugins = self._create_plugins(200)
with mock_plugin_manager(plugins=plugins):
response = self.client.get("/api/v1/plugins", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert response.json["total_entries"] == 200
assert len(response.json["plugins"]) == 100
def test_limit_of_zero_should_return_default(self):
plugins = self._create_plugins(200)
with mock_plugin_manager(plugins=plugins):
response = self.client.get("/api/v1/plugins?limit=0", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert response.json["total_entries"] == 200
assert len(response.json["plugins"]) == 100
@conf_vars({("api", "maximum_page_limit"): "150"})
def test_should_return_conf_max_if_req_max_above_conf(self):
plugins = self._create_plugins(200)
with mock_plugin_manager(plugins=plugins):
response = self.client.get("/api/v1/plugins?limit=180", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert len(response.json['plugins']) == 150
def _create_plugins(self, count):
plugins = []
for i in range(1, count + 1):
mock_plugin = AirflowPlugin()
mock_plugin.name = f"TEST_PLUGIN_{i}"
plugins.append(mock_plugin)
return plugins
|
{
"content_hash": "ca549f689f212677644bb790042cc92a",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 110,
"avg_line_length": 38.5748502994012,
"alnum_prop": 0.5605402049053089,
"repo_name": "Acehaidrey/incubator-airflow",
"id": "669a2f31e294e2c19c0324c5bb89ca54080299ff",
"size": "7229",
"binary": false,
"copies": "8",
"ref": "refs/heads/main",
"path": "tests/api_connexion/endpoints/test_plugin_endpoint.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25785"
},
{
"name": "Dockerfile",
"bytes": "76693"
},
{
"name": "HCL",
"bytes": "3786"
},
{
"name": "HTML",
"bytes": "164512"
},
{
"name": "JavaScript",
"bytes": "236992"
},
{
"name": "Jinja",
"bytes": "37155"
},
{
"name": "Jupyter Notebook",
"bytes": "2929"
},
{
"name": "Mako",
"bytes": "1339"
},
{
"name": "Python",
"bytes": "21727510"
},
{
"name": "R",
"bytes": "313"
},
{
"name": "Shell",
"bytes": "495253"
},
{
"name": "TypeScript",
"bytes": "326556"
}
],
"symlink_target": ""
}
|
#define WINVER 0x0501 /* MingW32 */
#define _WIN32_WINNT 0x0501 /* ACTCTX stuff */
#include "tkTreeCtrl.h"
#include "tkWinInt.h"
/*
*----------------------------------------------------------------------
*
* Tree_HDotLine --
*
* Draws a horizontal 1-pixel-tall dotted line.
*
* Results:
* None.
*
* Side effects:
* Stuff is drawn.
*
*----------------------------------------------------------------------
*/
void
Tree_HDotLine(
TreeCtrl *tree, /* Widget info. */
Drawable drawable, /* Where to draw. */
int x1, int y1, int x2 /* Left, top and right coordinates. */
)
{
TkWinDCState state;
HDC dc;
HPEN pen, oldPen;
int nw;
int wx = x1 + tree->drawableXOrigin;
int wy = y1 + tree->drawableYOrigin;
dc = TkWinGetDrawableDC(tree->display, drawable, &state);
SetROP2(dc, R2_COPYPEN);
pen = CreatePen(PS_SOLID, 1, tree->lineGC[0]->foreground);
oldPen = SelectObject(dc, pen);
nw = !(wx & 1) == !(wy & 1);
for (x1 += !nw; x1 < x2; x1 += 2) {
MoveToEx(dc, x1, y1, NULL);
LineTo(dc, x1 + 1, y1);
}
SelectObject(dc, oldPen);
DeleteObject(pen);
TkWinReleaseDrawableDC(drawable, dc, &state);
}
/*
*----------------------------------------------------------------------
*
* Tree_VDotLine --
*
* Draws a vertical 1-pixel-wide dotted line.
*
* Results:
* None.
*
* Side effects:
* Stuff is drawn.
*
*----------------------------------------------------------------------
*/
void
Tree_VDotLine(
TreeCtrl *tree, /* Widget info. */
Drawable drawable, /* Where to draw. */
int x1, int y1, int y2) /* Left, top, and bottom coordinates. */
{
TkWinDCState state;
HDC dc;
HPEN pen, oldPen;
int nw;
int wx = x1 + tree->drawableXOrigin;
int wy = y1 + tree->drawableYOrigin;
dc = TkWinGetDrawableDC(tree->display, drawable, &state);
SetROP2(dc, R2_COPYPEN);
pen = CreatePen(PS_SOLID, 1, tree->lineGC[0]->foreground);
oldPen = SelectObject(dc, pen);
nw = !(wx & 1) == !(wy & 1);
for (y1 += !nw; y1 < y2; y1 += 2) {
MoveToEx(dc, x1, y1, NULL);
LineTo(dc, x1 + 1, y1);
}
SelectObject(dc, oldPen);
DeleteObject(pen);
TkWinReleaseDrawableDC(drawable, dc, &state);
}
/*
*----------------------------------------------------------------------
*
* Tree_DrawActiveOutline --
*
* Draws 0 or more sides of a rectangle, dot-on dot-off, XOR style.
* This is used by rectangle Elements to indicate the "active"
* item.
*
* Results:
* None.
*
* Side effects:
* Stuff is drawn.
*
*----------------------------------------------------------------------
*/
void
Tree_DrawActiveOutline(
TreeCtrl *tree, /* Widget info. */
Drawable drawable, /* Where to draw. */
int x, int y, /* Left and top coordinates. */
int width, int height, /* Size of rectangle. */
int open /* RECT_OPEN_x flags */
)
{
int wx = x + tree->drawableXOrigin;
int wy = y + tree->drawableYOrigin;
int w = !(open & RECT_OPEN_W);
int n = !(open & RECT_OPEN_N);
int e = !(open & RECT_OPEN_E);
int s = !(open & RECT_OPEN_S);
int nw, ne, sw, se;
int i;
TkWinDCState state;
HDC dc;
/* Dots on even pixels only */
nw = !(wx & 1) == !(wy & 1);
ne = !((wx + width - 1) & 1) == !(wy & 1);
sw = !(wx & 1) == !((wy + height - 1) & 1);
se = !((wx + width - 1) & 1) == !((wy + height - 1) & 1);
dc = TkWinGetDrawableDC(tree->display, drawable, &state);
SetROP2(dc, R2_NOT);
if (w) /* left */
{
for (i = !nw; i < height; i += 2) {
MoveToEx(dc, x, y + i, NULL);
LineTo(dc, x + 1, y + i);
}
}
if (n) /* top */
{
for (i = nw ? w * 2 : 1; i < width; i += 2) {
MoveToEx(dc, x + i, y, NULL);
LineTo(dc, x + i + 1, y);
}
}
if (e) /* right */
{
for (i = ne ? n * 2 : 1; i < height; i += 2) {
MoveToEx(dc, x + width - 1, y + i, NULL);
LineTo(dc, x + width, y + i);
}
}
if (s) /* bottom */
{
for (i = sw ? w * 2 : 1; i < width - (se && e); i += 2) {
MoveToEx(dc, x + i, y + height - 1, NULL);
LineTo(dc, x + i + 1, y + height - 1);
}
}
TkWinReleaseDrawableDC(drawable, dc, &state);
}
/*
* The following structure is used when drawing a number of dotted XOR
* rectangles.
*/
struct DotStatePriv
{
TreeCtrl *tree;
Drawable drawable;
HDC dc;
TkWinDCState dcState;
HRGN rgn;
};
/*
*----------------------------------------------------------------------
*
* TreeDotRect_Setup --
*
* Prepare a drawable for drawing a series of dotted XOR rectangles.
*
* Results:
* State info is returned to be used by the other TreeDotRect_xxx()
* procedures.
*
* Side effects:
* On Win32 and OSX the device context/graphics port is altered
* in preparation for drawing. On X11 a new graphics context is
* created.
*
*----------------------------------------------------------------------
*/
void
TreeDotRect_Setup(
TreeCtrl *tree, /* Widget info. */
Drawable drawable, /* Where to draw. */
DotState *p /* Where to save state info. */
)
{
struct DotStatePriv *dotState = (struct DotStatePriv *) p;
if (sizeof(*dotState) > sizeof(*p))
panic("TreeDotRect_Setup: DotState hack is too small");
dotState->tree = tree;
dotState->drawable = drawable;
dotState->dc = TkWinGetDrawableDC(tree->display, drawable, &dotState->dcState);
/* XOR drawing */
SetROP2(dotState->dc, R2_NOT);
/* Keep drawing inside the contentbox. */
dotState->rgn = CreateRectRgn(
Tree_ContentLeft(tree),
Tree_ContentTop(tree),
Tree_ContentRight(tree),
Tree_ContentBottom(tree));
SelectClipRgn(dotState->dc, dotState->rgn);
}
/*
*----------------------------------------------------------------------
*
* TreeDotRect_Draw --
*
* Draw a dotted XOR rectangle.
*
* Results:
* None.
*
* Side effects:
* Stuff is drawn.
*
*----------------------------------------------------------------------
*/
void
TreeDotRect_Draw(
DotState *p, /* Info returned by TreeDotRect_Setup(). */
int x, int y, /* Left and top coordinates. */
int width, int height /* Size of rectangle. */
)
{
struct DotStatePriv *dotState = (struct DotStatePriv *) p;
#if 1
RECT rect;
rect.left = x;
rect.right = x + width;
rect.top = y;
rect.bottom = y + height;
DrawFocusRect(dotState->dc, &rect);
#else
HDC dc = dotState->dc;
int i;
int wx = x + dotState->tree->drawableXOrigin;
int wy = y + dotState->tree->drawableYOrigin;
int nw, ne, sw, se;
/* Dots on even pixels only */
nw = !(wx & 1) == !(wy & 1);
ne = !((wx + width - 1) & 1) == !(wy & 1);
sw = !(wx & 1) == !((wy + height - 1) & 1);
se = !((wx + width - 1) & 1) == !((wy + height - 1) & 1);
for (i = !nw; i < height; i += 2) {
MoveToEx(dc, x, y + i, NULL);
LineTo(dc, x + 1, y + i);
}
for (i = nw ? 2 : 1; i < width; i += 2) {
MoveToEx(dc, x + i, y, NULL);
LineTo(dc, x + i + 1, y);
}
for (i = ne ? 2 : 1; i < height; i += 2) {
MoveToEx(dc, x + width - 1, y + i, NULL);
LineTo(dc, x + width, y + i);
}
for (i = sw ? 2 : 1; i < width - se; i += 2) {
MoveToEx(dc, x + i, y + height - 1, NULL);
LineTo(dc, x + i + 1, y + height - 1);
}
#endif
}
/*
*----------------------------------------------------------------------
*
* TreeDotRect_Restore --
*
* Restore the drawing environment.
*
* Results:
* None.
*
* Side effects:
* On Win32 and OSX the device context/graphics port is restored.
* On X11 a new graphics context is freed.
*
*----------------------------------------------------------------------
*/
void
TreeDotRect_Restore(
DotState *p /* Info returned by TreeDotRect_Setup(). */
)
{
struct DotStatePriv *dotState = (struct DotStatePriv *) p;
SelectClipRgn(dotState->dc, NULL);
DeleteObject(dotState->rgn);
TkWinReleaseDrawableDC(dotState->drawable, dotState->dc, &dotState->dcState);
}
/*
*----------------------------------------------------------------------
*
* Tree_FillRegion --
*
* Paint a region with the foreground color of a graphics context.
*
* Results:
* None.
*
* Side effects:
* Stuff is drawn.
*
*----------------------------------------------------------------------
*/
void
Tree_FillRegion(
Display *display, /* Display. */
Drawable drawable, /* Where to draw. */
GC gc, /* Foreground color. */
TkRegion rgn /* Region to paint. */
)
{
HDC dc;
TkWinDCState dcState;
HBRUSH brush;
dc = TkWinGetDrawableDC(display, drawable, &dcState);
SetROP2(dc, R2_COPYPEN);
brush = CreateSolidBrush(gc->foreground);
FillRgn(dc, (HRGN) rgn, brush);
DeleteObject(brush);
TkWinReleaseDrawableDC(drawable, dc, &dcState);
}
/*
*----------------------------------------------------------------------
*
* Tree_OffsetRegion --
*
* Offset a region.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
Tree_OffsetRegion(
TkRegion region, /* Region to modify. */
int xOffset, int yOffset /* Horizontal and vertical offsets. */
)
{
OffsetRgn((HRGN) region, xOffset, yOffset);
}
/*
*----------------------------------------------------------------------
*
* Tree_UnionRegion --
*
* Compute the union of 2 regions.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
Tree_UnionRegion(
TkRegion rgnA,
TkRegion rgnB,
TkRegion rgnOut
)
{
CombineRgn((HRGN) rgnA, (HRGN) rgnB, (HRGN) rgnOut, RGN_OR);
}
/*
*----------------------------------------------------------------------
*
* Tree_ScrollWindow --
*
* Wrapper around TkScrollWindow() to fix an apparent bug with the
* Mac/OSX versions.
*
* Results:
* None.
*
* Side effects:
* Stuff is scrolled in a drawable.
*
*----------------------------------------------------------------------
*/
int
Tree_ScrollWindow(
TreeCtrl *tree, /* Widget info. */
GC gc, /* Arg to TkScrollWindow(). */
int x, int y, /* Arg to TkScrollWindow(). */
int width, int height, /* Arg to TkScrollWindow(). */
int dx, int dy, /* Arg to TkScrollWindow(). */
TkRegion damageRgn /* Arg to TkScrollWindow(). */
)
{
#if 0
/* It would be best to call ScrollWindowEx with SW_SCROLLCHILDREN so
* that windows in window elements scroll smoothly with a minimum of
* redrawing. */
HWND hwnd = TkWinGetHWND(Tk_WindowId(tree->tkwin));
HWND hwndChild;
RECT scrollRect, childRect;
struct {
int x;
int y;
TkWindow *winPtr;
} winInfo[128], *winInfoPtr;
TkWindow *winPtr = (TkWindow *) tree->tkwin;
int winCount = 0;
int result;
winInfoPtr = winInfo;
for (winPtr = winPtr->childList; winPtr != NULL; winPtr = winPtr->nextPtr) {
if (winPtr->window != None) {
hwndChild = TkWinGetHWND(winPtr->window);
GetWindowRect(hwndChild, &childRect);
winInfoPtr->x = childRect.left;
winInfoPtr->y = childRect.top;
winInfoPtr->winPtr = winPtr;
winInfoPtr++;
winCount++;
}
}
scrollRect.left = x;
scrollRect.top = y;
scrollRect.right = x + width;
scrollRect.bottom = y + height;
result = (ScrollWindowEx(hwnd, dx, dy, &scrollRect, NULL, (HRGN) damageRgn,
NULL, SW_SCROLLCHILDREN) == NULLREGION) ? 0 : 1;
winInfoPtr = winInfo;
while (winCount--) {
winPtr = winInfoPtr->winPtr;
hwndChild = TkWinGetHWND(winPtr->window);
GetWindowRect(hwndChild, &childRect);
if (childRect.left != winInfoPtr->x ||
childRect.top != winInfoPtr->y) {
dbwin("moved window %s %d,%d\n", winPtr->pathName, childRect.left - winInfoPtr->x, childRect.top - winInfoPtr->y);
winPtr->changes.x += childRect.left - winInfoPtr->x;
winPtr->changes.y += childRect.top - winInfoPtr->y;
/* TkDoConfigureNotify(winPtr); */
}
winInfoPtr++;
}
#else
int result = TkScrollWindow(tree->tkwin, gc, x, y, width, height, dx, dy,
damageRgn);
#endif
return result;
}
/*
*----------------------------------------------------------------------
*
* Tree_UnsetClipMask --
*
* Wrapper around XSetClipMask(). On Win32 Tk_DrawChars() does
* not clear the clipping region.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
Tree_UnsetClipMask(
TreeCtrl *tree, /* Widget info. */
Drawable drawable, /* Where to draw. */
GC gc /* Graphics context to modify. */
)
{
XSetClipMask(tree->display, gc, None);
/* Tk_DrawChars does not clear the clip region */
if (drawable == Tk_WindowId(tree->tkwin)) {
HDC dc;
TkWinDCState dcState;
dc = TkWinGetDrawableDC(tree->display, drawable, &dcState);
SelectClipRgn(dc, NULL);
TkWinReleaseDrawableDC(drawable, dc, &dcState);
}
}
/*
*----------------------------------------------------------------------
*
* Tree_DrawBitmapWithGC --
*
* Draw part of a bitmap.
*
* Results:
* None.
*
* Side effects:
* Stuff is drawn.
*
*----------------------------------------------------------------------
*/
void
Tree_DrawBitmapWithGC(
TreeCtrl *tree, /* Widget info. */
Pixmap bitmap, /* Bitmap to draw. */
Drawable drawable, /* Where to draw. */
GC gc, /* Graphics context. */
int src_x, int src_y, /* Left and top of part of bitmap to copy. */
int width, int height, /* Width and height of part of bitmap to
* copy. */
int dest_x, int dest_y /* Left and top coordinates to copy part of
* the bitmap to. */
)
{
TkpClipMask *clipPtr = (TkpClipMask *) gc->clip_mask;
XSetClipOrigin(tree->display, gc, dest_x, dest_y);
/*
* It seems as though the device context is not set up properly
* when drawing a transparent bitmap into a window. Normally Tk draws
* into an offscreen pixmap which gets a temporary device context.
* This fixes a bug with -doublebuffer none in the demo "Bitmaps".
*/
if (drawable == Tk_WindowId(tree->tkwin)) {
if ((clipPtr != NULL) &&
(clipPtr->type == TKP_CLIP_PIXMAP) &&
(clipPtr->value.pixmap == bitmap)) {
HDC dc;
TkWinDCState dcState;
dc = TkWinGetDrawableDC(tree->display, drawable, &dcState);
SetTextColor(dc, RGB(0,0,0));
SetBkColor(dc, RGB(255,255,255));
TkWinReleaseDrawableDC(drawable, dc, &dcState);
}
}
XCopyPlane(tree->display, bitmap, drawable, gc,
src_x, src_y, (unsigned int) width, (unsigned int) height,
dest_x, dest_y, 1);
XSetClipOrigin(tree->display, gc, 0, 0);
}
/*
* TIP #116 altered Tk_PhotoPutBlock API to add interp arg.
* We need to remove that for compiling with 8.4.
*/
#if (TK_MAJOR_VERSION == 8) && (TK_MINOR_VERSION < 5)
#define TK_PHOTOPUTBLOCK(interp, hdl, blk, x, y, w, h, cr) \
Tk_PhotoPutBlock(hdl, blk, x, y, w, h, cr)
#define TK_PHOTOPUTZOOMEDBLOCK(interp, hdl, blk, x, y, w, h, \
zx, zy, sx, sy, cr) \
Tk_PhotoPutZoomedBlock(hdl, blk, x, y, w, h, \
zx, zy, sx, sy, cr)
#else
#define TK_PHOTOPUTBLOCK Tk_PhotoPutBlock
#define TK_PHOTOPUTZOOMEDBLOCK Tk_PhotoPutZoomedBlock
#endif
/*
*----------------------------------------------------------------------
*
* Tree_XImage2Photo --
*
* Copy pixels from an XImage to a Tk photo image.
*
* Results:
* None.
*
* Side effects:
* The given photo image is blanked and all the pixels from the
* XImage are put into the photo image.
*
*----------------------------------------------------------------------
*/
void
Tree_XImage2Photo(
Tcl_Interp *interp, /* Current interpreter. */
Tk_PhotoHandle photoH, /* Existing photo image. */
XImage *ximage, /* XImage to copy pixels from. */
unsigned long trans, /* Pixel value in ximage that should be
* considered transparent. */
int alpha /* Desired transparency of photo image.*/
)
{
Tk_PhotoImageBlock photoBlock;
unsigned char *pixelPtr;
int x, y, w = ximage->width, h = ximage->height;
Tk_PhotoBlank(photoH);
/* See TkPoscriptImage */
pixelPtr = (unsigned char *) Tcl_Alloc(ximage->width * ximage->height * 4);
photoBlock.pixelPtr = pixelPtr;
photoBlock.width = ximage->width;
photoBlock.height = ximage->height;
photoBlock.pitch = ximage->width * 4;
photoBlock.pixelSize = 4;
photoBlock.offset[0] = 0;
photoBlock.offset[1] = 1;
photoBlock.offset[2] = 2;
photoBlock.offset[3] = 3;
for (y = 0; y < ximage->height; y++) {
for (x = 0; x < ximage->width; x++) {
int r, g, b;
unsigned long pixel;
/* FIXME: I think this blows up on classic Mac??? */
pixel = XGetPixel(ximage, x, y);
/* Set alpha=0 for transparent pixel in the source XImage */
if (trans != 0 && pixel == trans) {
pixelPtr[y * photoBlock.pitch + x * 4 + 3] = 0;
continue;
}
r = GetRValue(pixel);
g = GetGValue(pixel);
b = GetBValue(pixel);
pixelPtr[y * photoBlock.pitch + x * 4 + 0] = r;
pixelPtr[y * photoBlock.pitch + x * 4 + 1] = g;
pixelPtr[y * photoBlock.pitch + x * 4 + 2] = b;
pixelPtr[y * photoBlock.pitch + x * 4 + 3] = alpha;
}
}
TK_PHOTOPUTBLOCK(interp, photoH, &photoBlock, 0, 0, w, h,
TK_PHOTO_COMPOSITE_SET);
Tcl_Free((char *) pixelPtr);
}
typedef struct {
TreeCtrl *tree;
TreeClip *clip;
HDC dc;
TkRegion region;
} TreeClipStateDC;
static void
TreeClip_ToDC(
TreeCtrl *tree, /* Widget info. */
TreeClip *clip, /* Clipping area or NULL. */
HDC dc, /* Windows device context. */
TreeClipStateDC *state
)
{
state->tree = tree;
state->clip = clip;
state->dc = dc;
state->region = None;
if (clip && clip->type == TREE_CLIP_RECT) {
state->region = Tree_GetRectRegion(tree, &clip->tr);
SelectClipRgn(dc, (HRGN) state->region);
}
if (clip && clip->type == TREE_CLIP_AREA) {
TreeRectangle tr;
if (Tree_AreaBbox(tree, clip->area, &tr) == 0)
return;
state->region = Tree_GetRectRegion(tree, &tr);
SelectClipRgn(dc, (HRGN) state->region);
}
if (clip && clip->type == TREE_CLIP_REGION) {
SelectClipRgn(dc, (HRGN) clip->region);
}
}
static void
TreeClip_FinishDC(
TreeClipStateDC *state
)
{
SelectClipRgn(state->dc, NULL);
if (state->region != NULL)
Tree_FreeRegion(state->tree, state->region);
}
#if USE_ITEM_PIXMAP == 0
/*
*----------------------------------------------------------------------
*
* DrawOrFillArc --
* Copied from tkTwinDraw.c because the clip region is ignored on
* Win32.
*
* This function handles the rendering of drawn or filled arcs and
* chords.
*
* Results:
* None.
*
* Side effects:
* Renders the requested arc.
*
*----------------------------------------------------------------------
*/
/*
* These macros convert between X's bizarre angle units to radians.
*/
#define PI 3.14159265358979
#define XAngleToRadians(a) ((double)(a) / 64 * PI / 180);
static void
DrawOrFillArc(
TreeCtrl *tree, /* Widget info. */
Drawable d,
TreeClip *clip, /* Clipping area or NULL. */
GC gc,
int x, int y, /* left top */
unsigned int width, unsigned int height,
int start, /* start: three-o'clock (deg*64) */
int extent, /* extent: relative (deg*64) */
int fill) /* ==0 draw, !=0 fill */
{
HDC dc;
HBRUSH brush, oldBrush;
HPEN pen, oldPen;
TkWinDCState state;
TreeClipStateDC clipState;
int clockwise = (extent < 0); /* non-zero if clockwise */
int xstart, ystart, xend, yend;
double radian_start, radian_end, xr, yr;
if (d == None) {
return;
}
dc = TkWinGetDrawableDC(tree->display, d, &state);
TreeClip_ToDC(tree, clip, dc, &clipState);
/* SetROP2(dc, tkpWinRopModes[gc->function]);*/
/*
* Compute the absolute starting and ending angles in normalized radians.
* Swap the start and end if drawing clockwise.
*/
start = start % (64*360);
if (start < 0) {
start += (64*360);
}
extent = (start+extent) % (64*360);
if (extent < 0) {
extent += (64*360);
}
if (clockwise) {
int tmp = start;
start = extent;
extent = tmp;
}
radian_start = XAngleToRadians(start);
radian_end = XAngleToRadians(extent);
/*
* Now compute points on the radial lines that define the starting and
* ending angles. Be sure to take into account that the y-coordinate
* system is inverted.
*/
xr = x + width / 2.0;
yr = y + height / 2.0;
xstart = (int)((xr + cos(radian_start)*width/2.0) + 0.5);
ystart = (int)((yr + sin(-radian_start)*height/2.0) + 0.5);
xend = (int)((xr + cos(radian_end)*width/2.0) + 0.5);
yend = (int)((yr + sin(-radian_end)*height/2.0) + 0.5);
/*
* Now draw a filled or open figure. Note that we have to increase the
* size of the bounding box by one to account for the difference in pixel
* definitions between X and Windows.
*/
pen = CreatePen((int) PS_SOLID, gc->line_width, gc->foreground);
oldPen = SelectObject(dc, pen);
if (!fill) {
/*
* Note that this call will leave a gap of one pixel at the end of the
* arc for thin arcs. We can't use ArcTo because it's only supported
* under Windows NT.
*/
SetBkMode(dc, TRANSPARENT);
Arc(dc, x, y, (int) (x+width+1), (int) (y+height+1), xstart, ystart,
xend, yend);
} else {
brush = CreateSolidBrush(gc->foreground);
oldBrush = SelectObject(dc, brush);
if (gc->arc_mode == ArcChord) {
Chord(dc, x, y, (int) (x+width+1), (int) (y+height+1),
xstart, ystart, xend, yend);
} else if (gc->arc_mode == ArcPieSlice) {
Pie(dc, x, y, (int) (x+width+1), (int) (y+height+1),
xstart, ystart, xend, yend);
}
DeleteObject(SelectObject(dc, oldBrush));
}
DeleteObject(SelectObject(dc, oldPen));
TreeClip_FinishDC(&clipState);
TkWinReleaseDrawableDC(d, dc, &state);
}
/*
*----------------------------------------------------------------------
*
* Tree_DrawArc --
*
* Wrapper around XDrawArc() because the clip region is
* ignored on Win32.
*
* Results:
* None.
*
* Side effects:
* Draws onto the specified drawable.
*
*----------------------------------------------------------------------
*/
void
Tree_DrawArc(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
GC gc,
int x, int y,
unsigned int width, unsigned int height,
int start, int extent)
{
tree->display->request++;
DrawOrFillArc(tree, td.drawable, clip, gc, x, y, width, height,
start, extent, 0);
}
/*
*----------------------------------------------------------------------
*
* Tree_FillArc --
*
* Wrapper around XFillArc() because the clip region is
* ignored on Win32.
*
* Results:
* None.
*
* Side effects:
* Draws onto the specified drawable.
*
*----------------------------------------------------------------------
*/
void
Tree_FillArc(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
GC gc,
int x, int y,
unsigned int width, unsigned int height,
int start, int extent)
{
tree->display->request++;
DrawOrFillArc(tree, td.drawable, clip, gc, x, y, width, height,
start, extent, 1);
}
#endif /* USE_ITEM_PIXMAP == 0 */
/*
*----------------------------------------------------------------------
*
* Tree_FillRectangle --
*
* Wrapper around XFillRectangle() because the clip region is
* ignored on Win32.
*
* Results:
* None.
*
* Side effects:
* Draws onto the specified drawable.
*
*----------------------------------------------------------------------
*/
void
Tree_FillRectangle(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
GC gc, /* Graphics context. */
TreeRectangle tr /* Rectangle to paint. */
)
{
#if 1
HDC dc;
TkWinDCState dcState;
TreeClipStateDC clipState;
RECT rect;
COLORREF oldColor;
dc = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
TreeClip_ToDC(tree, clip, dc, &clipState);
rect.left = tr.x, rect.top = tr.y,
rect.right = tr.x + tr.width, rect.bottom = tr.y + tr.height;
oldColor = SetBkColor(dc, (COLORREF)gc->foreground);
SetBkMode(dc, OPAQUE);
ExtTextOut(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
SetBkColor(dc, oldColor);
TreeClip_FinishDC(&clipState);
TkWinReleaseDrawableDC(td.drawable, dc, &dcState);
#else
HDC dc;
TkWinDCState dcState;
HBRUSH brush;
RECT rect;
TreeClipStateDC clipState;
dc = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
TreeClip_ToDC(tree, clip, dc, &clipState);
brush = CreateSolidBrush(gc->foreground);
rect.left = tr.x, rect.top = tr.y,
rect.right = tr.x + tr.width, rect.bottom = tr.y + tr.height;
FillRect(dc, &rect, brush);
TreeClip_FinishDC(&clipState);
DeleteObject(brush);
TkWinReleaseDrawableDC(td.drawable, dc, &dcState);
#endif
}
#if USE_ITEM_PIXMAP == 0
static void
FastFillRect(
HDC dc,
int x, int y, int width, int height,
COLORREF pixel
)
{
RECT rect;
COLORREF oldColor;
rect.left = x, rect.top = y,
rect.right = x + width, rect.bottom = y + height;
oldColor = SetBkColor(dc, pixel);
SetBkMode(dc, OPAQUE);
ExtTextOut(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
SetBkColor(dc, oldColor);
}
static void
_3DVerticalBevel(
HDC dc,
Tk_Window tkwin, /* Window for which border was allocated. */
Tk_3DBorder border, /* Token for border to draw. */
int x, int y, int width, int height,
/* Area of vertical bevel. */
int leftBevel, /* Non-zero means this bevel forms the left
* side of the object; 0 means it forms the
* right side. */
int relief) /* Kind of bevel to draw. For example,
* TK_RELIEF_RAISED means interior of object
* should appear higher than exterior. */
{
COLORREF left, right;
int half;
switch (relief) {
case TK_RELIEF_RAISED:
left = (leftBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC)
: TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC);
right = (leftBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT2)
: TkWinGetBorderPixels(tkwin, border, TK_3D_DARK2);
break;
case TK_RELIEF_SUNKEN:
left = (leftBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC)
: TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT2);
right = (leftBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_DARK2)
: TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC);
break;
case TK_RELIEF_RIDGE:
left = TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC);
right = TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC);
break;
case TK_RELIEF_GROOVE:
left = TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC);
right = TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC);
break;
case TK_RELIEF_FLAT:
left = right = TkWinGetBorderPixels(tkwin, border, TK_3D_FLAT_GC);
break;
case TK_RELIEF_SOLID:
default:
left = right = RGB(0,0,0);
break;
}
half = width/2;
if (leftBevel && (width & 1)) {
half++;
}
FastFillRect(dc, x, y, half, height, left);
FastFillRect(dc, x+half, y, width-half, height, right);
}
static void
_3DHorizontalBevel(
HDC dc,
Tk_Window tkwin, /* Window for which border was allocated. */
Tk_3DBorder border, /* Token for border to draw. */
int x, int y, int width, int height,
/* Bounding box of area of bevel. Height gives
* width of border. */
int leftIn, int rightIn, /* Describes whether the left and right edges
* of the bevel angle in or out as they go
* down. For example, if "leftIn" is true, the
* left side of the bevel looks like this:
* ___________
* __________
* _________
* ________
*/
int topBevel, /* Non-zero means this bevel forms the top
* side of the object; 0 means it forms the
* bottom side. */
int relief) /* Kind of bevel to draw. For example,
* TK_RELIEF_RAISED means interior of object
* should appear higher than exterior. */
{
int bottom, halfway, x1, x2, x1Delta, x2Delta;
int topColor, bottomColor;
switch (relief) {
case TK_RELIEF_RAISED:
topColor = (topBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC)
: TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC);
bottomColor = (topBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT2)
: TkWinGetBorderPixels(tkwin, border, TK_3D_DARK2);
break;
case TK_RELIEF_SUNKEN:
topColor = (topBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC)
: TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT2);
bottomColor = (topBevel)
? TkWinGetBorderPixels(tkwin, border, TK_3D_DARK2)
: TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC);
break;
case TK_RELIEF_RIDGE:
topColor = TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC);
bottomColor = TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC);
break;
case TK_RELIEF_GROOVE:
topColor = TkWinGetBorderPixels(tkwin, border, TK_3D_DARK_GC);
bottomColor = TkWinGetBorderPixels(tkwin, border, TK_3D_LIGHT_GC);
break;
case TK_RELIEF_FLAT:
topColor = bottomColor = TkWinGetBorderPixels(tkwin, border, TK_3D_FLAT_GC);
break;
case TK_RELIEF_SOLID:
default:
topColor = bottomColor = RGB(0,0,0);
}
if (leftIn) {
x1 = x+1;
} else {
x1 = x+height-1;
}
x2 = x+width;
if (rightIn) {
x2--;
} else {
x2 -= height;
}
x1Delta = (leftIn) ? 1 : -1;
x2Delta = (rightIn) ? -1 : 1;
halfway = y + height/2;
if (topBevel && (height & 1)) {
halfway++;
}
bottom = y + height;
for ( ; y < bottom; y++) {
if (x1 < x2) {
FastFillRect(dc, x1, y, x2-x1, 1,
(y < halfway) ? topColor : bottomColor);
}
x1 += x1Delta;
x2 += x2Delta;
}
}
/*
*----------------------------------------------------------------------
*
* Tree_Draw3DRectangle --
*
* Reimplementation of Tk_Draw3DRectangle() because the clip
* region is ignored on Win32.
*
* Results:
* None.
*
* Side effects:
* Draws onto the specified drawable.
*
*----------------------------------------------------------------------
*/
void
Tree_Draw3DRectangle(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
Tk_3DBorder border, /* Token for border to draw. */
int x, int y, int width, int height,
/* Outside area of region in which border will
* be drawn. */
int borderWidth, /* Desired width for border, in pixels. */
int relief /* Type of relief: TK_RELIEF_RAISED,
* TK_RELIEF_SUNKEN, TK_RELIEF_GROOVE, etc. */
)
{
Tk_Window tkwin = tree->tkwin;
HDC dc;
TkWinDCState dcState;
TreeClipStateDC clipState;
dc = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
TreeClip_ToDC(tree, clip, dc, &clipState);
if (width < 2*borderWidth) {
borderWidth = width/2;
}
if (height < 2*borderWidth) {
borderWidth = height/2;
}
_3DVerticalBevel(dc, tkwin, border, x, y, borderWidth, height,
1, relief);
_3DVerticalBevel(dc, tkwin, border, x+width-borderWidth, y,
borderWidth, height, 0, relief);
_3DHorizontalBevel(dc, tkwin, border, x, y, width, borderWidth,
1, 1, 1, relief);
_3DHorizontalBevel(dc, tkwin, border, x, y+height-borderWidth,
width, borderWidth, 0, 0, 0, relief);
TreeClip_FinishDC(&clipState);
TkWinReleaseDrawableDC(td.drawable, dc, &dcState);
}
/*
*----------------------------------------------------------------------
*
* Tree_Fill3DRectangle --
*
* Reimplementation of Tree_Fill3DRectangle() because the clip
* region is ignored on Win32.
*
* Results:
* None.
*
* Side effects:
* Draws onto the specified drawable.
*
*----------------------------------------------------------------------
*/
void
Tree_Fill3DRectangle(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
Tk_3DBorder border, /* Token for border to draw. */
int x, int y, int width, int height,
/* Outside area of rectangular region. */
int borderWidth, /* Desired width for border, in pixels. Border
* will be *inside* region. */
int relief /* Indicates 3D effect: TK_RELIEF_FLAT,
* TK_RELIEF_RAISED, or TK_RELIEF_SUNKEN. */
)
{
Tk_Window tkwin = tree->tkwin;
HDC dc;
TkWinDCState dcState;
TreeClipStateDC clipState;
int doubleBorder;
dc = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
TreeClip_ToDC(tree, clip, dc, &clipState);
if (relief == TK_RELIEF_FLAT) {
borderWidth = 0;
} else {
if (width < 2*borderWidth) {
borderWidth = width/2;
}
if (height < 2*borderWidth) {
borderWidth = height/2;
}
}
doubleBorder = 2*borderWidth;
if ((width > doubleBorder) && (height > doubleBorder)) {
FastFillRect(dc,
x + borderWidth, y + borderWidth,
(unsigned int) (width - doubleBorder),
(unsigned int) (height - doubleBorder),
TkWinGetBorderPixels(tkwin, border, TK_3D_FLAT_GC));
}
TreeClip_FinishDC(&clipState);
TkWinReleaseDrawableDC(td.drawable, dc, &dcState);
if (borderWidth) {
Tree_Draw3DRectangle(tree, td, clip, border, x, y, width,
height, borderWidth, relief);
}
}
#endif /* USE_ITEM_PIXMAP == 0 */
/*** Themes ***/
#include <uxtheme.h>
#ifdef __MINGW32__
#include <tmschema.h>
#else /* __MING32__ */
/* <vsstyle.h> is part of the Windows SDK but not the Platform SDK. */
/*#include <vsstyle.h>*/
#ifndef HP_HEADERITEM
#define HP_HEADERITEM 1
#define HIS_NORMAL 1
#define HIS_HOT 2
#define HIS_PRESSED 3
#define TVP_GLYPH 2
#define TVP_HOTGLYPH 4
#define GLPS_CLOSED 1
#define GLPS_OPENED 2
#define HGLPS_CLOSED 1
#define HGLPS_OPENED 2
#endif /* HP_HEADERITEM */
#endif /* __MING32__ */
#include <shlwapi.h>
#include <basetyps.h> /* MingW32 */
#ifdef __MINGW32__
/* vsstyle.h */
#define TVP_HOTGLYPH 4
#define HGLPS_CLOSED 1
#define HGLPS_OPENED 2
#endif
#ifndef TMT_CONTENTMARGINS
#define TMT_CONTENTMARGINS 3602
#endif
typedef HTHEME (STDAPICALLTYPE OpenThemeDataProc)(HWND hwnd,
LPCWSTR pszClassList);
typedef HRESULT (STDAPICALLTYPE CloseThemeDataProc)(HTHEME hTheme);
typedef HRESULT (STDAPICALLTYPE DrawThemeBackgroundProc)(HTHEME hTheme,
HDC hdc, int iPartId, int iStateId, const RECT *pRect,
OPTIONAL const RECT *pClipRect);
typedef HRESULT (STDAPICALLTYPE DrawThemeBackgroundExProc)(HTHEME hTheme,
HDC hdc, int iPartId, int iStateId, const RECT *pRect,
DTBGOPTS *PDTBGOPTS);
typedef HRESULT (STDAPICALLTYPE DrawThemeParentBackgroundProc)(HWND hwnd,
HDC hdc, OPTIONAL const RECT *prc);
typedef HRESULT (STDAPICALLTYPE DrawThemeEdgeProc)(HTHEME hTheme, HDC hdc,
int iPartId, int iStateId, const RECT *pDestRect,
UINT uEdge, UINT uFlags, RECT *pContentRect);
typedef HRESULT (STDAPICALLTYPE DrawThemeTextProc)(HTHEME hTheme, HDC hdc,
int iPartId, int iStateId, LPCWSTR pszText, int iCharCount,
DWORD dwTextFlags, DWORD dwTextFlags2, const RECT *pRect);
typedef HRESULT (STDAPICALLTYPE GetThemeBackgroundContentRectProc)(
HTHEME hTheme, HDC hdc, int iPartId, int iStateId,
const RECT *pBoundingRect, RECT *pContentRect);
typedef HRESULT (STDAPICALLTYPE GetThemeBackgroundExtentProc)(HTHEME hTheme,
HDC hdc, int iPartId, int iStateId, const RECT *pContentRect,
RECT *pExtentRect);
typedef HRESULT (STDAPICALLTYPE GetThemeMarginsProc)(HTHEME, HDC,
int iPartId, int iStateId, int iPropId, OPTIONAL RECT *prc,
MARGINS *pMargins);
typedef HRESULT (STDAPICALLTYPE GetThemePartSizeProc)(HTHEME, HDC, int iPartId,
int iStateId, RECT *prc, enum THEMESIZE eSize, SIZE *psz);
typedef HRESULT (STDAPICALLTYPE GetThemeTextExtentProc)(HTHEME hTheme, HDC hdc,
int iPartId, int iStateId, LPCWSTR pszText, int iCharCount,
DWORD dwTextFlags, const RECT *pBoundingRect, RECT *pExtentRect);
typedef BOOL (STDAPICALLTYPE IsThemeActiveProc)(VOID);
typedef BOOL (STDAPICALLTYPE IsAppThemedProc)(VOID);
typedef BOOL (STDAPICALLTYPE IsThemePartDefinedProc)(HTHEME, int, int);
typedef HRESULT (STDAPICALLTYPE IsThemeBackgroundPartiallyTransparentProc)(
HTHEME, int, int);
typedef HRESULT (STDAPICALLTYPE SetWindowThemeProc)(HWND, LPCWSTR, LPCWSTR);
typedef struct
{
OpenThemeDataProc *OpenThemeData;
CloseThemeDataProc *CloseThemeData;
DrawThemeBackgroundProc *DrawThemeBackground;
DrawThemeBackgroundExProc *DrawThemeBackgroundEx;
DrawThemeParentBackgroundProc *DrawThemeParentBackground;
DrawThemeEdgeProc *DrawThemeEdge;
DrawThemeTextProc *DrawThemeText;
GetThemeBackgroundContentRectProc *GetThemeBackgroundContentRect;
GetThemeBackgroundExtentProc *GetThemeBackgroundExtent;
GetThemeMarginsProc *GetThemeMargins;
GetThemePartSizeProc *GetThemePartSize;
GetThemeTextExtentProc *GetThemeTextExtent;
IsThemeActiveProc *IsThemeActive;
IsAppThemedProc *IsAppThemed;
IsThemePartDefinedProc *IsThemePartDefined;
IsThemeBackgroundPartiallyTransparentProc *IsThemeBackgroundPartiallyTransparent;
SetWindowThemeProc *SetWindowTheme;
} XPThemeProcs;
typedef struct
{
HINSTANCE hlibrary;
XPThemeProcs *procs;
int registered;
int themeEnabled;
} XPThemeData;
typedef struct TreeThemeData_
{
HTHEME hThemeHEADER;
HTHEME hThemeTREEVIEW;
SIZE buttonOpen;
SIZE buttonClosed;
} TreeThemeData_;
static XPThemeProcs *procs = NULL;
static XPThemeData *appThemeData = NULL;
TCL_DECLARE_MUTEX(themeMutex)
/* Functions imported from kernel32.dll requiring windows XP or greater. */
/* But I already link to GetVersionEx so is this importing needed? */
typedef HANDLE (STDAPICALLTYPE CreateActCtxAProc)(PCACTCTXA pActCtx);
typedef BOOL (STDAPICALLTYPE ActivateActCtxProc)(HANDLE hActCtx, ULONG_PTR *lpCookie);
typedef BOOL (STDAPICALLTYPE DeactivateActCtxProc)(DWORD dwFlags, ULONG_PTR ulCookie);
typedef VOID (STDAPICALLTYPE ReleaseActCtxProc)(HANDLE hActCtx);
typedef struct
{
CreateActCtxAProc *CreateActCtxA;
ActivateActCtxProc *ActivateActCtx;
DeactivateActCtxProc *DeactivateActCtx;
ReleaseActCtxProc *ReleaseActCtx;
} ActCtxProcs;
static ActCtxProcs *
GetActCtxProcs(void)
{
HINSTANCE hInst;
ActCtxProcs *procs = (ActCtxProcs *) ckalloc(sizeof(ActCtxProcs));
hInst = LoadLibrary("kernel32.dll"); /* FIXME: leak? */
if (hInst != 0)
{
#define LOADPROC(name) \
(0 != (procs->name = (name ## Proc *)GetProcAddress(hInst, #name) ))
if (LOADPROC(CreateActCtxA) &&
LOADPROC(ActivateActCtx) &&
LOADPROC(DeactivateActCtx) &&
LOADPROC(ReleaseActCtx))
{
return procs;
}
#undef LOADPROC
}
ckfree((char*)procs);
return NULL;
}
static HMODULE thisModule = NULL;
/* Return the HMODULE for this treectrl.dll. */
static HMODULE
GetMyHandle(void)
{
#if 1
return thisModule;
#else
HMODULE hModule = NULL;
/* FIXME: Only >=NT so I shouldn't link to it? But I already linked to
* GetVersionEx so will it run on 95/98? */
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)&appThemeData,
&hModule);
return hModule;
#endif
}
BOOL WINAPI
DllMain(
HINSTANCE hInst, /* Library instance handle. */
DWORD reason, /* Reason this function is being called. */
LPVOID reserved) /* Not used. */
{
if (reason == DLL_PROCESS_ATTACH) {
thisModule = (HMODULE) hInst;
}
return TRUE;
}
static HANDLE
ActivateManifestContext(ActCtxProcs *procs, ULONG_PTR *ulpCookie)
{
ACTCTXA actctx;
HANDLE hCtx;
#if 1
char myPath[1024];
DWORD len;
if (procs == NULL)
return INVALID_HANDLE_VALUE;
len = GetModuleFileName(GetMyHandle(),myPath,1024);
myPath[len] = 0;
ZeroMemory(&actctx, sizeof(actctx));
actctx.cbSize = sizeof(actctx);
actctx.lpSource = myPath;
actctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID;
#else
if (procs == NULL)
return INVALID_HANDLE_VALUE;
ZeroMemory(&actctx, sizeof(actctx));
actctx.cbSize = sizeof(actctx);
actctx.dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID;
actctx.hModule = GetMyHandle();
#endif
actctx.lpResourceName = MAKEINTRESOURCE(2);
hCtx = procs->CreateActCtxA(&actctx);
if (hCtx == INVALID_HANDLE_VALUE)
{
char msg[1024];
DWORD err = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS|
FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)msg,
sizeof(msg), 0);
return INVALID_HANDLE_VALUE;
}
if (procs->ActivateActCtx(hCtx, ulpCookie))
return hCtx;
return INVALID_HANDLE_VALUE;
}
static void
DeactivateManifestContext(ActCtxProcs *procs, HANDLE hCtx, ULONG_PTR ulpCookie)
{
if (procs == NULL)
return;
if (hCtx != INVALID_HANDLE_VALUE)
{
procs->DeactivateActCtx(0, ulpCookie);
procs->ReleaseActCtx(hCtx);
}
ckfree((char*)procs);
}
/* http://www.manbu.net/Lib/En/Class5/Sub16/1/29.asp */
static int
ComCtlVersionOK(void)
{
HINSTANCE handle;
typedef HRESULT (STDAPICALLTYPE DllGetVersionProc)(DLLVERSIONINFO *);
DllGetVersionProc *pDllGetVersion;
int result = FALSE;
ActCtxProcs *procs;
HANDLE hCtx;
ULONG_PTR ulpCookie;
procs = GetActCtxProcs();
hCtx = ActivateManifestContext(procs, &ulpCookie);
handle = LoadLibrary("comctl32.dll");
DeactivateManifestContext(procs, hCtx, ulpCookie);
if (handle == NULL)
return FALSE;
pDllGetVersion = (DllGetVersionProc *) GetProcAddress(handle,
"DllGetVersion");
if (pDllGetVersion != NULL) {
DLLVERSIONINFO dvi;
memset(&dvi, '\0', sizeof(dvi));
dvi.cbSize = sizeof(dvi);
if ((*pDllGetVersion)(&dvi) == NOERROR)
result = dvi.dwMajorVersion >= 6;
}
FreeLibrary(handle);
return result;
}
/*
*----------------------------------------------------------------------
*
* LoadXPThemeProcs --
* Initialize XP theming support.
*
* XP theme support is included in UXTHEME.DLL
* We dynamically load this DLL at runtime instead of linking
* to it at build-time.
*
* Returns:
* A pointer to an XPThemeProcs table if successful, NULL otherwise.
*----------------------------------------------------------------------
*/
static XPThemeProcs *
LoadXPThemeProcs(HINSTANCE *phlib)
{
OSVERSIONINFO os;
/*
* We have to check whether we are running at least on Windows XP.
* In order to determine this we call GetVersionEx directly, although
* it would be a good idea to wrap it inside a function similar to
* TkWinGetPlatformId...
*/
ZeroMemory(&os, sizeof(os));
os.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&os);
if ((os.dwMajorVersion >= 5 && os.dwMinorVersion >= 1) ||
(os.dwMajorVersion > 5)) {
/*
* We are running under Windows XP or a newer version.
* Load the library "uxtheme.dll", where the native widget
* drawing routines are implemented.
*/
HINSTANCE handle;
*phlib = handle = LoadLibrary("uxtheme.dll");
if (handle != 0) {
/*
* We have successfully loaded the library. Proceed in storing the
* addresses of the functions we want to use.
*/
XPThemeProcs *procs = (XPThemeProcs*)ckalloc(sizeof(XPThemeProcs));
#define LOADPROC(name) \
(0 != (procs->name = (name ## Proc *)GetProcAddress(handle, #name) ))
if ( LOADPROC(OpenThemeData)
&& LOADPROC(CloseThemeData)
&& LOADPROC(DrawThemeBackground)
&& LOADPROC(DrawThemeBackgroundEx)
&& LOADPROC(DrawThemeParentBackground)
&& LOADPROC(DrawThemeEdge)
&& LOADPROC(DrawThemeText)
&& LOADPROC(GetThemeBackgroundContentRect)
&& LOADPROC(GetThemeBackgroundExtent)
&& LOADPROC(GetThemeMargins)
&& LOADPROC(GetThemePartSize)
&& LOADPROC(GetThemeTextExtent)
&& LOADPROC(IsThemeActive)
&& LOADPROC(IsAppThemed)
&& LOADPROC(IsThemePartDefined)
&& LOADPROC(IsThemeBackgroundPartiallyTransparent)
&& LOADPROC(SetWindowTheme)
&& ComCtlVersionOK()
) {
return procs;
}
#undef LOADPROC
ckfree((char*)procs);
}
}
return 0;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_DrawHeaderItem --
*
* Draws the background of a single column header. On Mac OS X
* this also draws the sort arrow, if any.
*
* Results:
* TCL_OK if drawing occurred, TCL_ERROR if the X11 fallback
* should be used.
*
* Side effects:
* Drawing.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_DrawHeaderItem(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
int state, /* COLUMN_STATE_xxx flags. */
int arrow, /* COLUMN_ARROW_xxx flags. */
int visIndex, /* 0-based index in list of visible columns. */
int x, int y, /* Bounds of the header. */
int width, int height /* Bounds of the header. */
)
{
HTHEME hTheme;
HDC hDC;
TkWinDCState dcState;
RECT rc;
HRESULT hr;
int iPartId = HP_HEADERITEM;
int iStateId = HIS_NORMAL;
switch (state) {
case COLUMN_STATE_ACTIVE: iStateId = HIS_HOT; break;
case COLUMN_STATE_PRESSED: iStateId = HIS_PRESSED; break;
}
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
hTheme = tree->themeData->hThemeHEADER;
if (!hTheme)
return TCL_ERROR;
#if 0 /* Always returns FALSE */
if (!procs->IsThemePartDefined(
hTheme,
iPartId,
iStateId)) {
return TCL_ERROR;
}
#endif
rc.left = x;
rc.top = y;
rc.right = x + width;
rc.bottom = y + height;
/* Is transparent for the default XP style. */
if (procs->IsThemeBackgroundPartiallyTransparent(
hTheme,
iPartId,
iStateId)) {
#if 1
/* What color should I use? */
Tk_Fill3DRectangle(tree->tkwin, td.drawable, tree->border, x, y, width, height, 0, TK_RELIEF_FLAT);
#else
/* This draws nothing, maybe because the parent window is not
* themed */
procs->DrawThemeParentBackground(
hwnd,
hDC,
&rc);
#endif
}
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
#if 0
{
/* Default XP theme gives rect 3 pixels narrower than rc */
RECT contentRect, extentRect;
hr = procs->GetThemeBackgroundContentRect(
hTheme,
hDC,
iPartId,
iStateId,
&rc,
&contentRect
);
dbwin("GetThemeBackgroundContentRect width=%d height=%d\n",
contentRect.right - contentRect.left,
contentRect.bottom - contentRect.top);
/* Gives rc */
hr = procs->GetThemeBackgroundExtent(
hTheme,
hDC,
iPartId,
iStateId,
&contentRect,
&extentRect
);
dbwin("GetThemeBackgroundExtent width=%d height=%d\n",
extentRect.right - extentRect.left,
extentRect.bottom - extentRect.top);
}
#endif
hr = procs->DrawThemeBackground(
hTheme,
hDC,
iPartId,
iStateId,
&rc,
NULL);
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
if (hr != S_OK)
return TCL_ERROR;
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_GetHeaderContentMargins --
*
* Returns the padding inside the column header borders where
* text etc may be displayed.
*
* Results:
* TCL_OK if 'bounds' was set, TCL_ERROR otherwise.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_GetHeaderContentMargins(
TreeCtrl *tree, /* Widget info. */
int state, /* COLUMN_STATE_xxx flags. */
int arrow, /* COLUMN_ARROW_xxx flags. */
int bounds[4] /* Returned left-top-right-bottom padding. */
)
{
Window win = Tk_WindowId(tree->tkwin);
HTHEME hTheme;
HDC hDC;
TkWinDCState dcState;
HRESULT hr;
MARGINS margins;
int iPartId = HP_HEADERITEM;
int iStateId = HIS_NORMAL;
switch (state) {
case COLUMN_STATE_ACTIVE: iStateId = HIS_HOT; break;
case COLUMN_STATE_PRESSED: iStateId = HIS_PRESSED; break;
}
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
hTheme = tree->themeData->hThemeHEADER;
if (!hTheme)
return TCL_ERROR;
hDC = TkWinGetDrawableDC(tree->display, win, &dcState);
/* The default XP themes give 3,0,0,0 which makes little sense since
* it is the *right* side that should not be drawn over by text; the
* 2-pixel wide header divider is on the right */
hr = procs->GetThemeMargins(
hTheme,
hDC,
iPartId,
iStateId,
TMT_CONTENTMARGINS,
NULL,
&margins);
TkWinReleaseDrawableDC(win, hDC, &dcState);
if (hr != S_OK)
return TCL_ERROR;
bounds[0] = margins.cxLeftWidth;
bounds[1] = margins.cyTopHeight;
bounds[2] = margins.cxRightWidth;
bounds[3] = margins.cyBottomHeight;
/*
dbwin("margins %d %d %d %d\n", bounds[0], bounds[1], bounds[2], bounds[3]);
*/
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_DrawHeaderArrow --
*
* Draws the sort arrow in a column header.
*
* Results:
* TCL_OK if drawing occurred, TCL_ERROR if the X11 fallback
* should be used.
*
* Side effects:
* Drawing.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_DrawHeaderArrow(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
int state, /* COLUMN_STATE_xxx flags. */
int up, /* TRUE if up arrow, FALSE otherwise. */
int x, int y, /* Bounds of arrow. Width and */
int width, int height /* height are the same as that returned */
/* by TreeTheme_GetArrowSize(). */
)
{
#define THEME_ARROW 0
#if THEME_ARROW==0
XColor *color;
GC gc;
int i;
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
color = Tk_GetColor(tree->interp, tree->tkwin, "#ACA899");
gc = Tk_GCForColor(color, td.drawable);
if (up) {
for (i = 0; i < height; i++) {
XDrawLine(tree->display, td.drawable, gc,
x + width / 2 - i, y + i,
x + width / 2 + i + 1, y + i);
}
} else {
for (i = 0; i < height; i++) {
XDrawLine(tree->display, td.drawable, gc,
x + width / 2 - i, y + (height - 1) - i,
x + width / 2 + i + 1, y + (height - 1) - i);
}
}
Tk_FreeColor(color);
return TCL_OK;
#else
/* Doesn't seem that Microsoft actually implemented this */
Window win = Tk_WindowId(tree->tkwin);
HWND hwnd = Tk_GetHWND(win);
HTHEME hTheme;
HDC hDC;
TkWinDCState dcState;
RECT rc;
HRESULT hr;
int iPartId = HP_HEADERSORTARROW;
int iStateId = up ? HSAS_SORTEDUP : HSAS_SORTEDDOWN;
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
hTheme = tree->themeData->hThemeHEADER;
if (!hTheme)
return TCL_ERROR;
if (!procs->IsThemePartDefined(
hTheme,
iPartId,
iStateId)) {
return TCL_ERROR;
}
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
rc.left = x;
rc.top = y;
rc.right = x + width;
rc.bottom = y + height;
hr = procs->DrawThemeBackground(
hTheme,
hDC,
iPartId,
iStateId,
&rc,
NULL);
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
return TCL_OK;
#endif /* THEME_ARROW==1 */
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_DrawButton --
*
* Draws a single expand/collapse item button.
*
* Results:
* TCL_OK if drawing occurred, TCL_ERROR if the X11 fallback
* should be used.
*
* Side effects:
* Drawing.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_DrawButton(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeItem item, /* Needed for animating. */
int state, /* STATE_xxx | BUTTON_STATE_xxx flags. */
int x, int y, /* Bounds of the button. Width and height */
int width, int height /* are the same as that returned by */
/* TreeTheme_GetButtonSize(). */
)
{
int open = state & STATE_ITEM_OPEN;
int active = state & (BUTTON_STATE_ACTIVE|BUTTON_STATE_PRESSED); /* windows theme has no "pressed" state */
HTHEME hTheme;
HDC hDC;
TkWinDCState dcState;
RECT rc;
HRESULT hr;
int iPartId, iStateId;
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
hTheme = tree->themeData->hThemeTREEVIEW;
if (!hTheme)
return TCL_ERROR;
/* On Win7 IsThemePartDefined(TVP_HOTGLYPH) correctly returns
* TRUE when SetWindowTheme("explorer") is called and FALSE when it
* wasn't called. */
if (active && procs->IsThemePartDefined(hTheme, TVP_HOTGLYPH, 0)) {
iPartId = TVP_HOTGLYPH;
iStateId = open ? HGLPS_OPENED : HGLPS_CLOSED;
} else {
iPartId = TVP_GLYPH;
iStateId = open ? GLPS_OPENED : GLPS_CLOSED;
}
#if 0 /* Always returns FALSE */
if (!procs->IsThemePartDefined(
hTheme,
iPartId,
iStateId)) {
return TCL_ERROR;
}
#endif
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
rc.left = x;
rc.top = y;
rc.right = x + width;
rc.bottom = y + height;
hr = procs->DrawThemeBackground(
hTheme,
hDC,
iPartId,
iStateId,
&rc,
NULL);
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
if (hr != S_OK)
return TCL_ERROR;
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_GetButtonSize --
*
* Returns the width and height of an expand/collapse item button.
*
* Results:
* TCL_OK if *widthPtr and *heightPtr were set, TCL_ERROR
* if themed buttons can't be drawn.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_GetButtonSize(
TreeCtrl *tree, /* Widget info. */
Drawable drawable, /* Needed on MS Windows. */
int open, /* TRUE if expanded button. */
int *widthPtr, /* Returned width of button. */
int *heightPtr /* Returned height of button. */
)
{
TreeThemeData themeData = tree->themeData;
HTHEME hTheme;
HDC hDC;
TkWinDCState dcState;
HRESULT hr;
SIZE size;
int iPartId, iStateId;
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
/* Use cached values */
size = open ? themeData->buttonOpen : themeData->buttonClosed;
if (size.cx > 1) {
*widthPtr = size.cx;
*heightPtr = size.cy;
return TCL_OK;
}
hTheme = themeData->hThemeTREEVIEW;
if (!hTheme)
return TCL_ERROR;
iPartId = TVP_GLYPH;
iStateId = open ? GLPS_OPENED : GLPS_CLOSED;
#if 0 /* Always returns FALSE */
if (!procs->IsThemePartDefined(
hTheme,
iPartId,
iStateId)) {
return TCL_ERROR;
}
#endif
hDC = TkWinGetDrawableDC(tree->display, drawable, &dcState);
/* Returns 9x9 for default XP style */
hr = procs->GetThemePartSize(
hTheme,
hDC,
iPartId,
iStateId,
NULL,
TS_DRAW,
&size
);
TkWinReleaseDrawableDC(drawable, hDC, &dcState);
/* With RandomN of 10000, I eventually get hr=E_HANDLE, invalid handle */
/* Not any longer since I don't call OpenThemeData/CloseThemeData for
* every call. */
if (hr != S_OK)
return TCL_ERROR;
/* Gave me 0,0 for a non-default theme, even though glyph existed */
if ((size.cx <= 1) && (size.cy <= 1))
return TCL_ERROR;
/* Cache the values */
if (open)
themeData->buttonOpen = size;
else
themeData->buttonClosed = size;
*widthPtr = size.cx;
*heightPtr = size.cy;
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_GetArrowSize --
*
* Returns the width and height of a column header sort arrow.
*
* Results:
* TCL_OK if *widthPtr and *heightPtr were set, TCL_ERROR
* if themed sort arrows can't be drawn.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_GetArrowSize(
TreeCtrl *tree, /* Widget info. */
Drawable drawable, /* Needed on MS Windows. */
int up, /* TRUE if up arrow. */
int *widthPtr, /* Returned width of arrow. */
int *heightPtr /* Returned height of arrow. */
)
{
#if THEME_ARROW==0
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
*widthPtr = 9;
*heightPtr = 5;
return TCL_OK;
#else
TreeThemeData themeData = tree->themeData;
HTHEME hTheme;
HDC hDC;
TkWinDCState dcState;
HRESULT hr;
SIZE size;
int iPartId, iStateId;
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
hTheme = themeData->hThemeTREEVIEW;
if (!hTheme)
return TCL_ERROR;
iPartId = HP_HEADERSORTARROW;
iStateId = up ? HSAS_SORTEDUP : HSAS_SORTEDDOWN;
#if 0 /* Always returns FALSE */
if (!procs->IsThemePartDefined(
hTheme,
iPartId,
iStateId)) {
return TCL_ERROR;
}
#endif
hDC = TkWinGetDrawableDC(tree->display, drawable, &dcState);
hr = procs->GetThemePartSize(
hTheme,
hDC,
iPartId,
iStateId,
NULL,
TS_DRAW,
&size
);
TkWinReleaseDrawableDC(drawable, hDC, &dcState);
if (hr != S_OK)
return TCL_ERROR;
if ((size.cx <= 1) && (size.cy <= 1))
return TCL_ERROR;
*widthPtr = size.cx;
*heightPtr = size.cy;
return TCL_OK;
#endif /* THEME_ARROW==1 */
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_SetBorders --
*
* Sets the TreeCtrl.inset pad values according to the needs of
* the system theme.
*
* Results:
* TCL_OK if the inset was set, TCL_ERROR if the -highlightthickness
* and -borderwidth values should be used.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_SetBorders(
TreeCtrl *tree /* Widget info. */
)
{
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_DrawBorders --
*
* Draws themed borders around the edges of the treectrl.
*
* Results:
* TCL_OK if drawing occurred, TCL_ERROR if the Tk focus rectangle
* and 3D border should be drawn.
*
* Side effects:
* Drawing.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_DrawBorders(
TreeCtrl *tree, /* Widget info. */
Drawable drawable /* Where to draw. */
)
{
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_GetHeaderTextColor --
*
* Returns the text fill color to display a column title with.
*
* Results:
* TCL_OK if the *colorPtrPtr was set, TCL_ERROR if a non-theme
* color should be used.
*
* Side effects:
* May allocate a new XColor.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_GetHeaderTextColor(
TreeCtrl *tree, /* Widget info. */
int columnState, /* COLUMN_STATE_xxx flags. */
XColor **colorPtrPtr /* Returned text color. */
)
{
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_AnimateButtonStart --
*
* Starts an expand/collapse item button animating from open to
* closed or vice versa.
*
* Results:
* TCL_OK.
*
* Side effects:
* May create a new Tcl_TimerToken.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_AnimateButtonStart(
TreeCtrl *tree, /* Widget info. */
TreeItem item /* The item whose button should animate. */
)
{
TreeItem_OpenClose(tree, item, -1);
#ifdef SELECTION_VISIBLE
Tree_DeselectHidden(tree);
#endif
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_ItemDeleted --
*
* Cancels any item-button animation in progress.
*
* Results:
* TCL_OK.
*
* Side effects:
* May delete a TCL_TimerToken.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_ItemDeleted(
TreeCtrl *tree, /* Widget info. */
TreeItem item /* Item being deleted. */
)
{
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_Relayout --
*
* This gets called when certain config options change and when
* the size of the widget changes.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
TreeTheme_Relayout(
TreeCtrl *tree /* Widget info. */
)
{
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_IsDesktopComposited --
*
* Determine if the OS windowing system is composited AKA
* double-buffered.
*
* Results:
* FALSE FALSE FALSE.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_IsDesktopComposited(
TreeCtrl *tree /* Widget info. */
)
{
/* TODO:
Detect Vista/Win7 use of Desktop Window Manager using
DwmIsCompositionEnabled().
WndProc should listen for WM_DWMCOMPOSITIONCHANGED.
*/
#if 1
/* On Win7 I see lots of flickering with the dragimage in the demo
* "Explorer (Large Icons)", so Composition must not work quite how I
* expected. */
return FALSE;
#elif 0
HMODULE library = LoadLibrary("dwmapi.dll");
int result = FALSE;
if (0 != library) {
typedef BOOL (STDAPICALLTYPE DwmIsCompositionEnabledProc)(BOOL *pfEnabled);
DwmIsCompositionEnabledProc *proc;
if (0 != (proc = GetProcAddress(library, "DwmIsCompositionEnabled"))) {
BOOL enabled = FALSE;
result = SUCCEEDED(proc(&enabled)) && enabled;
}
FreeLibrary(library);
}
return result;
#else
/* http://weblogs.asp.net/kennykerr/archive/2006/08/10/Windows-Vista-for-Developers-_1320_-Part-3-_1320_-The-Desktop-Window-Manager.aspx */
bool IsCompositionEnabled()
{
HMODULE library = ::LoadLibrary(L"dwmapi.dll");
bool result = false;
if (0 != library)
{
if (0 != ::GetProcAddress(library,
"DwmIsCompositionEnabled"))
{
BOOL enabled = FALSE;
result = SUCCEEDED(::DwmIsCompositionEnabled(&enabled)) && enabled;
}
VERIFY(::FreeLibrary(library));
}
return result;
}
#endif
return FALSE;
}
#if !defined(WM_THEMECHANGED)
#define WM_THEMECHANGED 0x031A
#endif
static LRESULT WINAPI
ThemeMonitorWndProc(
HWND hwnd,
UINT msg,
WPARAM wp,
LPARAM lp)
{
Tcl_Interp *interp = (Tcl_Interp *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
switch (msg) {
case WM_THEMECHANGED:
Tcl_MutexLock(&themeMutex);
appThemeData->themeEnabled = procs->IsThemeActive() &&
procs->IsAppThemed();
Tcl_MutexUnlock(&themeMutex);
Tree_TheWorldHasChanged(interp);
/* FIXME: must get tree->themeData->hThemeHEADER etc for each widget */
break;
}
return DefWindowProc(hwnd, msg, wp, lp);
}
static CHAR windowClassName[32] = "TreeCtrlMonitorClass";
static BOOL
RegisterThemeMonitorWindowClass(
HINSTANCE hinst)
{
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC) ThemeMonitorWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hinst;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) COLOR_WINDOW;
wc.lpszMenuName = windowClassName;
wc.lpszClassName = windowClassName;
return RegisterClassEx(&wc);
}
static HWND
CreateThemeMonitorWindow(
HINSTANCE hinst,
Tcl_Interp *interp)
{
CHAR title[32] = "TreeCtrlMonitorWindow";
HWND hwnd;
hwnd = CreateWindow(windowClassName, title, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hinst, NULL);
if (!hwnd)
return NULL;
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)interp);
ShowWindow(hwnd, SW_HIDE);
UpdateWindow(hwnd);
return hwnd;
}
typedef struct PerInterpData PerInterpData;
struct PerInterpData
{
HWND hwnd;
};
static void
ThemeFreeAssocData(
ClientData clientData,
Tcl_Interp *interp)
{
PerInterpData *data = (PerInterpData *) clientData;
DestroyWindow(data->hwnd);
ckfree((char *) data);
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_ThemeChanged --
*
* Called after the system theme changes.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
TreeTheme_ThemeChanged(
TreeCtrl *tree /* Widget info. */
)
{
Window win = Tk_WindowId(tree->tkwin);
HWND hwnd = Tk_GetHWND(win);
if (tree->themeData != NULL) {
if (tree->themeData->hThemeHEADER != NULL) {
procs->CloseThemeData(tree->themeData->hThemeHEADER);
tree->themeData->hThemeHEADER = NULL;
}
if (tree->themeData->hThemeTREEVIEW != NULL) {
procs->CloseThemeData(tree->themeData->hThemeTREEVIEW);
tree->themeData->hThemeTREEVIEW = NULL;
}
}
if (!appThemeData->themeEnabled || !procs)
return;
if (tree->themeData == NULL)
tree->themeData = (TreeThemeData) ckalloc(sizeof(TreeThemeData_));
tree->themeData->hThemeHEADER = procs->OpenThemeData(hwnd, L"HEADER");
tree->themeData->hThemeTREEVIEW = procs->OpenThemeData(hwnd, L"TREEVIEW");
tree->themeData->buttonClosed.cx = tree->themeData->buttonOpen.cx = -1;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_InitWidget --
*
* Performs theme-related initialization when a treectrl is
* created.
*
* Results:
* TCL_OK or TCL_ERROR, but result is ignored.
*
* Side effects:
* Depends on the platform.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_InitWidget(
TreeCtrl *tree /* Widget info. */
)
{
Window win = Tk_WindowId(tree->tkwin);
HWND hwnd = Tk_GetHWND(win);
if (!appThemeData->themeEnabled || !procs)
return TCL_ERROR;
tree->themeData = (TreeThemeData) ckalloc(sizeof(TreeThemeData_));
/* http://www.codeproject.com/cs/miscctrl/themedtabpage.asp?msg=1445385#xx1445385xx */
/* http://msdn2.microsoft.com/en-us/library/ms649781.aspx */
tree->themeData->hThemeHEADER = procs->OpenThemeData(hwnd, L"HEADER");
tree->themeData->hThemeTREEVIEW = procs->OpenThemeData(hwnd, L"TREEVIEW");
tree->themeData->buttonClosed.cx = tree->themeData->buttonOpen.cx = -1;
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_FreeWidget --
*
* Performs theme-related cleanup a when a treectrl is destroyed.
*
* Results:
* None.
*
* Side effects:
* Depends on the platform.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_FreeWidget(
TreeCtrl *tree /* Widget info. */
)
{
if (tree->themeData != NULL) {
if (tree->themeData->hThemeHEADER != NULL)
procs->CloseThemeData(tree->themeData->hThemeHEADER);
if (tree->themeData->hThemeTREEVIEW != NULL)
procs->CloseThemeData(tree->themeData->hThemeTREEVIEW);
ckfree((char *) tree->themeData);
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_InitInterp --
*
* Performs theme-related initialization when the TkTreeCtrl
* package is loaded into an interpreter.
*
* Results:
* TCL_OK or TCL_ERROR, but result is ignored.
*
* Side effects:
* Depends on the platform.
*
*----------------------------------------------------------------------
*/
int
TreeTheme_InitInterp(
Tcl_Interp *interp /* Interp that loaded TkTreeCtrl pkg. */
)
{
HWND hwnd;
PerInterpData *data;
Tcl_MutexLock(&themeMutex);
/* This is done once per-application */
if (appThemeData == NULL) {
appThemeData = (XPThemeData *) ckalloc(sizeof(XPThemeData));
appThemeData->procs = LoadXPThemeProcs(&appThemeData->hlibrary);
appThemeData->registered = FALSE;
appThemeData->themeEnabled = FALSE;
procs = appThemeData->procs;
if (appThemeData->procs) {
/* Check this again if WM_THEMECHANGED arrives */
appThemeData->themeEnabled = procs->IsThemeActive() &&
procs->IsAppThemed();
appThemeData->registered =
RegisterThemeMonitorWindowClass(Tk_GetHINSTANCE());
}
}
Tcl_MutexUnlock(&themeMutex);
if (!procs || !appThemeData->registered)
return TCL_ERROR;
/* Per-interp */
hwnd = CreateThemeMonitorWindow(Tk_GetHINSTANCE(), interp);
if (!hwnd)
return TCL_ERROR;
data = (PerInterpData *) ckalloc(sizeof(PerInterpData));
data->hwnd = hwnd;
Tcl_SetAssocData(interp, "TreeCtrlTheme", ThemeFreeAssocData, (ClientData) data);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TreeTheme_SetOptionDefault --
*
* Sets the default value for an option.
*
* Results:
* Sets the defValue field if it wasn't done already.
*
* Side effects:
* Changes an existing option table.
*
*----------------------------------------------------------------------
*/
void
TreeTheme_SetOptionDefault(
Tk_OptionSpec *specPtr
)
{
#ifdef TREECTRL_DEBUG
if (specPtr == NULL)
panic("TreeTheme_SetOptionDefault specPtr == NULL");
#endif
/* Only set the default value once per-application. */
if (specPtr->defValue != NULL)
return;
if (!strcmp(specPtr->optionName, "-buttontracking"))
specPtr->defValue = "0";
else if (!strcmp(specPtr->optionName, "-showlines"))
specPtr->defValue = "1";
#ifdef TREECTRL_DEBUG
else
panic("TreeTheme_SetOptionDefault unhandled option \"%s\"",
specPtr->optionName ? specPtr->optionName : "NULL");
#endif
}
int
TreeThemeCmd(
TreeCtrl *tree, /* Widget info. */
int objc, /* Number of arguments. */
Tcl_Obj *CONST objv[] /* Argument values. */
)
{
Tcl_Interp *interp = tree->interp;
static CONST char *commandName[] = {
"platform", "setwindowtheme", (char *) NULL
};
enum {
COMMAND_PLATFORM, COMMAND_SETWINDOWTHEME
};
int index;
if (objc < 3) {
Tcl_WrongNumArgs(interp, 2, objv, "command ?arg arg ...?");
return TCL_ERROR;
}
if (Tcl_GetIndexFromObj(interp, objv[2], commandName, "command", 0,
&index) != TCL_OK) {
return TCL_ERROR;
}
switch (index) {
/* T theme platform */
case COMMAND_PLATFORM: {
char *platform = "X11"; /* X11, xlib, whatever */
if (appThemeData->themeEnabled && appThemeData->procs)
platform = "visualstyles";
Tcl_SetObjResult(interp, Tcl_NewStringObj(platform, -1));
break;
}
/* T theme setwindowtheme $appname */
case COMMAND_SETWINDOWTHEME: {
LPCWSTR pszSubAppName; /* L"Explorer" for example */
int length;
Window win;
HWND hwnd;
if (objc != 4) {
Tcl_WrongNumArgs(interp, 3, objv, "appname");
return TCL_ERROR;
}
if (!appThemeData->themeEnabled || !appThemeData->procs)
break;
win = Tk_WindowId(tree->tkwin);
hwnd = Tk_GetHWND(win);
pszSubAppName = Tcl_GetUnicodeFromObj(objv[3], &length);
procs->SetWindowTheme(hwnd, length ? pszSubAppName : NULL, NULL);
/* uxtheme.h says a WM_THEMECHANGED is sent to the window. */
/* FIXME: only this window needs to be updated. */
/* This calls TreeTheme_ThemeChanged which is needed. */
Tree_TheWorldHasChanged(tree->interp);
break;
}
}
return TCL_OK;
}
/*** Gradients ***/
/*
* GDI+ flat api
*/
/* gdiplus.h is a C++ header file with MSVC. */
/* gdiplus.h works with C and C++ with MinGW. */
/* However gdiplus.h is not included with MinGW-w64 for some reason and
* also does not come with the Linux i586-mingw32msvc cross-compiler. */
#if 1
#define WINGDIPAPI __stdcall
#define GDIPCONST const
#define VOID void
typedef float REAL;
typedef enum CombineMode {
CombineModeReplace = 0
} CombineMode;
typedef enum GpFillMode
{
FillModeAlternate,
FillModeWinding
} GpFillMode;
typedef enum GpLineCap {
LineCapSquare = 1
} GpLineCap;
typedef enum GpUnit {
UnitWorld = 0,
UnitDisplay = 1,
UnitPixel = 2,
UnitPoint = 3,
UnitInch = 4,
UnitDocument = 5,
UnitMillimeter = 6
} GpUnit;
typedef enum GpStatus {
Ok = 0
} GpStatus;
typedef enum GpWrapMode
{
WrapModeTile = 0, /* repeat */
WrapModeTileFlipXY = 3 /* reflect */
} GpWrapMode;
typedef enum LinearGradientMode
{
LinearGradientModeHorizontal,
LinearGradientModeVertical
} LinearGradientMode;
typedef enum GpPenAlignment {
PenAlignmentCenter = 0,
PenAlignmentInset = 1
} GpPenAlignment;
typedef enum SmoothingMode {
SmoothingModeHighQuality = 2,
SmoothingModeAntiAlias = 4
} SmoothingMode;
typedef struct GdiplusStartupInput
{
UINT32 GdiplusVersion;
/*DebugEventProc*/VOID* DebugEventCallback;
BOOL SuppressBackgroundThread;
BOOL SuppressExternalCodecs;
} GdiplusStartupInput;
typedef struct GdiplusStartupOutput
{
/*NotificationHookProc*/VOID* NotificationHook;
/*NotificationUnhookProc*/VOID* NotificationUnhook;
} GdiplusStartupOutput;
typedef struct GpPoint {
INT X;
INT Y;
} GpPoint;
typedef struct GpPointF {
REAL X;
REAL Y;
} GpPointF;
typedef struct GpRect {
INT X;
INT Y;
INT Width;
INT Height;
} GpRect;
typedef DWORD ARGB;
typedef void GpBrush;
typedef void GpGraphics;
typedef void GpLineGradient;
typedef void GpPath;
typedef void GpPen;
typedef void GpSolidFill;
#endif
/* After gdiplus.dll is dynamically loaded, this structure is
* filled in with pointers to functions that are used below. */
static struct
{
HMODULE handle; /* gdiplus.dll */
VOID* (WINGDIPAPI *_GdipAlloc)(size_t);
VOID (WINGDIPAPI *_GdipFree)(VOID*);
GpStatus (WINGDIPAPI *_GdiplusStartup)(ULONG_PTR*,GDIPCONST GdiplusStartupInput*,GdiplusStartupOutput*);
VOID (WINGDIPAPI *_GdiplusShutdown)(ULONG_PTR);
/* Graphics */
GpStatus (WINGDIPAPI *_GdipCreateFromHDC)(HDC,GpGraphics**);
GpStatus (WINGDIPAPI *_GdipFillRectangleI)(GpGraphics*,GpBrush*,INT,INT,INT,INT);
GpStatus (WINGDIPAPI *_GdipDeleteGraphics)(GpGraphics*);
GpStatus (WINGDIPAPI *_GdipDrawPath)(GpGraphics*,GpPen*,GpPath*);
GpStatus (WINGDIPAPI *_GdipFillPath)(GpGraphics*,GpBrush*,GpPath*);
GpStatus (WINGDIPAPI *_GdipSetClipHrgn)(GpGraphics*,HRGN,CombineMode);
GpStatus (WINGDIPAPI *_GdipSetClipPath)(GpGraphics*,GpPath*,CombineMode);
GpStatus (WINGDIPAPI *_GdipSetClipRectI)(GpGraphics*,INT,INT,INT,INT,CombineMode);
GpStatus (WINGDIPAPI *_GdipSetSmoothingMode)(GpGraphics*,SmoothingMode);
/* GraphicsPath */
GpStatus (WINGDIPAPI *_GdipCreatePath)(GpFillMode,GpPath**);
GpStatus (WINGDIPAPI *_GdipDeletePath)(GpPath*);
GpStatus (WINGDIPAPI *_GdipResetPath)(GpPath*);
GpStatus (WINGDIPAPI *_GdipAddPathArc)(GpPath*,REAL,REAL,REAL,REAL,REAL,REAL);
GpStatus (WINGDIPAPI *_GdipAddPathLine)(GpPath*,REAL,REAL,REAL,REAL);
GpStatus (WINGDIPAPI *_GdipAddPathRectangle)(GpPath*,REAL,REAL,REAL,REAL);
GpStatus (WINGDIPAPI *_GdipStartPathFigure)(GpPath*);
GpStatus (WINGDIPAPI *_GdipClosePathFigure)(GpPath*);
/* Linear Gradient brush */
GpStatus (WINGDIPAPI *_GdipCreateLineBrushFromRectI)(GDIPCONST GpRect*,ARGB,ARGB,LinearGradientMode,GpWrapMode,GpLineGradient**);
GpStatus (WINGDIPAPI *_GdipSetLinePresetBlend)(GpLineGradient*,GDIPCONST ARGB*,GDIPCONST REAL*,INT);
GpStatus (WINGDIPAPI *_GdipDeleteBrush)(GpBrush*);
/* Pen */
GpStatus (WINGDIPAPI *_GdipCreatePen1)(ARGB,REAL,GpUnit,GpPen**);
GpStatus (WINGDIPAPI *_GdipCreatePen2)(GpBrush*,REAL,GpUnit,GpPen**);
GpStatus (WINGDIPAPI *_GdipSetPenEndCap)(GpPen*,GpLineCap);
GpStatus (WINGDIPAPI *_GdipSetPenStartCap)(GpPen*,GpLineCap);
GpStatus (WINGDIPAPI *_GdipSetPenMode)(GpPen*,GpPenAlignment);
GpStatus (WINGDIPAPI *_GdipDeletePen)(GpPen*);
/* SolidFill brush */
GpStatus (WINGDIPAPI *_GdipCreateSolidFill)(ARGB,GpSolidFill**);
} DllExports = {0};
/* Per-application global data */
typedef struct
{
ULONG_PTR token; /* Result of GdiplusStartup() */
#if 0
GdiplusStartupOutput output; /* Result of GdiplusStartup() */
#endif
} TreeDrawAppData;
static TreeDrawAppData *appDrawData = NULL;
/* Tcl_CreateExitHandler() callback that shuts down GDI+ */
static void
TreeDraw_ExitHandler(
ClientData clientData
)
{
if (appDrawData != NULL) {
if (DllExports.handle != NULL)
DllExports._GdiplusShutdown(appDrawData->token);
}
}
/* Load gdiplus.dll (if it exists) and fill in the DllExports global */
/* If gdiplus.dll can't be loaded DllExports.handle is set to NULL which
* should be checked to test whether GDI+ can be used. */
static int
LoadGdiplus(void)
{
DllExports.handle = LoadLibrary("gdiplus.dll");
if (DllExports.handle != NULL) {
#define LOADPROC(name) \
(0 != (DllExports._ ## name = (VOID *)GetProcAddress(DllExports.handle, #name) ))
if ( LOADPROC(GdipAlloc)
&& LOADPROC(GdipFree)
&& LOADPROC(GdiplusStartup)
&& LOADPROC(GdiplusShutdown)
&& LOADPROC(GdipCreateFromHDC)
&& LOADPROC(GdipFillRectangleI)
&& LOADPROC(GdipDeleteGraphics)
&& LOADPROC(GdipDrawPath)
&& LOADPROC(GdipFillPath)
&& LOADPROC(GdipSetClipHrgn)
&& LOADPROC(GdipSetClipPath)
&& LOADPROC(GdipSetClipRectI)
&& LOADPROC(GdipSetSmoothingMode)
&& LOADPROC(GdipCreatePath)
&& LOADPROC(GdipDeletePath)
&& LOADPROC(GdipResetPath)
&& LOADPROC(GdipAddPathArc)
&& LOADPROC(GdipAddPathLine)
&& LOADPROC(GdipAddPathRectangle)
&& LOADPROC(GdipStartPathFigure)
&& LOADPROC(GdipClosePathFigure)
&& LOADPROC(GdipCreateLineBrushFromRectI)
&& LOADPROC(GdipSetLinePresetBlend)
&& LOADPROC(GdipDeleteBrush)
&& LOADPROC(GdipCreatePen1)
&& LOADPROC(GdipCreatePen2)
&& LOADPROC(GdipSetPenEndCap)
&& LOADPROC(GdipSetPenStartCap)
&& LOADPROC(GdipSetPenMode)
&& LOADPROC(GdipDeletePen)
&& LOADPROC(GdipCreateSolidFill)
) {
return 1;
}
#undef LOADPROC
}
DllExports.handle = NULL;
return 0;
}
/* Per-interp init */
int
TreeDraw_InitInterp(
Tcl_Interp *interp
)
{
/* This is done once per-application */
if (appDrawData == NULL) {
appDrawData = (TreeDrawAppData *) ckalloc(sizeof(TreeDrawAppData));
memset(appDrawData, '\0', sizeof(TreeDrawAppData));
if (LoadGdiplus()) {
GdiplusStartupInput input;
GpStatus status;
input.GdiplusVersion = 1;
input.DebugEventCallback = NULL;
input.SuppressBackgroundThread = FALSE;
input.SuppressExternalCodecs = FALSE;
/* Not sure what happens when the main application or other
* DLLs also call this, probably it is okay. */
status = DllExports._GdiplusStartup(&appDrawData->token, &input,
#if 1
NULL);
#else
&appDrawData->output);
#endif
if (status != Ok) {
DllExports.handle = NULL;
}
}
Tcl_CreateExitHandler(TreeDraw_ExitHandler, NULL);
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tree_HasNativeGradients --
*
* Determine if this platform supports gradients natively.
*
* Results:
* 1 if GDI+ is available,
* 0 otherwise.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
Tree_HasNativeGradients(
TreeCtrl *tree)
{
return (DllExports.handle != NULL);
}
/* ARGB is a DWORD color used by GDI+ */
static ARGB MakeARGB(BYTE a, BYTE r, BYTE g, BYTE b)
{
return (ARGB) ((((DWORD) a) << 24) | (((DWORD) r) << 16)
| (((DWORD) g) << 8) | ((DWORD) b));
}
static ARGB MakeGDIPlusColor(XColor *xc, double opacity)
{
return MakeARGB(
(BYTE)(opacity*255),
(BYTE)((xc)->pixel & 0xFF),
(BYTE)(((xc)->pixel >> 8) & 0xFF),
(BYTE)(((xc)->pixel >> 16) & 0xFF));
}
typedef struct {
TreeCtrl *tree;
TreeClip *clip;
GpGraphics *graphics;
} TreeClipStateGraphics;
static GpStatus
TreeClip_ToGraphics(
TreeCtrl *tree,
TreeClip *clip,
GpGraphics *graphics,
TreeClipStateGraphics *state
)
{
GpStatus status = Ok;
state->tree = tree;
state->clip = clip;
state->graphics = graphics;
if (clip && clip->type == TREE_CLIP_RECT) {
status = DllExports._GdipSetClipRectI(graphics,
clip->tr.x, clip->tr.y, clip->tr.width, clip->tr.height,
CombineModeReplace);
}
if (clip && clip->type == TREE_CLIP_AREA) {
TreeRectangle tr;
if (Tree_AreaBbox(tree, clip->area, &tr) == 0) {
TreeRect_SetXYWH(tr, 0, 0, 0, 0);
}
status = DllExports._GdipSetClipRectI(graphics,
TreeRect_Left(tr), TreeRect_Top(tr),
TreeRect_Width(tr), TreeRect_Height(tr),
CombineModeReplace);
}
if (clip && clip->type == TREE_CLIP_REGION) {
status = DllExports._GdipSetClipHrgn(graphics, (HRGN) clip->region,
CombineModeReplace);
}
return status;
}
static GpStatus
MakeLinearGradientBrush(
TreeGradient gradient, /* Gradient token. */
TreeRectangle trBrush, /* Brush bounds. */
GpLineGradient **lgPtr /* Result. */
)
{
GpLineGradient *lineGradient;
GpStatus status;
GpRect rect;
GradientStop *stop;
int i, nstops;
ARGB color1, color2;
(*lgPtr) = NULL;
nstops = gradient->stopArrPtr->nstops;
rect.X = trBrush.x, rect.Y = trBrush.y,
rect.Width = trBrush.width, rect.Height = trBrush.height;
/* BUG BUG BUG: A linear gradient brush will *sometimes* wrap when it
* shouldn't due to rounding errors or something, resulting in a line
* of color2 where color1 starts. The recommended solution is to
* make the brush 1-pixel larger on all sides than the area being
* painted. The downside of this is you will lose a bit of the gradient. */
if (gradient->vertical)
rect.Y -= 1, rect.Height += 1;
else
rect.X -= 1, rect.Width += 1;
stop = gradient->stopArrPtr->stops[0];
color1 = MakeGDIPlusColor(stop->color, stop->opacity);
stop = gradient->stopArrPtr->stops[nstops-1];
color2 = MakeGDIPlusColor(stop->color, stop->opacity);
status = DllExports._GdipCreateLineBrushFromRectI(
&rect, color1, color2,
gradient->vertical ? LinearGradientModeVertical : LinearGradientModeHorizontal,
WrapModeTile, &lineGradient);
if (status != Ok)
return status;
if (nstops > 2) {
ARGB *col = DllExports._GdipAlloc(nstops * sizeof(ARGB));
if (col != NULL) {
REAL *pos = DllExports._GdipAlloc(nstops * sizeof(REAL));
if (pos != NULL) {
for (i = 0; i < nstops; i++) {
stop = gradient->stopArrPtr->stops[i];
col[i] = MakeGDIPlusColor(stop->color, stop->opacity);
pos[i] = (REAL)stop->offset;
}
status = DllExports._GdipSetLinePresetBlend(lineGradient,
col, pos, nstops);
DllExports._GdipFree((void*) pos);
}
DllExports._GdipFree((void*) col);
}
}
(*lgPtr) = lineGradient;
return Ok;
}
/*
*----------------------------------------------------------------------
*
* TreeGradient_FillRect --
*
* Paint a rectangle with a gradient using GDI+.
*
* Results:
* If GDI+ isn't available then fall back to X11. If the gradient
* has <2 stops then nothing is drawn.
*
* Side effects:
* Drawing.
*
*----------------------------------------------------------------------
*/
void
TreeGradient_FillRect(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
TreeGradient gradient, /* Gradient token. */
TreeRectangle trBrush, /* Brush bounds. */
TreeRectangle tr /* Rectangle to paint. */
)
{
HDC hDC;
TkWinDCState dcState;
TreeClipStateGraphics clipState;
GpGraphics *graphics;
GpLineGradient *lineGradient = NULL;
GpStatus status;
GpRect rect;
int nstops;
/* Draw nothing if the brush is zero-sized. */
if (trBrush.width <= 0 || trBrush.height <= 0)
return;
if (!tree->nativeGradients || (DllExports.handle == NULL)) {
TreeGradient_FillRectX11(tree, td, clip, gradient, trBrush, tr);
return;
}
nstops = gradient->stopArrPtr ? gradient->stopArrPtr->nstops : 0;
if (nstops < 2) /* can be 0, but < 2 isn't allowed */
return;
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
status = DllExports._GdipCreateFromHDC(hDC, &graphics);
if (status != Ok)
goto error1;
status = TreeClip_ToGraphics(tree, clip, graphics, &clipState);
if (status != Ok)
goto error2;
status = MakeLinearGradientBrush(gradient, trBrush, &lineGradient);
if (status != Ok)
goto error2;
rect.X = tr.x, rect.Y = tr.y, rect.Width = tr.width, rect.Height = tr.height;
DllExports._GdipFillRectangleI(graphics, lineGradient,
rect.X, rect.Y, rect.Width, rect.Height);
DllExports._GdipDeleteBrush(lineGradient);
error2:
DllExports._GdipDeleteGraphics(graphics);
error1:
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
#ifdef TREECTRL_DEBUG
if (status != Ok) dbwin("TreeGradient_FillRect gdiplus status != Ok");
#endif
}
static void
GetRectPath_Outline(
GpPath *path, /* GDI+ path to set. */
TreeRectangle tr, /* Rectangle to draw. */
int open, /* RECT_OPEN_x flags. */
int outlineWidth /* Thickness of the outline. */
)
{
REAL x = (REAL)tr.x, y = (REAL)tr.y, width = (REAL)tr.width, height = (REAL)tr.height;
int drawW = (open & RECT_OPEN_W) == 0;
int drawN = (open & RECT_OPEN_N) == 0;
int drawE = (open & RECT_OPEN_E) == 0;
int drawS = (open & RECT_OPEN_S) == 0;
/* Weird issue, if outlineWidth == 1 the NW corner is missing a pixel,
* even when calling GdipAddPathRectangle. So don't draw on the 1/2
* pixel boundary in that case. */
if (outlineWidth > 1) {
x += outlineWidth / 2.0f, y += outlineWidth / 2.0f;
}
width -= outlineWidth, height -= outlineWidth;
/* Simple case: draw all 4 edges */
if (drawW && drawN && drawE && drawS) {
DllExports._GdipAddPathRectangle(path, x, y, width, height);
/* Complicated case: some edges are "open" */
} else {
if (drawN)
DllExports._GdipAddPathLine(path, x, y, x + width, y);
if (drawE)
DllExports._GdipAddPathLine(path, x + width, y, x + width, y + height);
else if (drawN)
DllExports._GdipStartPathFigure(path);
if (drawS)
DllExports._GdipAddPathLine(path, x + width, y + height, x, y + height);
else if (drawE)
DllExports._GdipStartPathFigure(path);
if (drawW)
DllExports._GdipAddPathLine(path, x, y + height, x, y);
}
}
void
TreeGradient_DrawRect(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
TreeGradient gradient, /* Gradient. */
TreeRectangle trBrush, /* Brush bounds. */
TreeRectangle tr, /* Rectangle to draw. */
int outlineWidth, /* Width of outline. */
int open /* RECT_OPEN_x flags */
)
{
HDC hDC;
TkWinDCState dcState;
TreeClipStateGraphics clipState;
GpGraphics *graphics;
GpPath *path;
GpLineGradient *lineGradient;
GpPen *pen;
GpStatus status;
if (gradient->stopArrPtr == NULL || gradient->stopArrPtr->nstops < 2)
return;
/* Draw nothing if the brush is zero-sized. */
if (trBrush.width <= 0 || trBrush.height <= 0)
return;
if (!tree->nativeGradients || (DllExports.handle == NULL)) {
TreeGradient_DrawRectX11(tree, td, clip, gradient, trBrush, tr, outlineWidth, open);
return;
}
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
status = DllExports._GdipCreateFromHDC(hDC, &graphics);
if (status != Ok)
goto error1;
status = DllExports._GdipCreatePath(FillModeAlternate, &path);
if (status != Ok)
goto error2;
status = MakeLinearGradientBrush(gradient, trBrush, &lineGradient);
if (status != Ok)
goto error3;
status = DllExports._GdipCreatePen2(lineGradient, (REAL) outlineWidth,
UnitPixel, &pen);
if (status != Ok)
goto error4;
status = TreeClip_ToGraphics(tree, clip, graphics, &clipState);
if (status != Ok)
goto error5;
GetRectPath_Outline(path, tr, open, outlineWidth);
DllExports._GdipSetPenStartCap(pen, LineCapSquare);
DllExports._GdipSetPenEndCap(pen, LineCapSquare);
DllExports._GdipDrawPath(graphics, pen, path);
error5:
DllExports._GdipDeletePen(pen);
error4:
DllExports._GdipDeleteBrush(path);
error3:
DllExports._GdipDeletePath(path);
error2:
DllExports._GdipDeleteGraphics(graphics);
error1:
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
}
static void
GetRoundRectPath_Outline(
GpPath *path, /* GDI+ path to set. */
TreeRectangle tr, /* Rectangle to draw. */
int rx, int ry, /* Corner radius. */
int open, /* RECT_OPEN_x flags. */
int fudgeX, /* Fix for "open" edge endpoints when */
int fudgeY, /* outlineWidth>1. */
int outlineWidth
)
{
REAL x = (REAL)tr.x, y = (REAL)tr.y, width = (REAL)tr.width, height = (REAL)tr.height;
int drawW = (open & RECT_OPEN_W) == 0;
int drawN = (open & RECT_OPEN_N) == 0;
int drawE = (open & RECT_OPEN_E) == 0;
int drawS = (open & RECT_OPEN_S) == 0;
if (outlineWidth > 0) {
x += outlineWidth / 2.0f, y += outlineWidth / 2.0f;
width -= outlineWidth, height -= outlineWidth;
} else {
width -= 1, height -= 1;
}
/* Simple case: draw all 4 corners and 4 edges */
if (drawW && drawN && drawE && drawS) {
DllExports._GdipAddPathArc(path, x, y, rx*2.0f, ry*2.0f, 180.0f, 90.0f); /* top-left */
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y, rx*2.0f, ry*2.0f, 270.0f, 90.0f); /* top-right */
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 0.0f, 90.0f); /* bottom-right */
DllExports._GdipAddPathArc(path, x, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 90.0f, 90.0f); /* bottom-left */
DllExports._GdipClosePathFigure(path);
/* Complicated case: some edges are "open" */
} else {
GpPointF start[4], end[4]; /* start and end points of line segments*/
start[0].X = x, start[0].Y = y;
end[3] = start[0];
if (drawW && drawN) {
start[0].X += rx;
end[3].Y += ry;
} else {
start[0].X -= fudgeX;
end[3].Y -= fudgeY;
}
end[0].X = x + width, end[0].Y = y;
start[1]= end[0];
if (drawE && drawN) {
end[0].X -= rx;
start[1].Y += ry;
} else {
end[0].X += fudgeX;
start[1].Y -= fudgeY;
}
end[1].X = x + width, end[1].Y = y + height;
start[2] = end[1];
if (drawE && drawS) {
end[1].Y -= ry;
start[2].X -= rx;
} else {
end[1].Y += fudgeY;
start[2].X += fudgeX;
}
end[2].X = x, end[2].Y = y + height;
start[3] = end[2];
if (drawW && drawS) {
end[2].X += rx;
start[3].Y -= ry;
} else {
end[2].X -= fudgeX;
start[3].Y += fudgeY;
}
if (drawW && drawN)
DllExports._GdipAddPathArc(path, x, y, rx*2.0f, ry*2.0f, 180.0f, 90.0f); /* top-left */
if (drawN)
DllExports._GdipAddPathLine(path, start[0].X, start[0].Y, end[0].X, end[0].Y);
if (drawE && drawN)
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y, rx*2.0f, ry*2.0f, 270.0f, 90.0f); /* top-right */
if (drawE)
DllExports._GdipAddPathLine(path, start[1].X, start[1].Y, end[1].X, end[1].Y);
else if (drawN)
DllExports._GdipStartPathFigure(path);
if (drawE && drawS)
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 0.0f, 90.0f); /* bottom-right */
if (drawS)
DllExports._GdipAddPathLine(path, start[2].X, start[2].Y, end[2].X, end[2].Y);
else if (drawE)
DllExports._GdipStartPathFigure(path);
if (drawW && drawS)
DllExports._GdipAddPathArc(path, x, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 90.0f, 90.0f); /* bottom-left */
if (drawW)
DllExports._GdipAddPathLine(path, start[3].X, start[3].Y, end[3].X, end[3].Y);
}
}
void
Tree_DrawRoundRect(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
XColor *xcolor, /* Color. */
TreeRectangle tr, /* Rectangle to draw. */
int outlineWidth, /* Width of outline. */
int rx, int ry, /* Corner radius */
int open /* RECT_OPEN_x flags */
)
{
HDC hDC;
TkWinDCState dcState;
TreeClipStateGraphics clipState;
GpGraphics *graphics;
GpPath *path;
ARGB color;
GpPen *pen;
GpStatus status;
int i;
if (!tree->nativeGradients || (DllExports.handle == NULL)) {
GC gc = Tk_GCForColor(xcolor, td.drawable);
Tree_DrawRoundRectX11(tree, td, clip, gc, tr, outlineWidth, rx, ry, open);
return;
}
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
status = DllExports._GdipCreateFromHDC(hDC, &graphics);
if (status != Ok)
goto error1;
status = DllExports._GdipCreatePath(FillModeAlternate, &path);
if (status != Ok)
goto error2;
color = MakeGDIPlusColor(xcolor,1.0f);
status = DllExports._GdipCreatePen1(color, 1, UnitPixel, &pen);
if (status != Ok)
goto error3;
status = TreeClip_ToGraphics(tree, clip, graphics, &clipState);
if (status != Ok)
goto error3;
GetRoundRectPath_Outline(path, tr, rx, ry, open, 0, 0, 0);
DllExports._GdipDrawPath(graphics, pen, path);
/* http://www.codeproject.com/KB/GDI-plus/RoundRect.aspx */
for (i = 1; i < outlineWidth; i++) {
tr.x += 1, tr.width -= 2;
DllExports._GdipResetPath(path);
GetRoundRectPath_Outline(path, tr, rx, ry, open, i, i-1, 0);
DllExports._GdipDrawPath(graphics, pen, path);
tr.y += 1, tr.height -= 2;
DllExports._GdipResetPath(path);
GetRoundRectPath_Outline(path, tr, rx, ry, open, i, i, 0);
DllExports._GdipDrawPath(graphics, pen, path);
}
DllExports._GdipDeletePen(pen);
error3:
DllExports._GdipDeletePath(path);
error2:
DllExports._GdipDeleteGraphics(graphics);
error1:
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
}
void
TreeGradient_DrawRoundRect(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
TreeGradient gradient, /* Gradient. */
TreeRectangle trBrush, /* Brush bounds. */
TreeRectangle tr, /* Rectangle to draw. */
int outlineWidth, /* Width of outline. */
int rx, int ry, /* Corner radius */
int open /* RECT_OPEN_x flags */
)
{
HDC hDC;
TkWinDCState dcState;
TreeClipStateGraphics clipState;
GpGraphics *graphics;
GpPath *path;
GpLineGradient *lineGradient;
GpPen *pen;
GpStatus status;
int i;
int canRepairCorners;
if (gradient->stopArrPtr == NULL || gradient->stopArrPtr->nstops < 2)
return;
/* Draw nothing if the brush is zero-sized. */
if (trBrush.width <= 0 || trBrush.height <= 0)
return;
if (!tree->nativeGradients || (DllExports.handle == NULL)) {
XColor *xcolor = gradient->stopArrPtr->stops[0]->color; /* Use the first stop color */
GC gc = Tk_GCForColor(xcolor, td.drawable);
Tree_DrawRoundRectX11(tree, td, clip, gc, tr, outlineWidth, rx, ry, open);
return;
}
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
status = DllExports._GdipCreateFromHDC(hDC, &graphics);
if (status != Ok)
goto error1;
status = DllExports._GdipCreatePath(FillModeAlternate, &path);
if (status != Ok)
goto error2;
status = MakeLinearGradientBrush(gradient, trBrush, &lineGradient);
if (status != Ok)
goto error3;
canRepairCorners = (outlineWidth == 1) || TreeGradient_IsOpaque(tree, gradient);
status = DllExports._GdipCreatePen2(lineGradient, canRepairCorners ?
1.0f : (REAL) outlineWidth, UnitPixel, &pen);
if (status != Ok)
goto error4;
status = TreeClip_ToGraphics(tree, clip, graphics, &clipState);
if (status != Ok)
goto error5;
GetRoundRectPath_Outline(path, tr, rx, ry, open, 0, 0,
canRepairCorners ? 0 : outlineWidth);
DllExports._GdipDrawPath(graphics, pen, path);
/* http://www.codeproject.com/KB/GDI-plus/RoundRect.aspx */
if (canRepairCorners) {
for (i = 1; i < outlineWidth; i++) {
tr.x += 1, tr.width -= 2;
DllExports._GdipResetPath(path);
GetRoundRectPath_Outline(path, tr, rx, ry, open, i, i-1, 0);
DllExports._GdipDrawPath(graphics, pen, path);
tr.y += 1, tr.height -= 2;
DllExports._GdipResetPath(path);
GetRoundRectPath_Outline(path, tr, rx, ry, open, i, i, 0);
DllExports._GdipDrawPath(graphics, pen, path);
}
}
error5:
DllExports._GdipDeletePen(pen);
error4:
DllExports._GdipDeleteBrush(path);
error3:
DllExports._GdipDeletePath(path);
error2:
DllExports._GdipDeleteGraphics(graphics);
error1:
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
}
#define ROUND_RECT_SYMMETRY_HACK
/* This returns a path 1-pixel smaller on the right and bottom edges than
* it should be.
* For some reason GdipFillPath produces different (and asymmetric) results
* than GdipDrawPath. So after filling the round rectangle with this path
* GetRoundRectPath_Outline should be called to paint the right and bottom
* edges. */
/* http://www.codeproject.com/KB/GDI-plus/RoundRect.aspx */
static void
GetRoundRectPath_Fill(
GpPath *path, /* GDI+ path to set. */
TreeRectangle tr, /* Rectangle to paint. */
int rx, int ry, /* Corner radius. */
int open /* RECT_OPEN_x flags. */
#ifdef ROUND_RECT_SYMMETRY_HACK
, int rrhack
#endif
)
{
REAL x = (REAL)tr.x, y = (REAL)tr.y, width = (REAL)tr.width, height = (REAL)tr.height;
int drawW = (open & RECT_OPEN_W) == 0;
int drawN = (open & RECT_OPEN_N) == 0;
int drawE = (open & RECT_OPEN_E) == 0;
int drawS = (open & RECT_OPEN_S) == 0;
/* Simple case: draw all 4 corners and 4 edges */
if (drawW && drawN && drawE && drawS) {
#ifdef ROUND_RECT_SYMMETRY_HACK
if (rrhack)
width -= 1, height -= 1;
#endif
DllExports._GdipAddPathArc(path, x, y, rx*2.0f, ry*2.0f, 180.0f, 90.0f); /* top-left */
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y, rx*2.0f, ry*2.0f, 270.0f, 90.0f); /* top-right */
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 0.0f, 90.0f); /* bottom-right */
DllExports._GdipAddPathArc(path, x, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 90.0f, 90.0f); /* bottom-left */
DllExports._GdipClosePathFigure(path);
/* Complicated case: some edges are "open" */
} else {
GpPointF start[4], end[4]; /* start and end points of line segments*/
#ifdef ROUND_RECT_SYMMETRY_HACK
if (rrhack) {
if (drawE)
width -= 1;
if (drawS)
height -= 1;
}
#endif
start[0].X = x, start[0].Y = y;
end[3] = start[0];
if (drawW && drawN) {
start[0].X += rx;
end[3].Y += ry;
}
end[0].X = x + width, end[0].Y = y;
start[1]= end[0];
if (drawE && drawN) {
end[0].X -= rx;
start[1].Y += ry;
}
end[1].X = x + width, end[1].Y = y + height;
start[2] = end[1];
if (drawE && drawS) {
end[1].Y -= ry;
start[2].X -= rx;
}
end[2].X = x, end[2].Y = y + height;
start[3] = end[2];
if (drawW && drawS) {
end[2].X += rx;
start[3].Y -= ry;
}
if (drawW && drawN)
DllExports._GdipAddPathArc(path, x, y, rx*2.0f, ry*2.0f, 180.0f, 90.0f); /* top-left */
DllExports._GdipAddPathLine(path, start[0].X, start[0].Y, end[0].X, end[0].Y);
if (drawE && drawN)
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y, rx*2.0f, ry*2.0f, 270.0f, 90.0f); /* top-right */
DllExports._GdipAddPathLine(path, start[1].X, start[1].Y, end[1].X, end[1].Y);
if (drawE && drawS)
DllExports._GdipAddPathArc(path, x + width - rx*2.0f, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 0.0f, 90.0f); /* bottom-right */
DllExports._GdipAddPathLine(path, start[2].X, start[2].Y, end[2].X, end[2].Y);
if (drawW && drawS)
DllExports._GdipAddPathArc(path, x, y + height - ry*2.0f, rx*2.0f, ry*2.0f, 90.0f, 90.0f); /* bottom-left */
DllExports._GdipAddPathLine(path, start[3].X, start[3].Y, end[3].X, end[3].Y);
}
}
void
Tree_FillRoundRect(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
XColor *xcolor, /* Color. */
TreeRectangle tr, /* Recangle to paint. */
int rx, int ry, /* Corner radius */
int open /* RECT_OPEN_x flags */
)
{
HDC hDC;
TkWinDCState dcState;
TreeClipStateGraphics clipState;
GpGraphics *graphics;
GpPath *path;
ARGB color;
GpSolidFill *brush;
#ifdef ROUND_RECT_SYMMETRY_HACK
GpPen *pen;
#endif
GpStatus status;
if (!tree->nativeGradients || (DllExports.handle == NULL)) {
GC gc = Tk_GCForColor(xcolor, td.drawable);
Tree_FillRoundRectX11(tree, td, clip, gc, tr, rx, ry, open);
return;
}
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
status = DllExports._GdipCreateFromHDC(hDC, &graphics);
if (status != Ok)
goto error1;
status = DllExports._GdipCreatePath(FillModeAlternate, &path);
if (status != Ok)
goto error2;
color = MakeGDIPlusColor(xcolor,1.0f);
status = DllExports._GdipCreateSolidFill(color, &brush);
if (status != Ok)
goto error3;
#if !defined(ROUND_RECT_SYMMETRY_HACK) && 0
/* SmoothingModeHighQuality and SmoothingModeAntiAlias seem the same. */
DllExports._GdipSetSmoothingMode(graphics, SmoothingModeHighQuality);
/* Antialiasing paints outside the rectangle. If I clip drawing to the
* rectangle I still get artifacts on the "open" edges. */
// status = DllExports._GdipSetClipRectI(graphics,
// tr.x, tr.y, tr.width, tr.height, CombineModeReplace);
#endif
GetRoundRectPath_Fill(path, tr, rx, ry, open
#ifdef ROUND_RECT_SYMMETRY_HACK
, 1
#endif
);
status = TreeClip_ToGraphics(tree, clip, graphics, &clipState);
if (status != Ok)
goto error4;
DllExports._GdipFillPath(graphics, brush, path);
#ifdef ROUND_RECT_SYMMETRY_HACK
status = DllExports._GdipCreatePen1(color, 1, UnitPixel, &pen);
if (status != Ok)
goto error4;
/* See comments above for why this is done */
DllExports._GdipResetPath(path);
GetRoundRectPath_Outline(path, tr, rx, ry, open, 0, 0, 0);
DllExports._GdipDrawPath(graphics, pen, path);
DllExports._GdipDeletePen(pen);
#endif /* ROUND_RECT_SYMMETRY_HACK */
error4:
DllExports._GdipDeleteBrush(brush);
error3:
DllExports._GdipDeletePath(path);
error2:
DllExports._GdipDeleteGraphics(graphics);
error1:
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
}
void
TreeGradient_FillRoundRect(
TreeCtrl *tree, /* Widget info. */
TreeDrawable td, /* Where to draw. */
TreeClip *clip, /* Clipping area or NULL. */
TreeGradient gradient, /* Gradient token. */
TreeRectangle trBrush, /* Brush bounds. */
TreeRectangle tr, /* Rectangle to paint. */
int rx, int ry, /* Corner radius */
int open /* RECT_OPEN_x flags */
)
{
HDC hDC;
TkWinDCState dcState;
TreeClipStateGraphics clipState;
GpGraphics *graphics;
GpPath *path;
GpLineGradient *lineGradient;
GpPen *pen;
GpStatus status;
int canRepairCorners;
if (gradient->stopArrPtr == NULL || gradient->stopArrPtr->nstops < 2)
return;
/* Draw nothing if the brush is zero-sized. */
if (trBrush.width <= 0 || trBrush.height <= 0)
return;
if (!tree->nativeGradients || (DllExports.handle == NULL)) {
TreeGradient_FillRoundRectX11(tree, td, NULL, gradient, trBrush, tr,
rx, ry, open);
return;
}
hDC = TkWinGetDrawableDC(tree->display, td.drawable, &dcState);
status = DllExports._GdipCreateFromHDC(hDC, &graphics);
if (status != Ok)
goto error1;
status = DllExports._GdipCreatePath(FillModeAlternate, &path);
if (status != Ok)
goto error2;
status = MakeLinearGradientBrush(gradient, trBrush, &lineGradient);
if (status != Ok)
goto error3;
/* Filling the rounded rectangle gives asymmetric results at the corners.
* If the gradient is fully opaque then the corners can be "repaired" by
* drawing a 1-pixel thick outline after filling the shape. */
canRepairCorners = TreeGradient_IsOpaque(tree, gradient);
GetRoundRectPath_Fill(path, tr, rx, ry, open
#ifdef ROUND_RECT_SYMMETRY_HACK
, canRepairCorners
#endif
);
status = TreeClip_ToGraphics(tree, clip, graphics, &clipState);
if (status != Ok)
goto error4;
DllExports._GdipFillPath(graphics, lineGradient, path);
if (canRepairCorners) {
status = DllExports._GdipCreatePen2(lineGradient, 1, UnitPixel, &pen);
if (status != Ok)
goto error4;
DllExports._GdipResetPath(path);
GetRoundRectPath_Outline(path, tr, rx, ry, open, 0, 0, 0);
DllExports._GdipDrawPath(graphics, pen, path);
DllExports._GdipDeletePen(pen);
}
error4:
DllExports._GdipDeleteBrush(lineGradient);
error3:
DllExports._GdipDeletePath(path);
error2:
DllExports._GdipDeleteGraphics(graphics);
error1:
TkWinReleaseDrawableDC(td.drawable, hDC, &dcState);
}
|
{
"content_hash": "18b5e453afe047c8f13a8ffdebe85ca4",
"timestamp": "",
"source": "github",
"line_count": 3986,
"max_line_length": 139,
"avg_line_length": 26.396638233818365,
"alnum_prop": 0.6100820209661937,
"repo_name": "bitkeeper-scm/bitkeeper",
"id": "1eb8340751e813f65d0fecf4966b77ef0dea37f8",
"size": "105348",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/gui/tcltk/tktreectrl/win/tkWinTree.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "138638"
},
{
"name": "Awk",
"bytes": "537"
},
{
"name": "Batchfile",
"bytes": "17857"
},
{
"name": "BlitzBasic",
"bytes": "194161"
},
{
"name": "C",
"bytes": "28873391"
},
{
"name": "C#",
"bytes": "54012"
},
{
"name": "C++",
"bytes": "863164"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "28687"
},
{
"name": "CSS",
"bytes": "2606"
},
{
"name": "Common Lisp",
"bytes": "1386"
},
{
"name": "DIGITAL Command Language",
"bytes": "31087"
},
{
"name": "DTrace",
"bytes": "7347"
},
{
"name": "Emacs Lisp",
"bytes": "205568"
},
{
"name": "HTML",
"bytes": "1374203"
},
{
"name": "JavaScript",
"bytes": "6682"
},
{
"name": "Jolie",
"bytes": "3956"
},
{
"name": "Lex",
"bytes": "189720"
},
{
"name": "Logos",
"bytes": "168703"
},
{
"name": "M4",
"bytes": "744535"
},
{
"name": "Makefile",
"bytes": "506590"
},
{
"name": "Module Management System",
"bytes": "3093"
},
{
"name": "Objective-C",
"bytes": "220655"
},
{
"name": "Pascal",
"bytes": "94171"
},
{
"name": "Perl",
"bytes": "125543"
},
{
"name": "Perl 6",
"bytes": "1129"
},
{
"name": "PostScript",
"bytes": "130437"
},
{
"name": "Python",
"bytes": "48455"
},
{
"name": "R",
"bytes": "1390"
},
{
"name": "Roff",
"bytes": "4316683"
},
{
"name": "Ruby",
"bytes": "4837"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "742546"
},
{
"name": "Tcl",
"bytes": "4829953"
},
{
"name": "TeX",
"bytes": "677682"
},
{
"name": "Vim script",
"bytes": "385"
},
{
"name": "Yacc",
"bytes": "64491"
},
{
"name": "sed",
"bytes": "2377"
}
],
"symlink_target": ""
}
|
using extensions::Extension;
using extensions::ExtensionPrefs;
using extensions::ExtensionRegistry;
using extensions::FeatureSwitch;
namespace {
void OnWebApplicationInfoLoaded(
WebApplicationInfo synced_info,
base::WeakPtr<ExtensionService> extension_service,
const WebApplicationInfo& loaded_info) {
DCHECK_EQ(synced_info.app_url, loaded_info.app_url);
if (!extension_service)
return;
// Use the old icons if they exist.
synced_info.icons = loaded_info.icons;
CreateOrUpdateBookmarkApp(extension_service.get(), &synced_info);
}
} // namespace
ExtensionSyncService::ExtensionSyncService(Profile* profile,
ExtensionPrefs* extension_prefs,
ExtensionService* extension_service)
: profile_(profile),
extension_prefs_(extension_prefs),
extension_service_(extension_service),
app_sync_bundle_(this),
extension_sync_bundle_(this),
pending_app_enables_(make_scoped_ptr(new sync_driver::SyncPrefs(
extension_prefs_->pref_service())),
&app_sync_bundle_,
syncer::APPS),
pending_extension_enables_(make_scoped_ptr(new sync_driver::SyncPrefs(
extension_prefs_->pref_service())),
&extension_sync_bundle_,
syncer::EXTENSIONS) {
SetSyncStartFlare(sync_start_util::GetFlareForSyncableService(
profile_->GetPath()));
extension_service_->set_extension_sync_service(this);
extension_prefs_->app_sorting()->SetExtensionSyncService(this);
}
ExtensionSyncService::~ExtensionSyncService() {}
// static
ExtensionSyncService* ExtensionSyncService::Get(Profile* profile) {
return ExtensionSyncServiceFactory::GetForProfile(profile);
}
syncer::SyncChange ExtensionSyncService::PrepareToSyncUninstallExtension(
const extensions::Extension* extension, bool extensions_ready) {
// Extract the data we need for sync now, but don't actually sync until we've
// completed the uninstallation.
// TODO(tim): If we get here and IsSyncing is false, this will cause
// "back from the dead" style bugs, because sync will add-back the extension
// that was uninstalled here when MergeDataAndStartSyncing is called.
// See crbug.com/256795.
if (extensions::util::ShouldSyncApp(extension, profile_)) {
if (app_sync_bundle_.IsSyncing())
return app_sync_bundle_.CreateSyncChangeToDelete(extension);
else if (extensions_ready && !flare_.is_null())
flare_.Run(syncer::APPS); // Tell sync to start ASAP.
} else if (extensions::sync_helper::IsSyncableExtension(extension)) {
if (extension_sync_bundle_.IsSyncing())
return extension_sync_bundle_.CreateSyncChangeToDelete(extension);
else if (extensions_ready && !flare_.is_null())
flare_.Run(syncer::EXTENSIONS); // Tell sync to start ASAP.
}
return syncer::SyncChange();
}
void ExtensionSyncService::ProcessSyncUninstallExtension(
const std::string& extension_id,
const syncer::SyncChange& sync_change) {
if (app_sync_bundle_.HasExtensionId(extension_id) &&
sync_change.sync_data().GetDataType() == syncer::APPS) {
app_sync_bundle_.ProcessDeletion(extension_id, sync_change);
} else if (extension_sync_bundle_.HasExtensionId(extension_id) &&
sync_change.sync_data().GetDataType() == syncer::EXTENSIONS) {
extension_sync_bundle_.ProcessDeletion(extension_id, sync_change);
}
}
void ExtensionSyncService::SyncEnableExtension(
const extensions::Extension& extension) {
// Syncing may not have started yet, so handle pending enables.
if (extensions::util::ShouldSyncApp(&extension, profile_))
pending_app_enables_.OnExtensionEnabled(extension.id());
if (extensions::util::ShouldSyncExtension(&extension, profile_))
pending_extension_enables_.OnExtensionEnabled(extension.id());
SyncExtensionChangeIfNeeded(extension);
}
void ExtensionSyncService::SyncDisableExtension(
const extensions::Extension& extension) {
// Syncing may not have started yet, so handle pending enables.
if (extensions::util::ShouldSyncApp(&extension, profile_))
pending_app_enables_.OnExtensionDisabled(extension.id());
if (extensions::util::ShouldSyncExtension(&extension, profile_))
pending_extension_enables_.OnExtensionDisabled(extension.id());
SyncExtensionChangeIfNeeded(extension);
}
syncer::SyncMergeResult ExtensionSyncService::MergeDataAndStartSyncing(
syncer::ModelType type,
const syncer::SyncDataList& initial_sync_data,
scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) {
CHECK(sync_processor.get());
CHECK(sync_error_factory.get());
switch (type) {
case syncer::EXTENSIONS:
extension_sync_bundle_.SetupSync(sync_processor.release(),
sync_error_factory.release(),
initial_sync_data);
pending_extension_enables_.OnSyncStarted(extension_service_);
break;
case syncer::APPS:
app_sync_bundle_.SetupSync(sync_processor.release(),
sync_error_factory.release(),
initial_sync_data);
pending_app_enables_.OnSyncStarted(extension_service_);
break;
default:
LOG(FATAL) << "Got " << type << " ModelType";
}
// Process local extensions.
// TODO(yoz): Determine whether pending extensions should be considered too.
// See crbug.com/104399.
syncer::SyncDataList sync_data_list = GetAllSyncData(type);
syncer::SyncChangeList sync_change_list;
for (syncer::SyncDataList::const_iterator i = sync_data_list.begin();
i != sync_data_list.end();
++i) {
switch (type) {
case syncer::EXTENSIONS:
sync_change_list.push_back(
extension_sync_bundle_.CreateSyncChange(*i));
break;
case syncer::APPS:
sync_change_list.push_back(app_sync_bundle_.CreateSyncChange(*i));
break;
default:
LOG(FATAL) << "Got " << type << " ModelType";
}
}
if (type == syncer::EXTENSIONS) {
extension_sync_bundle_.ProcessSyncChangeList(sync_change_list);
} else if (type == syncer::APPS) {
app_sync_bundle_.ProcessSyncChangeList(sync_change_list);
}
return syncer::SyncMergeResult(type);
}
void ExtensionSyncService::StopSyncing(syncer::ModelType type) {
if (type == syncer::APPS) {
app_sync_bundle_.Reset();
} else if (type == syncer::EXTENSIONS) {
extension_sync_bundle_.Reset();
}
}
syncer::SyncDataList ExtensionSyncService::GetAllSyncData(
syncer::ModelType type) const {
if (type == syncer::EXTENSIONS)
return extension_sync_bundle_.GetAllSyncData();
if (type == syncer::APPS)
return app_sync_bundle_.GetAllSyncData();
// We should only get sync data for extensions and apps.
NOTREACHED();
return syncer::SyncDataList();
}
syncer::SyncError ExtensionSyncService::ProcessSyncChanges(
const tracked_objects::Location& from_here,
const syncer::SyncChangeList& change_list) {
for (syncer::SyncChangeList::const_iterator i = change_list.begin();
i != change_list.end();
++i) {
syncer::ModelType type = i->sync_data().GetDataType();
if (type == syncer::EXTENSIONS) {
extension_sync_bundle_.ProcessSyncChange(
extensions::ExtensionSyncData(*i));
} else if (type == syncer::APPS) {
app_sync_bundle_.ProcessSyncChange(extensions::AppSyncData(*i));
}
}
extension_prefs_->app_sorting()->FixNTPOrdinalCollisions();
return syncer::SyncError();
}
extensions::ExtensionSyncData ExtensionSyncService::GetExtensionSyncData(
const Extension& extension) const {
return extensions::ExtensionSyncData(
extension,
extension_service_->IsExtensionEnabled(extension.id()),
extensions::util::IsIncognitoEnabled(extension.id(), profile_),
extension_prefs_->HasDisableReason(extension.id(),
Extension::DISABLE_REMOTE_INSTALL));
}
extensions::AppSyncData ExtensionSyncService::GetAppSyncData(
const Extension& extension) const {
return extensions::AppSyncData(
extension,
extension_service_->IsExtensionEnabled(extension.id()),
extensions::util::IsIncognitoEnabled(extension.id(), profile_),
extension_prefs_->HasDisableReason(extension.id(),
Extension::DISABLE_REMOTE_INSTALL),
extension_prefs_->app_sorting()->GetAppLaunchOrdinal(extension.id()),
extension_prefs_->app_sorting()->GetPageOrdinal(extension.id()),
extensions::GetLaunchTypePrefValue(extension_prefs_, extension.id()));
}
std::vector<extensions::ExtensionSyncData>
ExtensionSyncService::GetExtensionSyncDataList() const {
ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
std::vector<extensions::ExtensionSyncData> extension_sync_list;
extension_sync_bundle_.GetExtensionSyncDataListHelper(
registry->enabled_extensions(), &extension_sync_list);
extension_sync_bundle_.GetExtensionSyncDataListHelper(
registry->disabled_extensions(), &extension_sync_list);
extension_sync_bundle_.GetExtensionSyncDataListHelper(
registry->terminated_extensions(), &extension_sync_list);
std::vector<extensions::ExtensionSyncData> pending_extensions =
extension_sync_bundle_.GetPendingData();
extension_sync_list.insert(extension_sync_list.begin(),
pending_extensions.begin(),
pending_extensions.end());
return extension_sync_list;
}
std::vector<extensions::AppSyncData> ExtensionSyncService::GetAppSyncDataList()
const {
ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
std::vector<extensions::AppSyncData> app_sync_list;
app_sync_bundle_.GetAppSyncDataListHelper(
registry->enabled_extensions(), &app_sync_list);
app_sync_bundle_.GetAppSyncDataListHelper(
registry->disabled_extensions(), &app_sync_list);
app_sync_bundle_.GetAppSyncDataListHelper(
registry->terminated_extensions(), &app_sync_list);
std::vector<extensions::AppSyncData> pending_apps =
app_sync_bundle_.GetPendingData();
app_sync_list.insert(app_sync_list.begin(),
pending_apps.begin(),
pending_apps.end());
return app_sync_list;
}
bool ExtensionSyncService::ProcessExtensionSyncData(
const extensions::ExtensionSyncData& extension_sync_data) {
if (!ProcessExtensionSyncDataHelper(extension_sync_data,
syncer::EXTENSIONS)) {
extension_sync_bundle_.AddPendingExtension(extension_sync_data.id(),
extension_sync_data);
extension_service_->CheckForUpdatesSoon();
return false;
}
return true;
}
bool ExtensionSyncService::ProcessAppSyncData(
const extensions::AppSyncData& app_sync_data) {
const std::string& id = app_sync_data.id();
if (app_sync_data.app_launch_ordinal().IsValid() &&
app_sync_data.page_ordinal().IsValid()) {
extension_prefs_->app_sorting()->SetAppLaunchOrdinal(
id,
app_sync_data.app_launch_ordinal());
extension_prefs_->app_sorting()->SetPageOrdinal(
id,
app_sync_data.page_ordinal());
}
// The corresponding validation of this value during AppSyncData population
// is in AppSyncData::PopulateAppSpecifics.
if (app_sync_data.launch_type() >= extensions::LAUNCH_TYPE_FIRST &&
app_sync_data.launch_type() < extensions::NUM_LAUNCH_TYPES) {
extensions::SetLaunchType(extension_service_, id,
app_sync_data.launch_type());
}
if (!app_sync_data.bookmark_app_url().empty())
ProcessBookmarkAppSyncData(app_sync_data);
if (!ProcessExtensionSyncDataHelper(app_sync_data.extension_sync_data(),
syncer::APPS)) {
app_sync_bundle_.AddPendingApp(id, app_sync_data);
extension_service_->CheckForUpdatesSoon();
return false;
}
return true;
}
void ExtensionSyncService::ProcessBookmarkAppSyncData(
const extensions::AppSyncData& app_sync_data) {
// Process bookmark app sync if necessary.
GURL bookmark_app_url(app_sync_data.bookmark_app_url());
if (!bookmark_app_url.is_valid() ||
app_sync_data.extension_sync_data().uninstalled()) {
return;
}
const extensions::Extension* extension =
extension_service_->GetInstalledExtension(
app_sync_data.extension_sync_data().id());
// Return if there are no bookmark app details that need updating.
if (extension && extension->non_localized_name() ==
app_sync_data.extension_sync_data().name() &&
extension->description() == app_sync_data.bookmark_app_description()) {
return;
}
WebApplicationInfo web_app_info;
web_app_info.app_url = bookmark_app_url;
web_app_info.title =
base::UTF8ToUTF16(app_sync_data.extension_sync_data().name());
web_app_info.description =
base::UTF8ToUTF16(app_sync_data.bookmark_app_description());
if (!app_sync_data.bookmark_app_icon_color().empty()) {
extensions::image_util::ParseCSSColorString(
app_sync_data.bookmark_app_icon_color(),
&web_app_info.generated_icon_color);
}
// If the bookmark app already exists, keep the old icons.
if (!extension) {
CreateOrUpdateBookmarkApp(extension_service_, &web_app_info);
} else {
app_sync_data.extension_sync_data().name();
GetWebApplicationInfoFromApp(profile_,
extension,
base::Bind(&OnWebApplicationInfoLoaded,
web_app_info,
extension_service_->AsWeakPtr()));
}
}
void ExtensionSyncService::SyncOrderingChange(const std::string& extension_id) {
const extensions::Extension* ext = extension_service_->GetInstalledExtension(
extension_id);
if (ext)
SyncExtensionChangeIfNeeded(*ext);
}
void ExtensionSyncService::SetSyncStartFlare(
const syncer::SyncableService::StartSyncFlare& flare) {
flare_ = flare;
}
bool ExtensionSyncService::IsCorrectSyncType(const Extension& extension,
syncer::ModelType type) const {
if (type == syncer::EXTENSIONS &&
extensions::sync_helper::IsSyncableExtension(&extension)) {
return true;
}
if (type == syncer::APPS &&
extensions::sync_helper::IsSyncableApp(&extension)) {
return true;
}
return false;
}
bool ExtensionSyncService::IsPendingEnable(
const std::string& extension_id) const {
return pending_app_enables_.Contains(extension_id) ||
pending_extension_enables_.Contains(extension_id);
}
bool ExtensionSyncService::ProcessExtensionSyncDataHelper(
const extensions::ExtensionSyncData& extension_sync_data,
syncer::ModelType type) {
const std::string& id = extension_sync_data.id();
const Extension* extension = extension_service_->GetInstalledExtension(id);
// TODO(bolms): we should really handle this better. The particularly bad
// case is where an app becomes an extension or vice versa, and we end up with
// a zombie extension that won't go away.
if (extension && !IsCorrectSyncType(*extension, type))
return true;
// Handle uninstalls first.
if (extension_sync_data.uninstalled()) {
if (!extension_service_->UninstallExtensionHelper(
extension_service_, id, extensions::UNINSTALL_REASON_SYNC)) {
LOG(WARNING) << "Could not uninstall extension " << id
<< " for sync";
}
return true;
}
// Extension from sync was uninstalled by the user as external extensions.
// Honor user choice and skip installation/enabling.
if (extensions::ExtensionPrefs::Get(profile_)
->IsExternalExtensionUninstalled(id)) {
LOG(WARNING) << "Extension with id " << id
<< " from sync was uninstalled as external extension";
return true;
}
// Set user settings.
// If the extension has been disabled from sync, it may not have
// been installed yet, so we don't know if the disable reason was a
// permissions increase. That will be updated once CheckPermissionsIncrease
// is called for it.
// However if the extension is marked as a remote install in sync, we know
// what the disable reason is, so set it to that directly. Note that when
// CheckPermissionsIncrease runs, it might still add permissions increase
// as a disable reason for the extension.
if (extension_sync_data.enabled()) {
extension_service_->EnableExtension(id);
} else if (!IsPendingEnable(id)) {
if (extension_sync_data.remote_install()) {
extension_service_->DisableExtension(id,
Extension::DISABLE_REMOTE_INSTALL);
} else {
extension_service_->DisableExtension(
id, Extension::DISABLE_UNKNOWN_FROM_SYNC);
}
}
// We need to cache some version information here because setting the
// incognito flag invalidates the |extension| pointer (it reloads the
// extension).
bool extension_installed = (extension != NULL);
int version_compare_result = extension ?
extension->version()->CompareTo(extension_sync_data.version()) : 0;
// If the target extension has already been installed ephemerally, it can
// be promoted to a regular installed extension and downloading from the Web
// Store is not necessary.
if (extension && extensions::util::IsEphemeralApp(id, profile_))
extension_service_->PromoteEphemeralApp(extension, true);
// Update the incognito flag.
extensions::util::SetIsIncognitoEnabled(
id, profile_, extension_sync_data.incognito_enabled());
extension = NULL; // No longer safe to use.
if (extension_installed) {
// If the extension is already installed, check if it's outdated.
if (version_compare_result < 0) {
// Extension is outdated.
return false;
}
} else {
CHECK(type == syncer::EXTENSIONS || type == syncer::APPS);
extensions::PendingExtensionInfo::ShouldAllowInstallPredicate filter =
(type == syncer::APPS) ? extensions::sync_helper::IsSyncableApp :
extensions::sync_helper::IsSyncableExtension;
if (!extension_service_->pending_extension_manager()->AddFromSync(
id,
extension_sync_data.update_url(),
filter,
extension_sync_data.remote_install(),
extension_sync_data.installed_by_custodian())) {
LOG(WARNING) << "Could not add pending extension for " << id;
// This means that the extension is already pending installation, with a
// non-INTERNAL location. Add to pending_sync_data, even though it will
// never be removed (we'll never install a syncable version of the
// extension), so that GetAllSyncData() continues to send it.
}
// Track pending extensions so that we can return them in GetAllSyncData().
return false;
}
return true;
}
void ExtensionSyncService::SyncExtensionChangeIfNeeded(
const Extension& extension) {
if (extensions::util::ShouldSyncApp(&extension, profile_)) {
if (app_sync_bundle_.IsSyncing())
app_sync_bundle_.SyncChangeIfNeeded(extension);
else if (extension_service_->is_ready() && !flare_.is_null())
flare_.Run(syncer::APPS);
} else if (extensions::util::ShouldSyncExtension(&extension, profile_)) {
if (extension_sync_bundle_.IsSyncing())
extension_sync_bundle_.SyncChangeIfNeeded(extension);
else if (extension_service_->is_ready() && !flare_.is_null())
flare_.Run(syncer::EXTENSIONS);
}
}
|
{
"content_hash": "fb2da374fe45bcfeec598caf790d303c",
"timestamp": "",
"source": "github",
"line_count": 518,
"max_line_length": 80,
"avg_line_length": 38.3011583011583,
"alnum_prop": 0.6723790322580645,
"repo_name": "mxOBS/deb-pkg_trusty_chromium-browser",
"id": "cd8d3aa9d1e55d30e024374f34495edaab2c56f0",
"size": "21689",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "chrome/browser/extensions/extension_sync_service.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "8402"
},
{
"name": "Assembly",
"bytes": "230130"
},
{
"name": "Batchfile",
"bytes": "34966"
},
{
"name": "C",
"bytes": "12435900"
},
{
"name": "C++",
"bytes": "264378706"
},
{
"name": "CMake",
"bytes": "27829"
},
{
"name": "CSS",
"bytes": "795726"
},
{
"name": "Dart",
"bytes": "74976"
},
{
"name": "Emacs Lisp",
"bytes": "2360"
},
{
"name": "Go",
"bytes": "31783"
},
{
"name": "Groff",
"bytes": "5283"
},
{
"name": "HTML",
"bytes": "19491230"
},
{
"name": "Java",
"bytes": "7637875"
},
{
"name": "JavaScript",
"bytes": "12723911"
},
{
"name": "LLVM",
"bytes": "1169"
},
{
"name": "Logos",
"bytes": "6893"
},
{
"name": "Lua",
"bytes": "14392"
},
{
"name": "Makefile",
"bytes": "208315"
},
{
"name": "Objective-C",
"bytes": "1460032"
},
{
"name": "Objective-C++",
"bytes": "7760068"
},
{
"name": "PLpgSQL",
"bytes": "175360"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "427212"
},
{
"name": "Python",
"bytes": "11447382"
},
{
"name": "Ragel in Ruby Host",
"bytes": "104846"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "1208350"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "nesC",
"bytes": "18335"
}
],
"symlink_target": ""
}
|
namespace {
Bool WaitForMapNotify(Display *dpy, XEvent *event, XPointer window)
{
return event->type == MapNotify && event->xmap.window == reinterpret_cast<Window>(window);
}
static Key X11CodeToKey(Display *display, unsigned int scancode)
{
int temp;
KeySym *keySymbols;
keySymbols = XGetKeyboardMapping(display, scancode, 1, &temp);
unsigned int keySymbol = keySymbols[0];
XFree(keySymbols);
switch (keySymbol)
{
case XK_Shift_L: return KEY_LSHIFT;
case XK_Shift_R: return KEY_RSHIFT;
case XK_Alt_L: return KEY_LALT;
case XK_Alt_R: return KEY_RALT;
case XK_Control_L: return KEY_LCONTROL;
case XK_Control_R: return KEY_RCONTROL;
case XK_Super_L: return KEY_LSYSTEM;
case XK_Super_R: return KEY_RSYSTEM;
case XK_Menu: return KEY_MENU;
case XK_semicolon: return KEY_SEMICOLON;
case XK_slash: return KEY_SLASH;
case XK_equal: return KEY_EQUAL;
case XK_minus: return KEY_DASH;
case XK_bracketleft: return KEY_LBRACKET;
case XK_bracketright:return KEY_RBRACKET;
case XK_comma: return KEY_COMMA;
case XK_period: return KEY_PERIOD;
case XK_backslash: return KEY_BACKSLASH;
case XK_asciitilde: return KEY_TILDE;
case XK_Escape: return KEY_ESCAPE;
case XK_space: return KEY_SPACE;
case XK_Return: return KEY_RETURN;
case XK_BackSpace: return KEY_BACK;
case XK_Tab: return KEY_TAB;
case XK_Page_Up: return KEY_PAGEUP;
case XK_Page_Down: return KEY_PAGEDOWN;
case XK_End: return KEY_END;
case XK_Home: return KEY_HOME;
case XK_Insert: return KEY_INSERT;
case XK_Delete: return KEY_DELETE;
case XK_KP_Add: return KEY_ADD;
case XK_KP_Subtract: return KEY_SUBTRACT;
case XK_KP_Multiply: return KEY_MULTIPLY;
case XK_KP_Divide: return KEY_DIVIDE;
case XK_Pause: return KEY_PAUSE;
case XK_F1: return KEY_F1;
case XK_F2: return KEY_F2;
case XK_F3: return KEY_F3;
case XK_F4: return KEY_F4;
case XK_F5: return KEY_F5;
case XK_F6: return KEY_F6;
case XK_F7: return KEY_F7;
case XK_F8: return KEY_F8;
case XK_F9: return KEY_F9;
case XK_F10: return KEY_F10;
case XK_F11: return KEY_F11;
case XK_F12: return KEY_F12;
case XK_F13: return KEY_F13;
case XK_F14: return KEY_F14;
case XK_F15: return KEY_F15;
case XK_Left: return KEY_LEFT;
case XK_Right: return KEY_RIGHT;
case XK_Down: return KEY_DOWN;
case XK_Up: return KEY_UP;
case XK_KP_Insert: return KEY_NUMPAD0;
case XK_KP_End: return KEY_NUMPAD1;
case XK_KP_Down: return KEY_NUMPAD2;
case XK_KP_Page_Down:return KEY_NUMPAD3;
case XK_KP_Left: return KEY_NUMPAD4;
case XK_KP_5: return KEY_NUMPAD5;
case XK_KP_Right: return KEY_NUMPAD6;
case XK_KP_Home: return KEY_NUMPAD7;
case XK_KP_Up: return KEY_NUMPAD8;
case XK_KP_Page_Up: return KEY_NUMPAD9;
case XK_a: return KEY_A;
case XK_b: return KEY_B;
case XK_c: return KEY_C;
case XK_d: return KEY_D;
case XK_e: return KEY_E;
case XK_f: return KEY_F;
case XK_g: return KEY_G;
case XK_h: return KEY_H;
case XK_i: return KEY_I;
case XK_j: return KEY_J;
case XK_k: return KEY_K;
case XK_l: return KEY_L;
case XK_m: return KEY_M;
case XK_n: return KEY_N;
case XK_o: return KEY_O;
case XK_p: return KEY_P;
case XK_q: return KEY_Q;
case XK_r: return KEY_R;
case XK_s: return KEY_S;
case XK_t: return KEY_T;
case XK_u: return KEY_U;
case XK_v: return KEY_V;
case XK_w: return KEY_W;
case XK_x: return KEY_X;
case XK_y: return KEY_Y;
case XK_z: return KEY_Z;
case XK_1: return KEY_NUM1;
case XK_2: return KEY_NUM2;
case XK_3: return KEY_NUM3;
case XK_4: return KEY_NUM4;
case XK_5: return KEY_NUM5;
case XK_6: return KEY_NUM6;
case XK_7: return KEY_NUM7;
case XK_8: return KEY_NUM8;
case XK_9: return KEY_NUM9;
case XK_0: return KEY_NUM0;
}
return Key(0);
}
static void AddX11KeyStateToEvent(Event *event, unsigned int state)
{
event->Key.Shift = state & ShiftMask;
event->Key.Control = state & ControlMask;
event->Key.Alt = state & Mod1Mask;
event->Key.System = state & Mod4Mask;
}
}
X11Window::X11Window()
: WM_DELETE_WINDOW(None),
WM_PROTOCOLS(None),
TEST_EVENT(None),
mDisplay(nullptr),
mWindow(0),
mRequestedVisualId(-1),
mVisible(false)
{
}
X11Window::X11Window(int visualId)
: WM_DELETE_WINDOW(None),
WM_PROTOCOLS(None),
TEST_EVENT(None),
mDisplay(nullptr),
mWindow(0),
mRequestedVisualId(visualId),
mVisible(false)
{
}
X11Window::~X11Window()
{
destroy();
}
bool X11Window::initialize(const std::string &name, size_t width, size_t height)
{
destroy();
mDisplay = XOpenDisplay(NULL);
if (!mDisplay)
{
return false;
}
{
int screen = DefaultScreen(mDisplay);
Window root = RootWindow(mDisplay, screen);
Visual *visual;
if (mRequestedVisualId == -1)
{
visual = DefaultVisual(mDisplay, screen);
}
else
{
XVisualInfo visualTemplate;
visualTemplate.visualid = mRequestedVisualId;
int numVisuals = 0;
XVisualInfo *visuals = XGetVisualInfo(mDisplay, VisualIDMask, &visualTemplate, &numVisuals);
if (numVisuals <= 0)
{
return false;
}
ASSERT(numVisuals == 1);
visual = visuals[0].visual;
XFree(visuals);
}
int depth = DefaultDepth(mDisplay, screen);
Colormap colormap = XCreateColormap(mDisplay, root, visual, AllocNone);
XSetWindowAttributes attributes;
unsigned long attributeMask = CWBorderPixel | CWColormap | CWEventMask;
attributes.event_mask = StructureNotifyMask | PointerMotionMask | ButtonPressMask |
ButtonReleaseMask | FocusChangeMask | EnterWindowMask |
LeaveWindowMask | KeyPressMask | KeyReleaseMask;
attributes.border_pixel = 0;
attributes.colormap = colormap;
mWindow = XCreateWindow(mDisplay, root, 0, 0, width, height, 0, depth, InputOutput,
visual, attributeMask, &attributes);
XFreeColormap(mDisplay, colormap);
}
if (!mWindow)
{
destroy();
return false;
}
// Tell the window manager to notify us when the user wants to close the
// window so we can do it ourselves.
WM_DELETE_WINDOW = XInternAtom(mDisplay, "WM_DELETE_WINDOW", False);
WM_PROTOCOLS = XInternAtom(mDisplay, "WM_PROTOCOLS", False);
if (WM_DELETE_WINDOW == None || WM_PROTOCOLS == None)
{
destroy();
return false;
}
if(XSetWMProtocols(mDisplay, mWindow, &WM_DELETE_WINDOW, 1) == 0)
{
destroy();
return false;
}
// Create an atom to identify our test event
TEST_EVENT = XInternAtom(mDisplay, "ANGLE_TEST_EVENT", False);
if (TEST_EVENT == None)
{
destroy();
return false;
}
XFlush(mDisplay);
mX = 0;
mY = 0;
mWidth = width;
mHeight = height;
return true;
}
void X11Window::destroy()
{
if (mWindow)
{
XDestroyWindow(mDisplay, mWindow);
mWindow = 0;
}
if (mDisplay)
{
XCloseDisplay(mDisplay);
mDisplay = nullptr;
}
WM_DELETE_WINDOW = None;
WM_PROTOCOLS = None;
}
EGLNativeWindowType X11Window::getNativeWindow() const
{
return mWindow;
}
EGLNativeDisplayType X11Window::getNativeDisplay() const
{
return mDisplay;
}
void X11Window::messageLoop()
{
int eventCount = XPending(mDisplay);
while (eventCount--)
{
XEvent event;
XNextEvent(mDisplay, &event);
processEvent(event);
}
}
void X11Window::setMousePosition(int x, int y)
{
XWarpPointer(mDisplay, None, mWindow, 0, 0, 0, 0, x, y);
}
OSWindow *CreateOSWindow()
{
return new X11Window();
}
bool X11Window::setPosition(int x, int y)
{
XMoveWindow(mDisplay, mWindow, x, y);
XFlush(mDisplay);
return true;
}
bool X11Window::resize(int width, int height)
{
XResizeWindow(mDisplay, mWindow, width, height);
XFlush(mDisplay);
Timer* timer = CreateTimer();
timer->start();
// Wait until the window as actually been resized so that the code calling resize
// can assume the window has been resized.
const double kResizeWaitDelay = 0.2;
while (mHeight != height && mWidth != width && timer->getElapsedTime() < kResizeWaitDelay)
{
messageLoop();
angle::Sleep(10);
}
delete timer;
return true;
}
void X11Window::setVisible(bool isVisible)
{
if (mVisible == isVisible)
{
return;
}
if (isVisible)
{
XMapWindow(mDisplay, mWindow);
// Wait until we get an event saying this window is mapped so that the
// code calling setVisible can assume the window is visible.
// This is important when creating a framebuffer as the framebuffer content
// is undefined when the window is not visible.
XEvent dummyEvent;
XIfEvent(mDisplay, &dummyEvent, WaitForMapNotify, reinterpret_cast<XPointer>(mWindow));
}
else
{
XUnmapWindow(mDisplay, mWindow);
XFlush(mDisplay);
}
mVisible = isVisible;
}
void X11Window::signalTestEvent()
{
XEvent event;
event.type = ClientMessage;
event.xclient.message_type = TEST_EVENT;
// Format needs to be valid or a BadValue is generated
event.xclient.format = 32;
// Hijack StructureNotifyMask as we know we will be listening for it.
XSendEvent(mDisplay, mWindow, False, StructureNotifyMask, &event);
}
void X11Window::processEvent(const XEvent &xEvent)
{
// TODO(cwallez) text events
switch (xEvent.type)
{
case ButtonPress:
{
Event event;
MouseButton button = MOUSEBUTTON_UNKNOWN;
int wheelX = 0;
int wheelY = 0;
// The mouse wheel updates are sent via button events.
switch (xEvent.xbutton.button)
{
case Button4:
wheelY = 1;
break;
case Button5:
wheelY = -1;
break;
case 6:
wheelX = 1;
break;
case 7:
wheelX = -1;
break;
case Button1:
button = MOUSEBUTTON_LEFT;
break;
case Button2:
button = MOUSEBUTTON_MIDDLE;
break;
case Button3:
button = MOUSEBUTTON_RIGHT;
break;
case 8:
button = MOUSEBUTTON_BUTTON4;
break;
case 9:
button = MOUSEBUTTON_BUTTON5;
break;
default:
break;
}
if (wheelY != 0)
{
event.Type = Event::EVENT_MOUSE_WHEEL_MOVED;
event.MouseWheel.Delta = wheelY;
pushEvent(event);
}
if (button != MOUSEBUTTON_UNKNOWN)
{
event.Type = Event::EVENT_MOUSE_BUTTON_RELEASED;
event.MouseButton.Button = button;
event.MouseButton.X = xEvent.xbutton.x;
event.MouseButton.Y = xEvent.xbutton.y;
pushEvent(event);
}
}
break;
case ButtonRelease:
{
Event event;
MouseButton button = MOUSEBUTTON_UNKNOWN;
switch (xEvent.xbutton.button)
{
case Button1:
button = MOUSEBUTTON_LEFT;
break;
case Button2:
button = MOUSEBUTTON_MIDDLE;
break;
case Button3:
button = MOUSEBUTTON_RIGHT;
break;
case 8:
button = MOUSEBUTTON_BUTTON4;
break;
case 9:
button = MOUSEBUTTON_BUTTON5;
break;
default:
break;
}
if (button != MOUSEBUTTON_UNKNOWN)
{
event.Type = Event::EVENT_MOUSE_BUTTON_RELEASED;
event.MouseButton.Button = button;
event.MouseButton.X = xEvent.xbutton.x;
event.MouseButton.Y = xEvent.xbutton.y;
pushEvent(event);
}
}
break;
case KeyPress:
{
Event event;
event.Type = Event::EVENT_KEY_PRESSED;
event.Key.Code = X11CodeToKey(mDisplay, xEvent.xkey.keycode);
AddX11KeyStateToEvent(&event, xEvent.xkey.state);
pushEvent(event);
}
break;
case KeyRelease:
{
Event event;
event.Type = Event::EVENT_KEY_RELEASED;
event.Key.Code = X11CodeToKey(mDisplay, xEvent.xkey.keycode);
AddX11KeyStateToEvent(&event, xEvent.xkey.state);
pushEvent(event);
}
break;
case EnterNotify:
{
Event event;
event.Type = Event::EVENT_MOUSE_ENTERED;
pushEvent(event);
}
break;
case LeaveNotify:
{
Event event;
event.Type = Event::EVENT_MOUSE_LEFT;
pushEvent(event);
}
break;
case MotionNotify:
{
Event event;
event.Type = Event::EVENT_MOUSE_MOVED;
event.MouseMove.X = xEvent.xmotion.x;
event.MouseMove.Y = xEvent.xmotion.y;
pushEvent(event);
}
break;
case ConfigureNotify:
{
if (xEvent.xconfigure.width != mWidth || xEvent.xconfigure.height != mHeight)
{
Event event;
event.Type = Event::EVENT_RESIZED;
event.Size.Width = xEvent.xconfigure.width;
event.Size.Height = xEvent.xconfigure.height;
pushEvent(event);
}
if (xEvent.xconfigure.x != mX || xEvent.xconfigure.y != mY)
{
// Sometimes, the window manager reparents our window (for example
// when resizing) then the X and Y coordinates will be with respect to
// the new parent and not what the user wants to know. Use
// XTranslateCoordinates to get the coordinates on the screen.
int screen = DefaultScreen(mDisplay);
Window root = RootWindow(mDisplay, screen);
int x, y;
Window child;
XTranslateCoordinates(mDisplay, mWindow, root, 0, 0, &x, &y, &child);
if (x != mX || y != mY)
{
Event event;
event.Type = Event::EVENT_MOVED;
event.Move.X = x;
event.Move.Y = y;
pushEvent(event);
}
}
}
break;
case FocusIn:
if (xEvent.xfocus.mode == NotifyNormal || xEvent.xfocus.mode == NotifyWhileGrabbed)
{
Event event;
event.Type = Event::EVENT_GAINED_FOCUS;
pushEvent(event);
}
break;
case FocusOut:
if (xEvent.xfocus.mode == NotifyNormal || xEvent.xfocus.mode == NotifyWhileGrabbed)
{
Event event;
event.Type = Event::EVENT_LOST_FOCUS;
pushEvent(event);
}
break;
case DestroyNotify:
// We already received WM_DELETE_WINDOW
break;
case ClientMessage:
if (xEvent.xclient.message_type == WM_PROTOCOLS &&
static_cast<Atom>(xEvent.xclient.data.l[0]) == WM_DELETE_WINDOW)
{
Event event;
event.Type = Event::EVENT_CLOSED;
pushEvent(event);
}
else if (xEvent.xclient.message_type == TEST_EVENT)
{
Event event;
event.Type = Event::EVENT_TEST;
pushEvent(event);
}
break;
}
}
|
{
"content_hash": "f2337e7e588f7765a7bd74fb5f132ab1",
"timestamp": "",
"source": "github",
"line_count": 597,
"max_line_length": 104,
"avg_line_length": 28.921273031825795,
"alnum_prop": 0.532781188462875,
"repo_name": "mlfarrell/angle",
"id": "869e32c3c27db49b3b3094c5bad3e1309e08ed82",
"size": "17601",
"binary": false,
"copies": "3",
"ref": "refs/heads/ms-holographic-mlfarrell",
"path": "util/x11/X11Window.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "17281"
},
{
"name": "C",
"bytes": "991037"
},
{
"name": "C++",
"bytes": "9048598"
},
{
"name": "HLSL",
"bytes": "16376"
},
{
"name": "Lex",
"bytes": "26529"
},
{
"name": "Objective-C",
"bytes": "30946"
},
{
"name": "Objective-C++",
"bytes": "43316"
},
{
"name": "PostScript",
"bytes": "989"
},
{
"name": "Python",
"bytes": "272577"
},
{
"name": "Shell",
"bytes": "1426"
},
{
"name": "Yacc",
"bytes": "62180"
}
],
"symlink_target": ""
}
|
<?php
namespace PHPExiftool\Driver\Tag\CanonVRD;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class NeutralRawShadow extends AbstractTag
{
protected $Id = 129;
protected $Name = 'NeutralRawShadow';
protected $FullName = 'CanonVRD::Ver2';
protected $GroupName = 'CanonVRD';
protected $g0 = 'CanonVRD';
protected $g1 = 'CanonVRD';
protected $g2 = 'Image';
protected $Type = 'int16s';
protected $Writable = true;
protected $Description = 'Neutral Raw Shadow';
}
|
{
"content_hash": "5a40e608e61eee2036f12f9f0c7bf26a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 50,
"avg_line_length": 16.333333333333332,
"alnum_prop": 0.6751700680272109,
"repo_name": "bburnichon/PHPExiftool",
"id": "aa538d0766b59213a8525a09c5353d342cde3326",
"size": "812",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/PHPExiftool/Driver/Tag/CanonVRD/NeutralRawShadow.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22076400"
}
],
"symlink_target": ""
}
|
/* eslint-disable */
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var WebpackBuildNotifierPlugin = require('webpack-build-notifier');
var path = require('path');
var redashBackend = process.env.REDASH_BACKEND || 'http://localhost:5000';
var config = {
entry: {
app: './client/app/index.js'
},
output: {
// path: process.env.NODE_ENV === 'production' ? './dist' : './dev',
path: './client/dist',
filename: '[name].[chunkhash].js',
},
plugins: [
new WebpackBuildNotifierPlugin({title: 'Redash'}),
new webpack.DefinePlugin({
ON_TEST: process.env.NODE_ENV === 'test'
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, './node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
new HtmlWebpackPlugin({
// template: __dirname + '/app/' + 'index.html'
template: './client/app/index.html'
}),
new ExtractTextPlugin('styles.[chunkhash].css')
],
module: {
loaders: [
{test: /\.js$/, loader: 'ng-annotate!babel!eslint', exclude: /node_modules/},
{test: /\.html$/, loader: 'raw', exclude: [/node_modules/, /index\.html/]},
// {test: /\.css$/, loader: 'style!css', exclude: /node_modules/},
{test: /\.css$/, loader: ExtractTextPlugin.extract("css-loader")},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract(["css-loader", "sass-loader"])
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: 'img/[name].[hash:7].[ext]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: 'fonts/[name].[hash:7].[ext]'
}
}
]
},
devtool: 'cheap-eval-module-source-map',
devServer: {
inline: true,
historyApiFallback: true,
proxy: {
'/login': {
target: redashBackend + '/',
secure: false
},
'/invite': {
target: redashBackend + '/',
secure: false
},
'/setup': {
target: redashBackend + '/',
secure: false
},
'/images': {
target: redashBackend + '/',
secure: false
},
'/js': {
target: redashBackend + '/',
secure: false
},
'/styles': {
target: redashBackend + '/',
secure: false
},
'/status.json': {
target: redashBackend + '/',
secure: false
},
'/api/admin': {
target: redashBackend + '/',
secure: false
},
'/api': {
target: redashBackend,
secure: false
}
}
}
};
if (process.env.DEV_SERVER_HOST) {
config.devServer.host = process.env.DEV_SERVER_HOST;
}
if (process.env.NODE_ENV === 'production') {
config.output.path = __dirname + '/client/dist';
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.devtool = 'source-map';
}
module.exports = config;
|
{
"content_hash": "5fb3ceefa3b8fac558b66fe0f109dcf1",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 83,
"avg_line_length": 26.81021897810219,
"alnum_prop": 0.5439695072148107,
"repo_name": "M32Media/redash",
"id": "d82051c065a5508ff0c786754f1e9afedd089b47",
"size": "3673",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "webpack.config.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "234214"
},
{
"name": "HTML",
"bytes": "134842"
},
{
"name": "JavaScript",
"bytes": "292468"
},
{
"name": "Makefile",
"bytes": "825"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "692211"
},
{
"name": "Shell",
"bytes": "26044"
}
],
"symlink_target": ""
}
|
from __future__ import print_function
try:
# Python 2
import ConfigParser
except ImportError:
# Python 3
import configparser as ConfigParser
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'swift_build_support'))
# E402 means module level import not at top of file
from swift_build_support import diagnostics # noqa (E402)
from swift_build_support import shell # noqa (E402)
HOME = os.environ.get("HOME", "/")
def _get_default_source_root():
result = ""
# Are we in a Swift checkout? Start from this file and check its parent
# directories.
#
# $SWIFT_SOURCE_ROOT/swift/utils/SwiftBuildSupport.py
(swift_path, parent_dirname) = os.path.split(os.path.dirname(__file__))
if parent_dirname != "utils":
return result
if not os.path.exists(os.path.join(swift_path, 'CMakeLists.txt')):
return result
result = os.path.dirname(swift_path)
# Are we in an LLVM checkout? Start from the Swift checkout and check /its/
# parent directories.
#
# $SWIFT_SOURCE_ROOT/llvm/tools/swift/utils/SwiftBuildSupport.py
(llvm_path, parent_dirname) = os.path.split(result)
if parent_dirname != "tools":
return result
if not os.path.exists(os.path.join(llvm_path, 'CMakeLists.txt')):
return result
result = os.path.dirname(llvm_path)
return result
# Set SWIFT_SOURCE_ROOT in your environment to control where the sources
# are found.
SWIFT_SOURCE_ROOT = os.environ.get(
"SWIFT_SOURCE_ROOT", _get_default_source_root())
# Set SWIFT_BUILD_ROOT to a directory that will contain a subdirectory
# for each build configuration
SWIFT_BUILD_ROOT = os.environ.get(
"SWIFT_BUILD_ROOT", os.path.join(SWIFT_SOURCE_ROOT, "build"))
def _load_preset_files_impl(preset_file_names, substitutions={}):
config = ConfigParser.SafeConfigParser(substitutions, allow_no_value=True)
if config.read(preset_file_names) == []:
diagnostics.fatal(
"preset file not found (tried " + str(preset_file_names) + ")")
return config
_PRESET_PREFIX = "preset: "
def _get_preset_options_impl(config, substitutions, preset_name):
section_name = _PRESET_PREFIX + preset_name
if section_name not in config.sections():
return (None, None, None)
build_script_opts = []
build_script_impl_opts = []
missing_opts = []
dash_dash_seen = False
for o in config.options(section_name):
try:
a = config.get(section_name, o)
except ConfigParser.InterpolationMissingOptionError as e:
# e.reference contains the correctly formatted option
missing_opts.append(e.reference)
continue
if not a:
a = ""
if o in substitutions:
continue
opt = None
if o == "mixin-preset":
# Split on newlines and filter out empty lines.
mixins = filter(None, [m.strip() for m in a.splitlines()])
for mixin in mixins:
(base_build_script_opts,
base_build_script_impl_opts,
base_missing_opts) = \
_get_preset_options_impl(config, substitutions, mixin)
build_script_opts += base_build_script_opts
build_script_impl_opts += base_build_script_impl_opts
missing_opts += base_missing_opts
elif o == "dash-dash":
dash_dash_seen = True
elif a == "":
opt = "--" + o
else:
opt = "--" + o + "=" + a
if opt:
if not dash_dash_seen:
build_script_opts.append(opt)
else:
build_script_impl_opts.append(opt)
return (build_script_opts, build_script_impl_opts, missing_opts)
def get_preset_options(substitutions, preset_file_names, preset_name):
config = _load_preset_files_impl(preset_file_names, substitutions)
(build_script_opts, build_script_impl_opts, missing_opts) = \
_get_preset_options_impl(config, substitutions, preset_name)
if not build_script_opts and not build_script_impl_opts:
diagnostics.fatal("preset '" + preset_name + "' not found")
if missing_opts:
diagnostics.fatal("missing option(s) for preset '" + preset_name +
"': " + ", ".join(missing_opts))
# Migrate 'swift-sdks' parameter to 'stdlib-deployment-targets'
for opt in build_script_impl_opts:
if opt.startswith("--swift-sdks"):
sdks_to_configure = opt.split("=")[1].split(";")
tgts = []
# Expand SDKs in to their deployment targets
from swift_build_support.targets import StdlibDeploymentTarget
for sdk in sdks_to_configure:
if sdk == "OSX":
tgts += StdlibDeploymentTarget.OSX.targets
elif sdk == "IOS":
tgts += StdlibDeploymentTarget.iOS.targets
elif sdk == "IOS_SIMULATOR":
tgts += StdlibDeploymentTarget.iOSSimulator.targets
elif sdk == "TVOS":
tgts += StdlibDeploymentTarget.AppleTV.targets
elif sdk == "TVOS_SIMULATOR":
tgts += StdlibDeploymentTarget.AppleTVSimulator.targets
elif sdk == "WATCHOS":
tgts += StdlibDeploymentTarget.AppleWatch.targets
elif sdk == "WATCHOS_SIMULATOR":
tgts += StdlibDeploymentTarget.AppleWatchSimulator.targets
build_script_opts.append("--stdlib-deployment-targets=" +
" ".join([tgt.name for tgt in tgts]))
# Filter the swift-sdks parameter
build_script_impl_opts = [opt for opt in build_script_impl_opts
if not opt.startswith("--swift-sdks")]
return build_script_opts + ["--"] + build_script_impl_opts
def get_all_preset_names(preset_file_names):
config = _load_preset_files_impl(preset_file_names)
return [name[len(_PRESET_PREFIX):] for name in config.sections()
if name.startswith(_PRESET_PREFIX)]
|
{
"content_hash": "274e7f4a5b78ceb61b21cab25a44d3e9",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 79,
"avg_line_length": 36.22352941176471,
"alnum_prop": 0.6070152646963299,
"repo_name": "russbishop/swift",
"id": "bf5a117108389cd0fef2932fc2cc53d47a27e20c",
"size": "6583",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utils/SwiftBuildSupport.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2142"
},
{
"name": "C",
"bytes": "46250"
},
{
"name": "C++",
"bytes": "19989180"
},
{
"name": "CMake",
"bytes": "266500"
},
{
"name": "D",
"bytes": "1686"
},
{
"name": "DTrace",
"bytes": "1857"
},
{
"name": "Emacs Lisp",
"bytes": "39337"
},
{
"name": "LLVM",
"bytes": "59306"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "207722"
},
{
"name": "Objective-C++",
"bytes": "166358"
},
{
"name": "Perl",
"bytes": "2216"
},
{
"name": "Python",
"bytes": "536347"
},
{
"name": "Ruby",
"bytes": "2091"
},
{
"name": "Shell",
"bytes": "153110"
},
{
"name": "Swift",
"bytes": "14298185"
},
{
"name": "VimL",
"bytes": "13394"
}
],
"symlink_target": ""
}
|
This hook helps with installing manpages and shell completion files. It exposes 2 shell functions `installManPage` and `installShellCompletion` that can be used from your `postInstall` hook.
The `installManPage` function takes one or more paths to manpages to install. The manpages must have a section suffix, and may optionally be compressed (with `.gz` suffix). This function will place them into the correct directory.
The `installShellCompletion` function takes one or more paths to shell completion files. By default it will autodetect the shell type from the completion file extension, but you may also specify it by passing one of `--bash`, `--fish`, or `--zsh`. These flags apply to all paths listed after them (up until another shell flag is given). Each path may also have a custom installation name provided by providing a flag `--name NAME` before the path. If this flag is not provided, zsh completions will be renamed automatically such that `foobar.zsh` becomes `_foobar`. A root name may be provided for all paths using the flag `--cmd NAME`; this synthesizes the appropriate name depending on the shell (e.g. `--cmd foo` will synthesize the name `foo.bash` for bash and `_foo` for zsh). The path may also be a fifo or named fd (such as produced by `<(cmd)`), in which case the shell and name must be provided.
```nix
nativeBuildInputs = [ installShellFiles ];
postInstall = ''
installManPage doc/foobar.1 doc/barfoo.3
# explicit behavior
installShellCompletion --bash --name foobar.bash share/completions.bash
installShellCompletion --fish --name foobar.fish share/completions.fish
installShellCompletion --zsh --name _foobar share/completions.zsh
# implicit behavior
installShellCompletion share/completions/foobar.{bash,fish,zsh}
# using named fd
installShellCompletion --cmd foobar \
--bash <($out/bin/foobar --bash-completion) \
--fish <($out/bin/foobar --fish-completion) \
--zsh <($out/bin/foobar --zsh-completion)
'';
```
|
{
"content_hash": "2e1a5dba6d37ea2f7e0636ede205e97b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 904,
"avg_line_length": 86.04347826086956,
"alnum_prop": 0.7594744820616472,
"repo_name": "NixOS/nixpkgs",
"id": "d27527503fedda25fca41a67295e3f1a066b95e0",
"size": "2026",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/hooks/installShellFiles.section.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "2836"
},
{
"name": "C",
"bytes": "152018"
},
{
"name": "C#",
"bytes": "1462"
},
{
"name": "C++",
"bytes": "25094"
},
{
"name": "CMake",
"bytes": "1245"
},
{
"name": "CSS",
"bytes": "749"
},
{
"name": "Common Lisp",
"bytes": "63628"
},
{
"name": "D",
"bytes": "5281"
},
{
"name": "Emacs Lisp",
"bytes": "23735"
},
{
"name": "Erlang",
"bytes": "1437"
},
{
"name": "Go",
"bytes": "345"
},
{
"name": "HCL",
"bytes": "210"
},
{
"name": "Haskell",
"bytes": "24243"
},
{
"name": "Jasmin",
"bytes": "656"
},
{
"name": "Java",
"bytes": "1387"
},
{
"name": "JavaScript",
"bytes": "19128"
},
{
"name": "Lua",
"bytes": "548"
},
{
"name": "M4",
"bytes": "9030"
},
{
"name": "Makefile",
"bytes": "1878"
},
{
"name": "Meson",
"bytes": "134"
},
{
"name": "Nim",
"bytes": "5730"
},
{
"name": "Nix",
"bytes": "60599214"
},
{
"name": "PHP",
"bytes": "224"
},
{
"name": "Perl",
"bytes": "200361"
},
{
"name": "Prolog",
"bytes": "9914"
},
{
"name": "PureScript",
"bytes": "170"
},
{
"name": "Python",
"bytes": "494938"
},
{
"name": "QMake",
"bytes": "729"
},
{
"name": "R",
"bytes": "5075"
},
{
"name": "Reason",
"bytes": "182"
},
{
"name": "Roff",
"bytes": "2202"
},
{
"name": "Ruby",
"bytes": "62965"
},
{
"name": "Rust",
"bytes": "28196"
},
{
"name": "Scheme",
"bytes": "181"
},
{
"name": "Shell",
"bytes": "1150670"
},
{
"name": "SmPL",
"bytes": "2780"
},
{
"name": "Smarty",
"bytes": "178"
},
{
"name": "TypeScript",
"bytes": "7559"
},
{
"name": "VHDL",
"bytes": "2420"
},
{
"name": "Vim Script",
"bytes": "21353"
},
{
"name": "XSLT",
"bytes": "20355"
},
{
"name": "sed",
"bytes": "1073"
}
],
"symlink_target": ""
}
|
package org.apache.taverna.activities.externaltool.views;
import java.awt.Frame;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.swing.Action;
import org.apache.taverna.activities.externaltool.ExternalToolActivity;
import org.apache.taverna.activities.externaltool.ExternalToolActivityConfigurationBean;
import org.apache.taverna.activities.externaltool.actions.ExternalToolActivityConfigureAction;
import org.apache.taverna.activities.externaltool.servicedescriptions.ExternalToolActivityIcon;
import org.apache.taverna.workbench.activityicons.ActivityIconManager;
import org.apache.taverna.workbench.configuration.colour.ColourManager;
import org.apache.taverna.workbench.edits.EditManager;
import org.apache.taverna.workbench.file.FileManager;
import org.apache.taverna.workbench.ui.actions.activity.HTMLBasedActivityContextualView;
import org.apache.taverna.workflowmodel.processor.activity.Activity;
import org.apache.taverna.activities.externaltool.desc.ScriptInput;
import org.apache.taverna.activities.externaltool.desc.ScriptInputStatic;
import org.apache.taverna.activities.externaltool.desc.ScriptOutput;
import org.apache.taverna.activities.externaltool.desc.ToolDescription;
/**
* ExternalToolActivityContextualView displays the use case information in a HTML table. Currently,
* this is only the use case ID.
*
* @author Hajo Nils Krabbenhoeft
*/
public class ExternalToolActivityContextualView extends
HTMLBasedActivityContextualView<ExternalToolActivityConfigurationBean> {
private static final long serialVersionUID = 1L;
private final EditManager editManager;
private final FileManager fileManager;
private final ActivityIconManager activityIconManager;
public ExternalToolActivityContextualView(Activity<?> activity, EditManager editManager,
FileManager fileManager, ColourManager colourManager, ActivityIconManager activityIconManager) {
super(activity, colourManager);
this.editManager = editManager;
this.fileManager = fileManager;
this.activityIconManager = activityIconManager;
}
@Override
protected String getRawTableRowsHtml() {
String html = "";
ExternalToolActivityConfigurationBean bean = getConfigBean();
String repositoryUrl = bean.getRepositoryUrl();
if ((repositoryUrl == null) || repositoryUrl.isEmpty()) {
repositoryUrl = "<b>Not specified</b>";
}
html += "<tr><td>Repository URL</td><td>" + repositoryUrl + "</td></tr>";
String id = bean.getExternaltoolid();
if ((id == null) || id.isEmpty()) {
id = "<b>Not specified</b>";
}
html += "<tr><td>Id</td><td>" + id + "</td></tr>";
ToolDescription toolDescription = bean.getToolDescription();
String name = toolDescription.getTooldescid();
if ((name == null) || name.isEmpty()) {
name = "<b>Not specified</b>";
}
html += "<tr><td>Name</td><td>" + name + "</td></tr>";
Map<String, ScriptInput> stringReplacements = new TreeMap<String, ScriptInput>();
Map<String, ScriptInput> fileInputs = new TreeMap<String, ScriptInput>();
for (Entry<String, ScriptInput> entry : toolDescription.getInputs().entrySet()) {
String key = entry.getKey();
ScriptInput value = entry.getValue();
if (value.isFile()) {
fileInputs.put(key, value);
} else if (value.isTempFile()) {
// Nothing
} else {
stringReplacements.put(key, value);
}
}
if (!stringReplacements.isEmpty()) {
html += "<tr><td colspan=2 align=center><b>String replacements</b></td></tr>";
html += "<tr><td><b>Port name</b></td><td><b>Replaces</b></td></tr>";
for (String siName : stringReplacements.keySet()) {
html += "<tr><td>" + siName + "</td>";
ScriptInput si = stringReplacements.get(siName);
html += "<td>%%" + si.getTag() + "%%</td>";
html += "</tr>";
}
}
if (!fileInputs.isEmpty()) {
html += "<tr><td colspan=2 align=center><b>File inputs</b></td></tr>";
html += "<tr><td><b>Port name</b></td><td><b>To file</b></td></tr>";
for (String siName : fileInputs.keySet()) {
html += "<tr><td>" + siName + "</td>";
ScriptInput si = fileInputs.get(siName);
html += "<td>" + si.getTag() + "</td>";
html += "</tr>";
}
}
List<ScriptInputStatic> staticInputs = toolDescription.getStatic_inputs();
if (!staticInputs.isEmpty()) {
html += "<tr><td colspan=2 align=center><b>Static inputs</b></td></tr>";
html += "<tr><td><b>Type</b></td><td><b>To file</b></td></tr>";
for (ScriptInputStatic si : staticInputs) {
if (si.getUrl() != null) {
html += "<td><b>URL</b></td>";
} else {
html += "<td><b>Explicit content</b></td>";
}
if (si.isFile()) {
html += "<td>" + si.getTag() + "</td>";
}
html += "</tr>";
}
}
Map<String, ScriptOutput> outputs = toolDescription.getOutputs();
if (!outputs.isEmpty()) {
html += "<tr><td colspan=2 align=center><b>File outputs</b></td></tr>";
html += "<tr><td><b>Port name</b></td><td><b>From file</b></td></tr>";
for (String soName : outputs.keySet()) {
html += "<tr><td>" + soName + "</td>";
ScriptOutput so = outputs.get(soName);
html += "<td>" + so.getPath() + "</td>";
html += "</tr>";
}
}
return html;
}
@Override
public String getViewTitle() {
return "Tool service";
}
@Override
public Action getConfigureAction(final Frame owner) {
return new ExternalToolActivityConfigureAction((ExternalToolActivity) getActivity(), owner,
editManager, fileManager, activityIconManager);
}
public String getBackgroundColour() {
return ExternalToolActivityIcon.getColourString();
}
@Override
public int getPreferredPosition() {
return 100;
}
}
|
{
"content_hash": "c7f4a6ccdda6bbe01cc6a46ea83aa2fa",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 99,
"avg_line_length": 34.882716049382715,
"alnum_prop": 0.6920898955937003,
"repo_name": "apache/incubator-taverna-workbench-common-activities",
"id": "75aa2c206e1ff48940fa85d4da30ab361b906f9f",
"size": "6453",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "taverna-external-tool-activity-ui/src/main/java/org/apache/taverna/activities/externaltool/views/ExternalToolActivityContextualView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "666499"
}
],
"symlink_target": ""
}
|
<p>
Test for <i><a href="rdar://problem/7194735">rdar://problem/7194735</a> Crashes at RenderText::RenderText()</i>.
</p>
<p>
This test should not crash or cause an assertion failure.
</p>
<embed type="application/x-webkit-test-netscape" ondestroy="destroyed()">
<div id="target"></div>
<script>
function destroyed()
{
var target = document.getElementById("target");
target.innerHTML = "text";
}
if (window.testRunner)
testRunner.dumpAsText();
document.body.offsetTop;
location.href = "data:text/html,Test for rdar://problem/7194735 PASSED.";
</script>
|
{
"content_hash": "9730f9d9f948b9acf7f78efc95ebbc9d",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 116,
"avg_line_length": 29.095238095238095,
"alnum_prop": 0.6563011456628478,
"repo_name": "lordmos/blink",
"id": "3e600c904ff982b4c756591af000f8e677a5e08d",
"size": "611",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "LayoutTests/plugins/attach-during-destroy.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "6433"
},
{
"name": "C",
"bytes": "753714"
},
{
"name": "C++",
"bytes": "40028043"
},
{
"name": "CSS",
"bytes": "539440"
},
{
"name": "F#",
"bytes": "8755"
},
{
"name": "Java",
"bytes": "18650"
},
{
"name": "JavaScript",
"bytes": "25700387"
},
{
"name": "Objective-C",
"bytes": "426711"
},
{
"name": "PHP",
"bytes": "141755"
},
{
"name": "Perl",
"bytes": "901523"
},
{
"name": "Python",
"bytes": "3748305"
},
{
"name": "Ruby",
"bytes": "141818"
},
{
"name": "Shell",
"bytes": "9635"
},
{
"name": "XSLT",
"bytes": "49328"
}
],
"symlink_target": ""
}
|
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('teams', '0001_initial'),
('substitutes', '0001_initial'),
('invites', '0004_auto_20180105_0213'),
]
operations = [
migrations.AlterUniqueTogether(
name='sessioneventinvite',
unique_together=set([('sub', 'team')]),
),
]
|
{
"content_hash": "fe6c234ae29e11092d2f73a96c768971",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 51,
"avg_line_length": 22.894736842105264,
"alnum_prop": 0.5839080459770115,
"repo_name": "eSmelser/SnookR",
"id": "9eefdb3de321effc9d9e668b40c9019f33d82a58",
"size": "508",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "SnookR/invites/migrations/0005_auto_20180106_0333.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "42731"
},
{
"name": "HTML",
"bytes": "83044"
},
{
"name": "JavaScript",
"bytes": "7810344"
},
{
"name": "PHP",
"bytes": "6093"
},
{
"name": "Python",
"bytes": "115524"
}
],
"symlink_target": ""
}
|
PILE_OF_POO = u"\U0001F4A9"
def pytest_addoption(parser):
group = parser.getgroup('Poo', 'Poo')
group._addoption('--poo',
action="store_true", dest="poo", default=False,
help="Show crappy tests.")
def pytest_report_teststatus(report, config):
if (not config.option.poo) or ('poo' not in report.keywords) or (report.when != 'call'):
return
if (config.option.verbose == -1 and report.passed) or config.option.verbose >= 0:
return (report.outcome, PILE_OF_POO, '%s (%s)' % (report.outcome.upper(), PILE_OF_POO))
def pytest_configure(config):
config.addinivalue_line(
'markers',
'poo: Mark the test as crappy. When using --poo, pile of poo '
'will be shown with the test outcome.')
|
{
"content_hash": "b4246ecd619e1c167574492c5da0ed4a",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 95,
"avg_line_length": 37.38095238095238,
"alnum_prop": 0.6127388535031847,
"repo_name": "pelme/pytest-poo",
"id": "9fa6f1edaad3118be712c8f157f9fbf2557848cb",
"size": "786",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pytest_poo.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "4162"
}
],
"symlink_target": ""
}
|
require 'spec_helper'
describe 'graphite-cluster::default' do
cached(:chef_run) do
ChefSpec::ServerRunner.converge(described_recipe)
end
it 'converges successfully' do
chef_run # This should not raise an error
end
end
|
{
"content_hash": "97d5372a05844b99cfa6b20558cd7021",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 53,
"avg_line_length": 21.454545454545453,
"alnum_prop": 0.7330508474576272,
"repo_name": "obazoud/chef-graphite-cluster",
"id": "0d40d5d1e703bc5e720c6e740a8f2d0151d8edc0",
"size": "348",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/unit/recipes/default_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "8906"
}
],
"symlink_target": ""
}
|
<div>
<div class="view-header clearfix">
<h1>Templates <a class="cta" ui-sref="templates-new"><span class="icon icon-plus"></span> New Template</a></h1>
</div>
<table class="table list-table">
<thead>
<tr>
<th>Name</th>
<th>Updated At</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="ng-list" ng-repeat="templateItem in template.templateList | orderBy:['group', 'path']">
<td>
<a ui-sref="templates-edit({ id: templateItem._id })">{{templateItem.name}}</a>
</td>
<td>
<span class="updated-at">{{templateItem.updatedAt | date:'medium'}}</span>
</td>
<td class="text-right">
<a ui-sref="templates-edit({ id: templateItem._id })">Edit</a>
</td>
<td class="text-right">
<a ng-click="template.delete( templateItem )">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
|
{
"content_hash": "6989fd88303fa4bf0551367641f8c02b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 115,
"avg_line_length": 29.96875,
"alnum_prop": 0.5203336809176226,
"repo_name": "mgmeyers/fluid-cms",
"id": "0555b482f502875641de18d32d12433be1ef9b02",
"size": "959",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "system/modules/template/ui/fl.template.list.ng.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19212"
},
{
"name": "HTML",
"bytes": "22401"
},
{
"name": "JavaScript",
"bytes": "80047"
}
],
"symlink_target": ""
}
|
require 'doorkeeper/models/mongoid/revocable'
require 'doorkeeper/models/mongoid/scopes'
module Doorkeeper
class AccessGrant
include Mongoid::Document
include Mongoid::Timestamps
include Doorkeeper::Models::Mongoid::Revocable
include Doorkeeper::Models::Mongoid::Scopes
self.store_in :oauth_access_grants
field :resource_owner_id, :type => Integer
field :application_id, :type => Hash
field :token, :type => String
field :expires_in, :type => Integer
field :redirect_uri, :type => String
field :revoked_at, :type => DateTime
index :token, :unique => true
end
end
|
{
"content_hash": "e7dcfde5b8b4213615e5b23bdd1fc1f2",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 50,
"avg_line_length": 28.136363636363637,
"alnum_prop": 0.7043618739903069,
"repo_name": "davesherratt/doorkeeper",
"id": "1e23c973545cc695d9a9bcb9bda02f3b7fa188e2",
"size": "619",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "lib/doorkeeper/models/mongoid2/access_grant.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "505"
},
{
"name": "Ruby",
"bytes": "216240"
},
{
"name": "Shell",
"bytes": "409"
}
],
"symlink_target": ""
}
|
import os
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
ENVIRONMENT_DIR = os.path.abspath(os.path.join(PROJECT_DIR, "..", "..", ".."))
HTDOCS_DIR = os.path.join(ENVIRONMENT_DIR, 'htdocs',)
LOG_DIR = os.path.join(ENVIRONMENT_DIR, 'var', 'log')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ("Example", "example@example.com"),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'psafe.db',
# The following settings are not used with sqlite3:
'USER': 'psafe',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
LANGUAGE_COOKIE_NAME = "language"
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(HTDOCS_DIR, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(HTDOCS_DIR, 'static')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'p@%8m9m6!-zg=9muwc=t&*inii7a_(p!k>33ozv5=h9@!hca'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'psafe.score.context_processors.site',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'psafe.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'psafe.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'django_extensions',
'mptt',
'safe',
'psafe.score',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': os.path.join(LOG_DIR, "psafe.log"),
'formatter': 'verbose'
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'psafe': {
'handlers': ['file', 'console'],
'level': 'DEBUG',
'propagate': True,
},
}
}
try:
from local_settings import *
except ImportError:
pass
|
{
"content_hash": "732621c29b46f791c428a8f95c4065b0",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 108,
"avg_line_length": 32.02358490566038,
"alnum_prop": 0.6640153188982177,
"repo_name": "JoeJasinski/password-safe",
"id": "db3e3d3bfe2ecb44bffbd14beaceb18bd1ac7aef",
"size": "6827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "psafe/settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3984"
},
{
"name": "HTML",
"bytes": "50515"
},
{
"name": "JavaScript",
"bytes": "731350"
},
{
"name": "Makefile",
"bytes": "4583"
},
{
"name": "Nginx",
"bytes": "1549"
},
{
"name": "Python",
"bytes": "33895"
},
{
"name": "Shell",
"bytes": "196"
}
],
"symlink_target": ""
}
|
namespace PlanetWars.Areas.HelpPage.ModelDescriptions
{
public class SimpleTypeModelDescription : ModelDescription
{
}
}
|
{
"content_hash": "c2ddfcd452cda64233738cecfb9ad2e4",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 62,
"avg_line_length": 22,
"alnum_prop": 0.7727272727272727,
"repo_name": "eonarheim/planet-wars-competition",
"id": "8099aa36cf99da380cb8d9031afc18055cf1e9c4",
"size": "132",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "PlanetWars/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "104"
},
{
"name": "C#",
"bytes": "205590"
},
{
"name": "CSS",
"bytes": "5548"
},
{
"name": "JavaScript",
"bytes": "1030618"
},
{
"name": "Scilab",
"bytes": "596"
},
{
"name": "TypeScript",
"bytes": "15530"
}
],
"symlink_target": ""
}
|
package com.all.client.view.toolbar.social;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.HierarchyBoundsAdapter;
import java.awt.event.HierarchyEvent;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;
import com.all.appControl.control.ViewEngine;
import com.all.client.view.dialog.DialogFactory;
import com.all.observ.Observable;
import com.all.observ.ObserveObject;
import com.all.observ.Observer;
import com.all.observ.ObserverCollection;
import com.all.shared.model.ContactInfo;
public final class FriendsScrollPane extends JScrollPane {
private static final long serialVersionUID = 1L;
private static final int PROFILE_CONTAC_PANEL_WIDTH = 98;
private static final int PROFILE_CONTAC_PANEL_HEIGHT = 125;
private static final Dimension SCROLL_PANE_DEFAULT_SIZE = new Dimension(566, 248);
private static final Dimension SCROLL_PANE_MINIMUM_SIZE = new Dimension(310, 168);
private static final String FRIENDS_PANEL_NAME = "friendsPanelBackround";
private static final String CURRENT_COMPONENT_NAME = "HighlightAddFriendsCellProfile";
private boolean loaded;
protected DialogFactory dialogFactory;
public final Observable<ObserveObject> onLoadFriendsPanelEvent = new Observable<ObserveObject>();
private JPanel friendsContainer;
private PaginationFriendsPanelManager paginationFriendsPanelManager;
private Component prevComponent;
private final ViewEngine viewEngine;
public FriendsScrollPane(DialogFactory dialogFactory, ViewEngine viewEngine) {
this.dialogFactory = dialogFactory;
this.viewEngine = viewEngine;
initialize();
}
public FriendsScrollPane(DialogFactory dialogFactory, PaginationFriendsPanelManager paginationFriendsPanelManager,
ViewEngine viewEngine) {
this.dialogFactory = dialogFactory;
this.paginationFriendsPanelManager = paginationFriendsPanelManager;
this.viewEngine = viewEngine;
initialize();
}
private void initialize() {
this.setSize(SCROLL_PANE_DEFAULT_SIZE);
this.setPreferredSize(SCROLL_PANE_DEFAULT_SIZE);
this.setMinimumSize(SCROLL_PANE_MINIMUM_SIZE);
this.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.setViewportView(getFriendsContainer());
this.getViewport().setName(FRIENDS_PANEL_NAME);
this.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
@Override
public void ancestorResized(HierarchyEvent e) {
updateSizeFriendsContainerPanel();
}
});
}
public JPanel getFriendsContainer() {
if (friendsContainer == null) {
friendsContainer = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public Dimension getSize() {
Dimension size = updateSize();
return size;
}
};
friendsContainer.setLayout(new FlowLayout(FlowLayout.LEFT));
}
return friendsContainer;
}
public void fillFirstPage() {
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() {
fillFriendsContainer(paginationFriendsPanelManager.getFirstFriendsPage());
updateSizeFriendsContainerPanel();
return null;
}
@Override
protected void done() {
loaded = true;
onLoadFriendsPanelEvent.fire(ObserveObject.EMPTY);
}
}.execute();
}
public void updateSizeFriendsContainerPanel() {
friendsContainer.setPreferredSize(new Dimension(getWidth(), friendsContainer.getSize().height));
friendsContainer.setSize(new Dimension(getWidth(), friendsContainer.getSize().height));
}
private Dimension updateSize() {
int cupoPorFila = ((getWidth() - this.getVerticalScrollBar().getWidth()) / PROFILE_CONTAC_PANEL_WIDTH);
int filas = 0;
if (cupoPorFila > 0) {
filas = friendsContainer.getComponentCount() / cupoPorFila;
filas = (friendsContainer.getComponentCount() % cupoPorFila > 0) ? filas + 1 : filas;
}
Dimension size = super.getSize();
size.height = filas * PROFILE_CONTAC_PANEL_HEIGHT;
return size;
}
public void fillFriendsContainer(List<ContactInfo> friends) {
friendsContainer.removeAll();
for (final ContactInfo contactInfo : friends) {
final ProfileContactPanel profileContactPanel = new ProfileContactPanel(contactInfo, viewEngine, dialogFactory);
profileContactPanel.onSelectProfile().add(new Observer<ObserveObject>() {
@Override
public void observe(ObserveObject eventArgs) {
final Component currentComponent = profileContactPanel;
if (prevComponent != null) {
prevComponent.setName("");
((ProfileContactPanel) prevComponent).setHightLightPhotoPanel(false);
}
currentComponent.setName(CURRENT_COMPONENT_NAME);
((ProfileContactPanel) currentComponent).setHightLightPhotoPanel(true);
prevComponent = currentComponent;
}
});
friendsContainer.add(profileContactPanel);
}
friendsContainer.repaint();
friendsContainer.revalidate();
}
public ObserverCollection<ObserveObject> onLoadFriendsPanel() {
return onLoadFriendsPanelEvent;
}
public boolean isLoaded() {
return loaded;
}
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
public void setPaginationFriendsPanelManager(PaginationFriendsPanelManager paginationFriendsPanelManager) {
this.paginationFriendsPanelManager = paginationFriendsPanelManager;
}
public PaginationFriendsPanelManager getPaginationManager() {
return paginationFriendsPanelManager;
}
public void updateContact(ContactInfo contact) {
for (Component component : friendsContainer.getComponents()) {
if (component instanceof ProfileContactPanel) {
ProfileContactPanel contactPanel = (ProfileContactPanel) component;
if (contact.equals(contactPanel.getContact())) {
contactPanel.refresh(contact);
}
}
}
}
}
|
{
"content_hash": "0c67abc3cbac3ace1e96e58d10ec4d6e",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 115,
"avg_line_length": 32.376344086021504,
"alnum_prop": 0.7482563932248423,
"repo_name": "josdem/client",
"id": "ea8f6e2d34574ec62204b2b950310e72ae0cd649",
"size": "17584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client-view/src/main/java/com/all/client/view/toolbar/social/FriendsScrollPane.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "13516347"
},
{
"name": "JavaScript",
"bytes": "2520155"
},
{
"name": "Shell",
"bytes": "34062"
}
],
"symlink_target": ""
}
|
package com.eclecticlogic.orc.impl;
import net.sf.cglib.proxy.CallbackFilter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static java.util.stream.Collectors.*;
/**
* Filter to decide whether to intercept the method or not.
* Created by kabram
*/
public class SchemaFilter<T> implements CallbackFilter {
private final Class<T> clz;
private final Set<Method> allowedMethods;
private static final Set<String> disallowed = new HashSet(Arrays.asList("getClass", "notify", "wait", "notifyAll"));
public SchemaFilter(Class<T> clz) {
this.clz = clz;
allowedMethods = Arrays.stream(clz.getMethods()) //
// No parameters
.filter(it -> it.getParameterCount() == 0) //
// Not void return type
.filter(it -> !it.getReturnType().isAssignableFrom(Void.class)) //
.filter(it -> !disallowed.contains(it.getName())) //
// Filter out groovy specific meta-methods. Primitives and arrays don't have a package name!
.filter(it -> it.getReturnType().isPrimitive() || //
it.getReturnType().isArray() || //
!it.getReturnType().getPackage().getName().contains("groovy"))
.collect(toSet());
}
@Override
public int accept(Method method) {
return allowedMethods.contains(method) ? 0 : 1;
}
}
|
{
"content_hash": "0553ff9edfc9c765b1a39da6bcdf8987",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 120,
"avg_line_length": 33.56818181818182,
"alnum_prop": 0.6167907921462423,
"repo_name": "eclecticlogic/eclectic-orc",
"id": "06f2364cf8ec624c5f57ee63d8ca11c92968275d",
"size": "2082",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/eclecticlogic/orc/impl/SchemaFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "32099"
},
{
"name": "Java",
"bytes": "78081"
}
],
"symlink_target": ""
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const PFS_1 = require("./PFS");
function BFSanityChecks(graph, start) {
if (graph == null || start == null) {
throw new Error('Graph as well as start node have to be valid objects.');
}
if (graph.nrDirEdges() === 0 && graph.nrUndEdges() === 0) {
throw new Error('Cowardly refusing to traverse a graph without edges.');
}
if (!graph.hasNodeID(start.getID())) {
throw new Error('Cannot start from an outside node.');
}
}
function BellmanFordArray(graph, start) {
BFSanityChecks(graph, start);
let distances = [], nodes = graph.getNodes(), edge, node_keys = Object.keys(nodes), node, id_idx_map = {}, bf_edge_entry, new_weight, neg_cycle = false;
for (let n_idx = 0; n_idx < node_keys.length; ++n_idx) {
node = nodes[node_keys[n_idx]];
distances[n_idx] = (node === start) ? 0 : Number.POSITIVE_INFINITY;
id_idx_map[node.getID()] = n_idx;
}
let graph_edges = graph.getDirEdgesArray().concat(graph.getUndEdgesArray());
let bf_edges = [];
for (let e_idx = 0; e_idx < graph_edges.length; ++e_idx) {
edge = graph_edges[e_idx];
let bf_edge_entry = bf_edges.push([
id_idx_map[edge.getNodes().a.getID()],
id_idx_map[edge.getNodes().b.getID()],
isFinite(edge.getWeight()) ? edge.getWeight() : PFS_1.DEFAULT_WEIGHT,
edge.isDirected()
]);
}
for (let i = 0; i < node_keys.length - 1; ++i) {
for (let e_idx = 0; e_idx < bf_edges.length; ++e_idx) {
edge = bf_edges[e_idx];
updateDist(edge[0], edge[1], edge[2]);
!edge[3] && updateDist(edge[1], edge[0], edge[2]);
}
}
for (let e_idx = 0; e_idx < bf_edges.length; ++e_idx) {
edge = bf_edges[e_idx];
if (betterDist(edge[0], edge[1], edge[2]) || (!edge[3] && betterDist(edge[1], edge[0], edge[2]))) {
neg_cycle = true;
break;
}
}
function updateDist(u, v, weight) {
new_weight = distances[u] + weight;
if (distances[v] > new_weight) {
distances[v] = new_weight;
}
}
function betterDist(u, v, weight) {
return (distances[v] > distances[u] + weight);
}
return { distances, neg_cycle };
}
exports.BellmanFordArray = BellmanFordArray;
function BellmanFordDict(graph, start) {
BFSanityChecks(graph, start);
let distances = {}, edges, edge, a, b, weight, new_weight, nodes_size, neg_cycle = false;
distances = {};
edges = graph.getDirEdgesArray().concat(graph.getUndEdgesArray());
nodes_size = graph.nrNodes();
for (let node in graph.getNodes()) {
distances[node] = Number.POSITIVE_INFINITY;
}
distances[start.getID()] = 0;
for (let i = 0; i < nodes_size - 1; ++i) {
for (let e_idx = 0; e_idx < edges.length; ++e_idx) {
edge = edges[e_idx];
a = edge.getNodes().a.getID();
b = edge.getNodes().b.getID();
weight = isFinite(edge.getWeight()) ? edge.getWeight() : PFS_1.DEFAULT_WEIGHT;
updateDist(a, b, weight);
!edge.isDirected() && updateDist(b, a, weight);
}
}
for (let edgeID in edges) {
edge = edges[edgeID];
a = edge.getNodes().a.getID();
b = edge.getNodes().b.getID();
weight = isFinite(edge.getWeight()) ? edge.getWeight() : PFS_1.DEFAULT_WEIGHT;
if (betterDist(a, b, weight) || (!edge.isDirected() && betterDist(b, a, weight))) {
neg_cycle = true;
}
}
function updateDist(u, v, weight) {
new_weight = distances[u] + weight;
if (distances[v] > new_weight) {
distances[v] = new_weight;
}
}
function betterDist(u, v, weight) {
return (distances[v] > distances[u] + weight);
}
return { distances, neg_cycle };
}
exports.BellmanFordDict = BellmanFordDict;
|
{
"content_hash": "ca03c951b5c1700efd68270e1701c673",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 156,
"avg_line_length": 39.8,
"alnum_prop": 0.5608040201005026,
"repo_name": "cassinius/GraphiniusJS",
"id": "e54674774a46d4c683ebfe5b289f6d38f6fca4e1",
"size": "3980",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/search/BellmanFord.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "180851"
},
{
"name": "Python",
"bytes": "30425"
},
{
"name": "Shell",
"bytes": "661"
},
{
"name": "TypeScript",
"bytes": "645899"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
Hieracium alaricum Arv.-Touv. & Gaut.
### Remarks
null
|
{
"content_hash": "e6fe66902c6ea6decbbc70363993f28e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 37,
"avg_line_length": 11.23076923076923,
"alnum_prop": 0.6917808219178082,
"repo_name": "mdoering/backbone",
"id": "8d8af50d26ba7b8d5548025600d228ee67be62f9",
"size": "237",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium glaucinum/Hieracium glaucinum alaricum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_60) on Wed Mar 04 14:40:47 SAST 2015 -->
<title>U-Index</title>
<meta name="date" content="2015-03-04">
<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="U-Index";
}
//-->
</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>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-18.html">Prev Letter</a></li>
<li><a href="index-20.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-19.html" target="_top">Frames</a></li>
<li><a href="index-19.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">L</a> <a href="index-11.html">M</a> <a href="index-12.html">N</a> <a href="index-13.html">O</a> <a href="index-14.html">P</a> <a href="index-15.html">Q</a> <a href="index-16.html">R</a> <a href="index-17.html">S</a> <a href="index-18.html">T</a> <a href="index-19.html">U</a> <a href="index-20.html">V</a> <a href="index-21.html">W</a> <a name="_U_">
<!-- -->
</a>
<h2 class="title">U</h2>
<dl>
<dt><span class="strong"><a href="../be/ppareit/swiftp/R.string.html#unknown">unknown</a></span> - Static variable in class be.ppareit.swiftp.<a href="../be/ppareit/swiftp/R.string.html" title="class in be.ppareit.swiftp">R.string</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../meesters/wifip2p/deps/Router.P2P_ReceiverActions.html#UPDATE_SERVICES_VIEW">UPDATE_SERVICES_VIEW</a></span> - Static variable in class meesters.wifip2p.deps.<a href="../meesters/wifip2p/deps/Router.P2P_ReceiverActions.html" title="class in meesters.wifip2p.deps">Router.P2P_ReceiverActions</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../be/ppareit/swiftp/FsService.html#updateDeviceInfo(WifiP2pDevice)">updateDeviceInfo(WifiP2pDevice)</a></span> - Method in class be.ppareit.swiftp.<a href="../be/ppareit/swiftp/FsService.html" title="class in be.ppareit.swiftp">FsService</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../be/ppareit/swiftp/FsService.html#updateLocalP2PAddress(java.net.InetAddress)">updateLocalP2PAddress(InetAddress)</a></span> - Method in class be.ppareit.swiftp.<a href="../be/ppareit/swiftp/FsService.html" title="class in be.ppareit.swiftp">FsService</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../be/ppareit/swiftp/R.string.html#username_default">username_default</a></span> - Static variable in class be.ppareit.swiftp.<a href="../be/ppareit/swiftp/R.string.html" title="class in be.ppareit.swiftp">R.string</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../be/ppareit/swiftp/R.string.html#username_label">username_label</a></span> - Static variable in class be.ppareit.swiftp.<a href="../be/ppareit/swiftp/R.string.html" title="class in be.ppareit.swiftp">R.string</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../be/ppareit/swiftp/R.string.html#username_validation_error">username_validation_error</a></span> - Static variable in class be.ppareit.swiftp.<a href="../be/ppareit/swiftp/R.string.html" title="class in be.ppareit.swiftp">R.string</a></dt>
<dd> </dd>
<dt><a href="../be/ppareit/swiftp/Util.html" title="class in be.ppareit.swiftp"><span class="strong">Util</span></a> - Class in <a href="../be/ppareit/swiftp/package-summary.html">be.ppareit.swiftp</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../be/ppareit/swiftp/Util.html#Util()">Util()</a></span> - Constructor for class be.ppareit.swiftp.<a href="../be/ppareit/swiftp/Util.html" title="class in be.ppareit.swiftp">Util</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">L</a> <a href="index-11.html">M</a> <a href="index-12.html">N</a> <a href="index-13.html">O</a> <a href="index-14.html">P</a> <a href="index-15.html">Q</a> <a href="index-16.html">R</a> <a href="index-17.html">S</a> <a href="index-18.html">T</a> <a href="index-19.html">U</a> <a href="index-20.html">V</a> <a href="index-21.html">W</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-18.html">Prev Letter</a></li>
<li><a href="index-20.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-19.html" target="_top">Frames</a></li>
<li><a href="index-19.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"content_hash": "a4a55f3892904b51c6c5504e181010b2",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 770,
"avg_line_length": 54.5514705882353,
"alnum_prop": 0.650896347216606,
"repo_name": "dschoonwinkel/ConnectNet",
"id": "cce46eb666fb7aaf9e567b70cc03247cd3dc989b",
"size": "7419",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "swiftp/doc/index-files/index-19.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "HTML",
"bytes": "1613028"
},
{
"name": "Java",
"bytes": "708780"
},
{
"name": "Shell",
"bytes": "178"
}
],
"symlink_target": ""
}
|
using System;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Codecs.Lucene3x
{
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
/// <summary>
/// Codec, only for testing, that can write and read the
/// pre-flex index format.
///
/// @lucene.experimental
/// </summary>
#pragma warning disable 612, 618
internal class PreFlexRWPostingsFormat : Lucene3xPostingsFormat
{
public PreFlexRWPostingsFormat()
{
// NOTE: we impersonate the PreFlex codec so that it can
// read the segments we write!
}
public override FieldsConsumer FieldsConsumer(SegmentWriteState state)
{
return new PreFlexRWFieldsWriter(state);
}
public override FieldsProducer FieldsProducer(SegmentReadState state)
{
// Whenever IW opens readers, eg for merging, we have to
// keep terms order in UTF16:
return new Lucene3xFieldsAnonymousInnerClassHelper(this, state.Directory, state.FieldInfos, state.SegmentInfo, state.Context, state.TermsIndexDivisor);
}
private class Lucene3xFieldsAnonymousInnerClassHelper : Lucene3xFields
{
private readonly PreFlexRWPostingsFormat OuterInstance;
public Lucene3xFieldsAnonymousInnerClassHelper(PreFlexRWPostingsFormat outerInstance, Store.Directory directory, Index.FieldInfos fieldInfos, Index.SegmentInfo segmentInfo, Store.IOContext context, int termsIndexDivisor)
: base(directory, fieldInfos, segmentInfo, context, termsIndexDivisor)
{
this.OuterInstance = outerInstance;
}
protected override bool SortTermsByUnicode
{
get
{
// We carefully peek into stack track above us: if
// we are part of a "merge", we must sort by UTF16:
bool unicodeSortOrder = true;
// LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
// to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
if (Util.StackTraceHelper.DoesStackTraceContainMethod("Merge"))
{
unicodeSortOrder = false;
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("NOTE: PreFlexRW codec: forcing legacy UTF16 term sort order");
}
}
return unicodeSortOrder;
}
}
}
}
#pragma warning restore 612, 618
}
|
{
"content_hash": "1b8f970368f81cc5b4c3f30d44e5d73e",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 232,
"avg_line_length": 38.5,
"alnum_prop": 0.6120984278879016,
"repo_name": "laimis/lucenenet",
"id": "9829a8186ba0a7e3e8c8591c4fe26a84fee4ac25",
"size": "3847",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWPostingsFormat.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4805"
},
{
"name": "C#",
"bytes": "41089688"
},
{
"name": "Gnuplot",
"bytes": "2444"
},
{
"name": "HTML",
"bytes": "79746"
},
{
"name": "PowerShell",
"bytes": "73932"
},
{
"name": "XSLT",
"bytes": "21773"
}
],
"symlink_target": ""
}
|
import { Options, RetryFunction } from 'async-retry';
import retry = require("async-retry");
const o: Options = {
retries: 1,
factor: 2,
minTimeout: 3,
maxTimeout: 4,
randomize: true,
onRetry: (e: Error) => 42
};
const hello: Promise<string> = retry(
bail => 'hello',
{ retries: 3 }
);
const answer: Promise<number> = retry(
bail => Promise.resolve(42),
{ retries: 3 }
);
|
{
"content_hash": "ac6122f4d33ecfc27f95a5a5a7fb1e19",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 53,
"avg_line_length": 18.80952380952381,
"alnum_prop": 0.6278481012658228,
"repo_name": "AgentME/DefinitelyTyped",
"id": "20dfc62c4b32321c6ba11fb4b3184042a64a7733",
"size": "395",
"binary": false,
"copies": "27",
"ref": "refs/heads/master",
"path": "types/async-retry/async-retry-tests.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "10652407"
},
{
"name": "Ruby",
"bytes": "40"
},
{
"name": "Shell",
"bytes": "60"
},
{
"name": "TypeScript",
"bytes": "11370242"
}
],
"symlink_target": ""
}
|
</script><b>Coronal slice 144 labels</b> (<a href="../contours/1003/labels.php" onClick="return popup(../contours/1003/labels.php)">full label list</a>):<br /><table align="left" valign="top" width="512px"><tr><td align="left" valign="top"><font size="2">Left Lateral Ventricle<br />
Left Caudate<br />
Left Putamen<br />
Left Pallidum<br />
Left PrG precentral gyrus<br />
Left PrG precentral gyrus<br />
Left PoG postcentral gyrus<br />
Left CO central operculum<br />
Left PP planum polare<br />
Left MTG middle temporal gyrus<br />
Left ITG inferior temporal gyrus<br />
Left FuG fusiform gyrus<br />
Left Ent entorhinal area<br />
Left SFG superior frontal gyrus<br />
Left MFG middle frontal gyrus<br />
Left AIns anterior insula<br />
Left PIns posterior insula<br />
Left MCgG middle cingulate gyrus<br />
Left SMC supplementary motor cortex<br />
Left STG superior temporal gyrus<br />
</font></td><td align="left" valign="top"><font size="2">Right Lateral Ventricle<br />
Right Caudate<br />
Right Putamen<br />
Right Pallidum<br />
Right PIns posterior insula<br />
Right PrG precentral gyrus<br />
Right MFG middle frontal gyrus<br />
Right OpIFG opercular part of the inferior frontal gyrus<br />
Right STG superior temporal gyrus<br />
Right MTG middle temporal gyrus<br />
Right ITG inferior temporal gyrus<br />
Right Ent entorhinal area<br />
Right SFG superior frontal gyrus<br />
Right AIns anterior insula<br />
Right CO central operculum<br />
Right MCgG middle cingulate gyrus<br />
Right SMC supplementary motor cortex<br />
Right PP planum polare<br />
</font></td></tr><table>
|
{
"content_hash": "d71bab69160bc49957efdc2f438240d9",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 283,
"avg_line_length": 42.48717948717949,
"alnum_prop": 0.7109233554616777,
"repo_name": "binarybottle/braincolor-roygbiv",
"id": "f820803eb4ecacac213c58651320acf840a86967",
"size": "1657",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contours/1003/slice144_labellist.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "869"
},
{
"name": "HTML",
"bytes": "24787136"
},
{
"name": "JavaScript",
"bytes": "58228"
},
{
"name": "PHP",
"bytes": "36568"
},
{
"name": "Python",
"bytes": "22073"
}
],
"symlink_target": ""
}
|
package c99.parser.pp;
import c99.Ident;
public class PPSymbol extends Ident
{
public PPSymCode ppCode;
public Object ppDecl;
public PPSymbol ( byte[] bytes, int hash )
{
super( bytes, hash );
}
}
|
{
"content_hash": "cc7c12d42d4ab3adb12e61a842468653",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 42,
"avg_line_length": 14.428571428571429,
"alnum_prop": 0.7227722772277227,
"repo_name": "tmikov/c99",
"id": "a5bf6a3cbfde9ed1b8aad287fc64ea37ca1eb434",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/cpp/src/c99/parser/pp/PPSymbol.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Bison",
"bytes": "75869"
},
{
"name": "C",
"bytes": "10161"
},
{
"name": "Diff",
"bytes": "7761"
},
{
"name": "Java",
"bytes": "377424"
},
{
"name": "Shell",
"bytes": "1251"
}
],
"symlink_target": ""
}
|
using Moq;
using NUnit.Framework;
[TestFixture]
public class ShouldStartSinceFileChangedTests
{
[Test]
public void NotProcessedByFody()
{
var processor = new Processor
{
Logger = new Mock<BuildLogger>().Object,
AssemblyFilePath = typeof (string).Assembly.CodeBase.Replace("file:///", "")
};
Assert.IsTrue(processor.ShouldStartSinceFileChanged());
}
[Test]
public void ProcessedByFody()
{
var processor = new Processor
{
Logger = new Mock<BuildLogger>().Object,
AssemblyFilePath = GetType().Assembly.CodeBase.Replace("file:///", "")
};
Assert.IsFalse(processor.ShouldStartSinceFileChanged());
}
}
public interface ProcessedByFody
{
}
|
{
"content_hash": "8d2de61e8f78af05cb8db4fb08a8f52d",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 92,
"avg_line_length": 24.727272727272727,
"alnum_prop": 0.5906862745098039,
"repo_name": "huoxudong125/Fody",
"id": "97ce72c9a307933f32a23329e2f390f69012c2de",
"size": "816",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "Fody.Tests/ShouldStartSinceFileChangedTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "123239"
},
{
"name": "PostScript",
"bytes": "3581"
}
],
"symlink_target": ""
}
|
model in "hearts.bug"
data in "hearts-data.R"
compile, nchains(2)
parameters in "hearts-inits.R"
initialize
update 1000
monitor theta
monitor beta
monitor p
update 10000
coda *
|
{
"content_hash": "3d55588248c6680a5495624f32f97c28",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 30,
"avg_line_length": 14.916666666666666,
"alnum_prop": 0.770949720670391,
"repo_name": "NLMichaud/nimble",
"id": "63c2cd8aaf8af90bdaf02cf05b2d2fc65539c054",
"size": "179",
"binary": false,
"copies": "3",
"ref": "refs/heads/devel",
"path": "packages/nimble/inst/classic-bugs/vol2/hearts/test1.cmd",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "14212"
},
{
"name": "C",
"bytes": "44479"
},
{
"name": "C++",
"bytes": "3166959"
},
{
"name": "CMake",
"bytes": "6810"
},
{
"name": "Groff",
"bytes": "1099194"
},
{
"name": "M4",
"bytes": "4510"
},
{
"name": "Makefile",
"bytes": "1574"
},
{
"name": "R",
"bytes": "2539688"
},
{
"name": "Shell",
"bytes": "11904"
}
],
"symlink_target": ""
}
|
FROM balenalib/asus-tinker-board-s-ubuntu:focal-run
ENV NODE_VERSION 14.16.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "a64860a02e4b692d262d453952cae99a3c9842d3fc90336b54ca03e990c780b8 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu focal \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.16.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
{
"content_hash": "b2a4ed97a536fceee1fb6800cf635de1",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 691,
"avg_line_length": 64.53333333333333,
"alnum_prop": 0.7048898071625345,
"repo_name": "nghiant2710/base-images",
"id": "07f2869944e99253e1c9c790bf621d446cdd821b",
"size": "2925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/asus-tinker-board-s/ubuntu/focal/14.16.0/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
}
|
sudo rm /var/log/tarantool/bench.log
sudo rm /var/log/tarantool/bench2.log
sudo rm -rf /var/lib/tarantool/bench/
sudo rm -rf /var/lib/tarantool/bench2/
sudo tarantoolctl restart bench
sudo tarantoolctl restart bench2
#sleep 3
./load.pl --batch_len=5000 --limit=10000
rm load
./post.sh '{"method":"build","id":0,"params":[] }'
rm load
#./post.sh '{"method":"show","id":0,"params":[] }'
#rm load
./post.sh '{"method":"lookup","id":0,"params":["Jonathan"] }'
|
{
"content_hash": "2306ed146ada34d7e66369baf17b7a9d",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 61,
"avg_line_length": 32.57142857142857,
"alnum_prop": 0.6820175438596491,
"repo_name": "Sulverus/tarantool-wiki-lookup",
"id": "744f0dd13a22e6e1066936b280f2d1060527622f",
"size": "456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "run/run.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "7526"
},
{
"name": "Lua",
"bytes": "5768"
},
{
"name": "Nginx",
"bytes": "980"
},
{
"name": "Perl",
"bytes": "7968"
},
{
"name": "Python",
"bytes": "3642"
},
{
"name": "Shell",
"bytes": "523"
}
],
"symlink_target": ""
}
|
//
// ChartViewControllerTest.m
// Demo#227
//
// Created by technicise on 11/21/14.
// Copyright (c) 2014 technicise. All rights reserved.
//
#import "ChartViewControllerTest.h"
#import "ChartCell.h"
@interface ChartViewControllerTest ()
@end
@implementation ChartViewControllerTest
{
NSArray *ImageArray;
NSArray *Name;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Name =[[NSArray alloc]initWithObjects:@"Demographics",@"Providers",@"Care Network",@"Insurence Card", nil];
ImageArray=[NSArray arrayWithObjects:@"Image1.png",@"Image2.png",@"Image3.png",@"Image4.png",@"Image5.png", nil];
_tiltle.text=@"PATIENT INFORMATION";
_gender.text=@"Male";
_image.image=[UIImage imageNamed:@"29 Settings"];
_date.text=@"01/06/1990";
_catagory.text=@"Medical/Labs/BMI";
_name.text=@"John Appuser";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section
{
return [Name count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableCell";
ChartCell *cell = (ChartCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
//cell = [[HiWorldCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChartCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
// NSLog(@"nib");
}
CALayer *btnLayer1 = [cell.CellButton layer];
[btnLayer1 setMasksToBounds:YES];
[btnLayer1 setCornerRadius:10.0f];
cell.CellLabel.text=[Name objectAtIndex:indexPath.row];
cell.celImage.image= [UIImage imageNamed:[ImageArray objectAtIndex:indexPath.row]];
cell.CellButton.hidden=YES;
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
/*UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell.textLabel setHighlightedTextColor: [UIColor whiteColor]];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
}
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text=[Name objectAtIndex:indexPath.row];
*/
/* cell.name.text=[Name objectAtIndex:indexPath.row];
cell.gender.text=@"Male";
cell.date.text=@"01/06/1990";
cell.catagory.text=@"Medical/Labs/BMI";
cell.image.image=[UIImage imageNamed:@"29 Settings"];
*/ //cell.textLabel.text=@"Male";
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 90)];
separatorView.layer.borderColor = [UIColor colorWithRed:0.329 green:0.839 blue:0.416 alpha:1].CGColor;
separatorView.layer.borderColor = [[UIColor lightGrayColor]CGColor];
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
|
{
"content_hash": "d1b0f368e1dd8cde216f124511eb26ed",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 118,
"avg_line_length": 31.557377049180328,
"alnum_prop": 0.7031168831168831,
"repo_name": "sayan801/GoogleMapIosSamples",
"id": "4c682daeb7e650e7b3e3df8f0f2abfa7a87c5b38",
"size": "3850",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Demo#227/Demo#227/ChartViewControllerTest.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "24851"
}
],
"symlink_target": ""
}
|
package org.camunda.bpm.quarkus.engine.test.helper;
import io.quarkus.arc.Arc;
import io.quarkus.test.QuarkusUnitTest;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.impl.test.TestHelper;
import org.camunda.bpm.engine.test.Deployment;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.function.Supplier;
public class ProcessEngineAwareExtension extends QuarkusUnitTest {
protected String deploymentId;
protected Supplier<JavaArchive> archiveProducer;
protected String withConfigurationResource;
@Override
public void beforeEach(ExtensionContext context) throws Exception {
super.beforeEach(context);
Method testMethod = context.getTestMethod().orElse(null);
if (testMethod != null) {
Deployment annotation = testMethod.getAnnotation(Deployment.class);
if (annotation != null) {
Object processEngine = getBean("processEngine");
String testMethodName = testMethod.getName();
Class<?> testHelperClass = loadClass(TestHelper.class);
Method annotationDeploymentSetUp = testHelperClass.getMethod("annotationDeploymentSetUp",
loadClass(ProcessEngine.class), String[].class, Class.class, String.class);
String[] resources = annotation.resources();
Class<?> testClass = context.getTestClass().orElse(null);
deploymentId = (String) annotationDeploymentSetUp.invoke(testHelperClass, processEngine, resources, testClass,
testMethodName);
}
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
if (deploymentId != null) {
Object repositoryService = getBean("repositoryService");
Method deleteDeployment = repositoryService.getClass().getMethod("deleteDeployment", String.class, Boolean.TYPE);
deleteDeployment.invoke(repositoryService, deploymentId, true);
deploymentId = null;
}
super.afterEach(context);
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
if (withConfigurationResource == null) {
super.withConfigurationResource("application.properties");
} else {
super.withConfigurationResource(withConfigurationResource);
}
JavaArchive javaArchive = archiveProducer.get();
javaArchive.addClass(ProcessEngineAwareExtension.class);
Method[] testMethods = context.getTestClass().get().getMethods();
Arrays.stream(testMethods).forEach(method -> {
if (method.getAnnotation(Test.class) != null) {
Deployment annotation = method.getAnnotation(Deployment.class);
if (annotation != null) {
String[] resources = annotation.resources();
if (resources.length == 0) {
Class<?> testClass = context.getTestClass().orElse(null);
String testMethodName = method.getName();
String resource = TestHelper.getBpmnProcessDefinitionResource(testClass, testMethodName);
javaArchive.addAsResource(resource);
} else {
Arrays.stream(resources).forEach(javaArchive::addAsResource);
}
}
}
});
super.setArchiveProducer(() -> javaArchive);
super.beforeAll(context);
}
@Override
public QuarkusUnitTest setArchiveProducer(Supplier<JavaArchive> archiveProducer) {
this.archiveProducer = archiveProducer;
return this;
}
@Override
public ProcessEngineAwareExtension withConfigurationResource(String resourceName) {
this.withConfigurationResource = resourceName;
return this;
}
protected Class<?> loadClass(Class<?> clazz) throws ClassNotFoundException {
return Thread.currentThread().getContextClassLoader().loadClass(clazz.getName());
}
protected Object getBean(String beanName) throws Exception {
Class<?> arcClass = loadClass(Arc.class);
Method containerMethod = arcClass.getMethod("container");
Object container = containerMethod.invoke(null);
Method instanceMethod = container.getClass().getMethod("instance", String.class);
Object instanceHandle = instanceMethod.invoke(container, beanName);
Method getMethod = instanceHandle.getClass().getMethod("get");
getMethod.setAccessible(true);
Object bean = getMethod.invoke(instanceHandle);
return bean;
}
}
|
{
"content_hash": "f808935522fa7a3511bfcf394772e584",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 119,
"avg_line_length": 35.408,
"alnum_prop": 0.7245820153637597,
"repo_name": "langfr/camunda-bpm-platform",
"id": "c5fa1eb44943a836a8a1d02b54b90825d2e9d475",
"size": "5233",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "quarkus-extension/engine/deployment/src/test/java/org/camunda/bpm/quarkus/engine/test/helper/ProcessEngineAwareExtension.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8608"
},
{
"name": "CSS",
"bytes": "5486"
},
{
"name": "Fluent",
"bytes": "3111"
},
{
"name": "FreeMarker",
"bytes": "1439225"
},
{
"name": "Groovy",
"bytes": "1904"
},
{
"name": "HTML",
"bytes": "961289"
},
{
"name": "Java",
"bytes": "44041849"
},
{
"name": "JavaScript",
"bytes": "3063544"
},
{
"name": "Less",
"bytes": "154956"
},
{
"name": "Python",
"bytes": "192"
},
{
"name": "Ruby",
"bytes": "60"
},
{
"name": "SQLPL",
"bytes": "44180"
},
{
"name": "Shell",
"bytes": "11634"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
<id>com.vfw1401.project1</id>
<name>Project1</name>
<version>1.0</version>
<publisher>Jeshko</publisher>
<url>http://</url>
<description>not specified</description>
<copyright>2014 by Jeshko</copyright>
<icon>appicon.png</icon>
<fullscreen>false</fullscreen>
<navbar-hidden>false</navbar-hidden>
<analytics>true</analytics>
<guid>327443a7-d7ea-47ca-941e-8e95b654d50e</guid>
<property name="ti.ui.defaultunit" type="string">dp</property>
<ios>
<plist>
<dict>
<key>UISupportedInterfaceOrientations~iphone</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIRequiresPersistentWiFi</key>
<false/>
<key>UIPrerenderedIcon</key>
<false/>
<key>UIStatusBarHidden</key>
<false/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleDefault</string>
</dict>
</plist>
</ios>
<android xmlns:android="http://schemas.android.com/apk/res/android"/>
<mobileweb>
<precache/>
<splash>
<enabled>true</enabled>
<inline-css-images>true</inline-css-images>
</splash>
<theme>default</theme>
</mobileweb>
<modules/>
<deployment-targets>
<target device="android">true</target>
<target device="blackberry">false</target>
<target device="ipad">true</target>
<target device="iphone">true</target>
<target device="mobileweb">false</target>
<target device="tizen">false</target>
</deployment-targets>
<sdk-version>3.2.1.GA</sdk-version>
</ti:app>
|
{
"content_hash": "02f3f394961cfbc6cbc125d4a02b3e25",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 77,
"avg_line_length": 37.7,
"alnum_prop": 0.5773651635720601,
"repo_name": "r90230/Hereshko_John_Project1",
"id": "fab9a6a10cb47f7d866b6fa1fb9a79abb9e9df2a",
"size": "2262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tiapp.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "1483"
},
{
"name": "Perl",
"bytes": "561"
},
{
"name": "Shell",
"bytes": "170"
}
],
"symlink_target": ""
}
|
#ifndef XNFIRMWAREINFO_H
#define XNFIRMWAREINFO_H
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <XnStreamParams.h>
#include <XnArray.h>
//---------------------------------------------------------------------------
// Types
//---------------------------------------------------------------------------
class XnFirmwareInfo
{
public:
XnFWVer nFWVer;
XnUInt16 nHostMagic;
XnUInt16 nFWMagic;
XnUInt16 nProtocolHeaderSize;
XnUInt16 nProtocolMaxPacketSize;
XnParamCurrentMode nCurrMode;
XnBool bAudioSupported;
XnBool bGetPresetsSupported;
XnBool bDeviceInfoSupported;
XnBool bImageAdjustmentsSupported;
XnUInt16 nOpcodeGetVersion;
XnUInt16 nOpcodeKeepAlive;
XnUInt16 nOpcodeGetParam;
XnUInt16 nOpcodeSetParam;
XnUInt16 nOpcodeGetFixedParams;
XnUInt16 nOpcodeGetMode;
XnUInt16 nOpcodeSetMode;
XnUInt16 nOpcodeAlgorithmParams;
XnUInt16 nOpcodeReset;
XnUInt16 nOpcodeSetCmosBlanking;
XnUInt16 nOpcodeGetCmosBlanking;
XnUInt16 nOpcodeGetCmosPresets;
XnUInt16 nOpcodeGetSerialNumber;
XnUInt16 nOpcodeGetFastConvergenceTEC;
XnUInt16 nOpcodeGetCMOSReg;
XnUInt16 nOpcodeSetCMOSReg;
XnUInt16 nOpcodeWriteI2C;
XnUInt16 nOpcodeReadI2C;
XnUInt16 nOpcodeReadAHB;
XnUInt16 nOpcodeWriteAHB;
XnUInt16 nOpcodeGetPlatformString;
XnUInt16 nOpcodeGetUsbCore;
XnUInt16 nOpcodeSetLedState;
XnUInt16 nOpcodeEnableEmitter;
XnUInt16 nOpcodeGetLog;
XnUInt16 nOpcodeTakeSnapshot;
XnUInt16 nOpcodeInitFileUpload;
XnUInt16 nOpcodeWriteFileUpload;
XnUInt16 nOpcodeFinishFileUpload;
XnUInt16 nOpcodeDownloadFile;
XnUInt16 nOpcodeDeleteFile;
XnUInt16 nOpcodeGetFlashMap;
XnUInt16 nOpcodeGetFileList;
XnUInt16 nOpcodeSetFileAttribute;
XnUInt16 nOpcodeExecuteFile;
XnUInt16 nOpcodeReadFlash;
XnUInt16 nOpcodeBIST;
XnUInt16 nOpcodeSetGMCParams;
XnUInt16 nOpcodeGetCPUStats;
XnUInt16 nOpcodeCalibrateTec;
XnUInt16 nOpcodeGetTecData;
XnUInt16 nOpcodeCalibrateEmitter;
XnUInt16 nOpcodeGetEmitterData;
XnUInt16 nOpcodeCalibrateProjectorFault;
XnUInt16 nLogStringType;
XnUInt16 nLogOverflowType;
XnBool bMirrorSupported;
XnUInt16 nUSBDelayReceive;
XnUInt16 nUSBDelayExecutePreSend;
XnUInt16 nUSBDelayExecutePostSend;
XnUInt16 nUSBDelaySoftReset;
XnUInt16 nUSBDelaySetParamFlicker;
XnUInt16 nUSBDelaySetParamStream0Mode;
XnUInt16 nUSBDelaySetParamStream1Mode;
XnUInt16 nUSBDelaySetParamStream2Mode;
XnUInt8 nISOAlternativeInterface;
XnUInt8 nBulkAlternativeInterface;
XnUInt8 nISOLowDepthAlternativeInterface;
XnBool bGetImageCmosTypeSupported;
XnBool bImageSupported;
XnBool bIncreasedFpsCropSupported;
XnBool bHasFilesystemLock;
xnl::Array<XnCmosPreset> depthModes;
xnl::Array<XnCmosPreset> _imageBulkModes;
xnl::Array<XnCmosPreset> _imageIsoModes;
xnl::Array<XnCmosPreset> imageModes;
xnl::Array<XnCmosPreset> irModes;
};
#endif // XNFIRMWAREINFO_H
|
{
"content_hash": "6f7baa3565dfa2f9784c166104dd24ec",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 77,
"avg_line_length": 27.62264150943396,
"alnum_prop": 0.7609289617486339,
"repo_name": "Windowsfreak/NIStreamer",
"id": "51de9fe86e50297109dfbb8e16555ae355ac15eb",
"size": "4507",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Android/OpenNI2-develop/Source/Drivers/PS1080/Sensor/XnFirmwareInfo.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2502"
},
{
"name": "C",
"bytes": "3558822"
},
{
"name": "C++",
"bytes": "5998696"
},
{
"name": "CSS",
"bytes": "12808"
},
{
"name": "HTML",
"bytes": "1177610"
},
{
"name": "Java",
"bytes": "9478987"
},
{
"name": "JavaScript",
"bytes": "827"
},
{
"name": "Makefile",
"bytes": "5071291"
},
{
"name": "Python",
"bytes": "98955"
},
{
"name": "Shell",
"bytes": "302765"
}
],
"symlink_target": ""
}
|
require 'traffic_source_parser/tools'
require 'traffic_source_parser/result/campaign'
module TrafficSourceParser
module CampaignParser
extend self
extend Tools
def match_cookie_value?(value)
value =~ /utm_source|utm_medium|utm_term|utm_content|utm_campaign/
end
def parse(campaign_query)
@campaign_query = campaign_query
TrafficSourceParser::Result::Campaign.new(campaign_hash)
end
def campaign_hash
translate_keys(parsed_campaign_params, campaign_params_mapper)
end
def campaign_params
get_params(@campaign_query)
end
def parsed_campaign_params
parse_params(campaign_params)
end
def campaign_params_mapper
@campaign_params ||= load_config('campaign_params.yml')
end
end
end
|
{
"content_hash": "8dfb8ab9733c85da93c617e013af992d",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 72,
"avg_line_length": 22.428571428571427,
"alnum_prop": 0.7006369426751592,
"repo_name": "ResultadosDigitais/traffic_source_parser",
"id": "d8d0ffa37b88646bcd9a7c2689c49bf253074468",
"size": "785",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/traffic_source_parser/campaign_parser.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "36415"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
}
|
Traderun
====
In the spirit of the ludum dare october contest I will try to finish a small fork of
my gowt game project in the hopes of releasing a fun yet demanding space trader strategy
game.
Let's see how that goes.
|
{
"content_hash": "495142b335b2add67686bbc60f75c144",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 88,
"avg_line_length": 27.875,
"alnum_prop": 0.7623318385650224,
"repo_name": "zorfmorf/loveprojects",
"id": "a8e7db6208efaa2a91ba22744196e2f67734c318",
"size": "223",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "traderun/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "11780"
},
{
"name": "Lua",
"bytes": "605895"
},
{
"name": "Shell",
"bytes": "4715"
}
],
"symlink_target": ""
}
|
/***********************************************************************
created: 5/4/2005
author: Tomas Lindquist Olsen (based on code by Paul D Turner)
purpose: Implementation of MenuBase widget base class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#include "CEGUI/widgets/MenuBase.h"
#include "CEGUI/widgets/PopupMenu.h"
#include "CEGUI/widgets/MenuItem.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Constants
*************************************************************************/
// event strings
const String MenuBase::EventNamespace("MenuBase");
const String MenuBase::EventPopupOpened("PopupOpened");
const String MenuBase::EventPopupClosed("PopupClosed");
/*************************************************************************
Constructor for MenuBase base class.
*************************************************************************/
MenuBase::MenuBase(const String& type, const String& name)
: ItemListBase(type, name),
d_itemSpacing(0.0f),
d_popupItem(0),
d_allowMultiplePopups(false),
d_autoCloseNestedPopups(false)
{
// add properties for MenuBase class
addMenuBaseProperties();
}
/*************************************************************************
Destructor for MenuBase base class.
*************************************************************************/
MenuBase::~MenuBase(void)
{
}
/*************************************************************************
Change the currently open MenuItem PopupMenu
*************************************************************************/
void MenuBase::changePopupMenuItem(MenuItem* item)
{
if (!d_allowMultiplePopups && d_popupItem == item)
return;
if (!d_allowMultiplePopups && d_popupItem != 0)
{
WindowEventArgs we(d_popupItem->getPopupMenu());
d_popupItem->closePopupMenu(false);
d_popupItem = 0;
onPopupClosed(we);
}
if (item)
{
d_popupItem = item;
d_popupItem->openPopupMenu(false);
WindowEventArgs we(d_popupItem->getPopupMenu());
onPopupOpened(we);
}
}
/*************************************************************************
handler invoked internally when the a MenuItem attached to this
MenuBase opens its popup.
*************************************************************************/
void MenuBase::onPopupOpened(WindowEventArgs& e)
{
fireEvent(EventPopupOpened, e, EventNamespace);
}
/*************************************************************************
handler invoked internally when the a MenuItem attached to this
MenuBase closes its popup.
*************************************************************************/
void MenuBase::onPopupClosed(WindowEventArgs& e)
{
fireEvent(EventPopupClosed, e, EventNamespace);
}
/************************************************************************
Add properties for this widget
*************************************************************************/
void MenuBase::addMenuBaseProperties(void)
{
const String propertyOrigin = "CEGUI/MenuBase";
CEGUI_DEFINE_PROPERTY(MenuBase, float,
"ItemSpacing", "Property to get/set the item spacing of the menu. Value is a float.",
&MenuBase::setItemSpacing, &MenuBase::getItemSpacing, 10.0f
);
CEGUI_DEFINE_PROPERTY(MenuBase, bool,
"AllowMultiplePopups", "Property to get/set the state of the allow multiple popups setting for the menu. Value is either \"true\" or \"false\".",
&MenuBase::setAllowMultiplePopups, &MenuBase::isMultiplePopupsAllowed, false /* TODO: Inconsistency and awful English */
);
CEGUI_DEFINE_PROPERTY(MenuBase, bool,
"AutoCloseNestedPopups", "Property to set if the menu should close all its open child popups, when it gets hidden. Value is either \"true\" or \"false\".",
&MenuBase::setAutoCloseNestedPopups, &MenuBase::getAutoCloseNestedPopups, false
);
}
/************************************************************************
Set if multiple child popup menus are allowed simultaneously
*************************************************************************/
void MenuBase::setAllowMultiplePopups(bool setting)
{
if (d_allowMultiplePopups != setting)
{
// TODO :
// close all popups except perhaps the last one opened!
d_allowMultiplePopups = setting;
}
}
void MenuBase::setPopupMenuItemClosing()
{
if (d_popupItem)
{
d_popupItem->startPopupClosing();
}
}
//----------------------------------------------------------------------------//
void MenuBase::onChildRemoved(ElementEventArgs& e)
{
// if the removed window was our tracked popup item, zero ptr to it.
if (static_cast<Window*>(e.element) == d_popupItem)
d_popupItem = 0;
// base class version
ItemListBase::onChildRemoved(e);
}
void MenuBase::onHidden(WindowEventArgs&)
{
if (!getAutoCloseNestedPopups())
return;
changePopupMenuItem(0);
if (d_allowMultiplePopups)
{
for (size_t i = 0; i < d_listItems.size(); ++i)
{
if (!d_listItems[i])
continue;
MenuItem* menuItem = dynamic_cast<MenuItem*>(d_listItems[i]);
if (!menuItem)
continue;
if (!menuItem->getPopupMenu())
continue;
WindowEventArgs we(menuItem->getPopupMenu());
menuItem->closePopupMenu(false);
onPopupClosed(we);
}
}
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
|
{
"content_hash": "9767c03bb5bdb91cd954c7cf88138c48",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 163,
"avg_line_length": 35.85353535353536,
"alnum_prop": 0.5210593041273419,
"repo_name": "LiberatorUSA/GUCEF",
"id": "b3d5cf8093376cf8c324fb1e57f9cf8ef927fd0b",
"size": "7099",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "dependencies/cegui/cegui/src/widgets/MenuBase.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "68139"
},
{
"name": "C",
"bytes": "2158073"
},
{
"name": "C++",
"bytes": "14978976"
},
{
"name": "CMake",
"bytes": "7671056"
},
{
"name": "Cuda",
"bytes": "297"
},
{
"name": "Dockerfile",
"bytes": "349"
},
{
"name": "Emacs Lisp",
"bytes": "29494"
},
{
"name": "Fortran",
"bytes": "4029"
},
{
"name": "Java",
"bytes": "1389"
},
{
"name": "Lua",
"bytes": "750004"
},
{
"name": "M4",
"bytes": "1460"
},
{
"name": "Makefile",
"bytes": "295122"
},
{
"name": "NSIS",
"bytes": "35409"
},
{
"name": "Shell",
"bytes": "181211"
},
{
"name": "Tcl",
"bytes": "6493"
},
{
"name": "Vim Script",
"bytes": "121243"
}
],
"symlink_target": ""
}
|
/*
Author: Start Bootstrap - http://startbootstrap.com
'SB Admin' HTML Template by Start Bootstrap
All Start Bootstrap themes are licensed under Apache 2.0.
For more info and more free Bootstrap 3 HTML themes, visit http://startbootstrap.com!
*/
/* ATTN: This is mobile first CSS - to update 786px and up screen width use the media query near the bottom of the document! */
/* Global Styles */
body {
margin-top: 50px;
}
#wrapper {
padding-left: 0;
}
#page-wrapper {
width: 100%;
padding: 5px 15px;
}
/* Nav Messages */
.messages-dropdown .dropdown-menu .message-preview .avatar,
.messages-dropdown .dropdown-menu .message-preview .name,
.messages-dropdown .dropdown-menu .message-preview .message,
.messages-dropdown .dropdown-menu .message-preview .time {
display: block;
}
.messages-dropdown .dropdown-menu .message-preview .avatar {
float: left;
margin-right: 15px;
}
.messages-dropdown .dropdown-menu .message-preview .name {
font-weight: bold;
}
.messages-dropdown .dropdown-menu .message-preview .message {
font-size: 12px;
}
.messages-dropdown .dropdown-menu .message-preview .time {
font-size: 12px;
}
/* Nav Announcements */
.announcement-heading {
font-size: 50px;
margin: 0;
}
.announcement-text {
margin: 0;
}
/* Table Headers */
table.tablesorter thead {
cursor: pointer;
}
table.tablesorter thead tr th:hover {
background-color: #f5f5f5;
}
.td-center td{ text-align:center;}
/*.table-design tr th{ background:#3dc490; color:#fff; border:0px !important; text-transform:uppercase;}
.table-design tr th:hover{ background-color:#009966 !important;}*/
.table-design .fa-check{ color:#3dc490 !important;}
.table-design td .fa{ font-size:16px; color:#777777;}
.table-design td{ vertical-align:middle !important;}
.table-design td a:hover .fa{ color:#3dc490;}
.table-design .small{ font-size:11px !important;}
table .fa-user{color:#42c874 !important;}
table .fa-user.inactive{ color:#dbdbdb !important;}
.mt-10{ margin-top:10px;}
.ml-10{ margin-left:10px;}
.panel-sub-heading{ border-bottom:1px solid #ccc; padding-bottom:10px; margin-bottom:20px}
.tooltip *{ text-align:left !important;}
.dataTables_filter{ text-align:right;}
.dashboard-panel h3{ font-size:14px; text-transform:uppercase; color:#555; font-weight:bold;}
.dashboard-panel h3 a{ color:#555;}
.dashboard-panel a{ color:#999;}
th.edit-category .fa{ display:none;}
th.edit-category:hover .fa{ display:inline-block;}
.add-dropdown{ float:right; margin-right:100px; margin-top:33px}
a:hover{ text-decoration:none;}
.fixed-header thead, .fixed-header tbody, .fixed-header tr, .fixed-header td, .fixed-header th { display: block; }
.fixed-header tr:after {content: ' '; display: block; visibility: hidden; clear: both;}
.fixed-header thead th {height: 30px;}
.fixed-header tbody {height: 300px;overflow-y: auto;}
.fixed-header tbody td, .fixed-header thead th {width: 19.5%;float: left; box-sizing:padding-box !important; text-overflow:ellipsis; white-space:nowrap; overflow:hidden;}
.fixed-header thead th { width:19.2% !important;}
/* Flot Chart Containers */
.flot-chart {
display: block;
height: 400px;
}
.flot-chart-content {
width: 100%;
height: 100%;
}
.jqstooltip{ width:auto !important; height:auto !important;}
/* Edit Below to Customize Widths > 768px */
@media (min-width:768px) {
/* Wrappers */
#wrapper {
padding-left: 250px;
padding-top:50px;
}
#page-wrapper {
padding: 15px 25px;
}
/* Side Nav */
.side-nav {
margin-left: -250px;
left: 250px;
width: 250px;
position: fixed;
top: 100px;
height: 100%;
border-radius: 0;
border: none;
background-color: #30323f !important;
overflow-y: auto;
}
/* Bootstrap Default Overrides - Customized Dropdowns for the Side Nav */
.side-nav>li.dropdown>ul.dropdown-menu {
position: relative;
min-width: 225px;
margin: 0;
padding: 0;
border: none;
border-radius: 0;
background-color: transparent;
box-shadow: none;
-webkit-box-shadow: none;
}
.side-nav>li.dropdown>ul.dropdown-menu>li>a {
color: #999999;
padding: 15px 15px 15px 25px;
}
.side-nav>li.dropdown>ul.dropdown-menu>li>a:hover,
.side-nav>li.dropdown>ul.dropdown-menu>li>a.active,
.side-nav>li.dropdown>ul.dropdown-menu>li>a:focus {
color: #fff;
background-color: #080808;
}
.side-nav>li>a {
width: 250px;
text-transform:uppercase;
font-weight:bold; -webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.side-nav>li>a .fa{ font-size:16px; margin-right:10px;}
.navbar-inverse .navbar-nav>li>a:hover,
.navbar-inverse .navbar-nav>li>a:focus {
background-color: #080808;
}
.navbar .search{float:left; width:428px; margin:34px 0px 0px 25px;}
@-moz-document url-prefix() {
.navbar .search{
width:427px;
}
}
.navbar .search .btn-group{ float:left;}
.navbar .search .btn-group .btn-default{ height:46px;}
.navbar .search .btn-group .dropdown-toggle{ border-radius:0px 0px 0px 0px; border-width:1px 0px;}
.navbar .search .search-btn{background-color:#428bca; color:#fff; font-size:24px; border:0px;}
.navbar .search .input{ width:295px; float:left; height:46px;}
/* Nav Messages */
.messages-dropdown .dropdown-menu {
min-width: 300px;
}
.messages-dropdown .dropdown-menu li a {
white-space: normal;
}
.navbar-collapse {
padding-left: 15px !important;
padding-right: 15px !important;
}
/* Background colors */
.bg-red,
.bg-yellow,
.bg-aqua,
.bg-blue,
.bg-light-blue,
.bg-green,
.bg-navy,
.bg-teal,
.bg-olive,
.bg-lime,
.bg-orange,
.bg-fuchsia,
.bg-purple,
.bg-maroon,
.bg-black {
color: #f9f9f9 !important;
}
.bg-gray {
background-color: #eaeaec !important;
}
.bg-black {
background-color: #222222 !important;
}
.bg-red {
background-color: #f56954 !important;
}
.bg-yellow {
background-color: #f39c12 !important;
}
.bg-aqua {
background-color: #00c0ef !important;
}
.bg-blue {
background-color: #0073b7 !important;
}
.bg-light-blue {
background-color: #3c8dbc !important;
}
.bg-green {
background-color: #00a65a !important;
}
.bg-navy {
background-color: #001f3f !important;
}
.bg-teal {
background-color: #39cccc !important;
}
.bg-olive {
background-color: #3d9970 !important;
}
.bg-lime {
background-color: #01ff70 !important;
}
.bg-orange {
background-color: #ff851b !important;
}
.bg-fuchsia {
background-color: #f012be !important;
}
.bg-purple {
background-color: #932ab6 !important;
}
.bg-maroon {
background-color: #85144b !important;
}
/* Text colors */
.text-red {
color: #f56954 !important;
}
.text-yellow {
color: #f39c12 !important;
}
.text-aqua {
color: #00c0ef !important;
}
.text-blue {
color: #0073b7 !important;
}
.text-light-blue {
color: #3c8dbc !important;
}
.text-green {
color: #00a65a !important;
}
.text-navy {
color: #001f3f !important;
}
.text-teal {
color: #39cccc !important;
}
.text-olive {
color: #3d9970 !important;
}
.text-lime {
color: #01ff70 !important;
}
.text-orange {
color: #ff851b !important;
}
.text-fuchsia {
color: #f012be !important;
}
.text-purple {
color: #932ab6 !important;
}
.text-maroon {
color: #85144b !important;
}
}
|
{
"content_hash": "6a901fb13d4d3c73cb1bdd654471110c",
"timestamp": "",
"source": "github",
"line_count": 324,
"max_line_length": 170,
"avg_line_length": 24.69753086419753,
"alnum_prop": 0.6178455386153462,
"repo_name": "maor10/Projectkerendanieli",
"id": "8df1d1e9bda816a3f87b371c8b267c783e2b9221",
"size": "8002",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "css/sb-admin.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "87301"
},
{
"name": "HTML",
"bytes": "5391642"
},
{
"name": "JavaScript",
"bytes": "664754"
},
{
"name": "PHP",
"bytes": "1768744"
}
],
"symlink_target": ""
}
|
#ifndef ZEPHIR_KERNEL_OBJECT_H
#define ZEPHIR_KERNEL_OBJECT_H
#include <php.h>
#include <Zend/zend.h>
#include "kernel/globals.h"
#include "kernel/main.h"
/** Class Retrieving/Checking */
int zephir_class_exists(const zval *class_name, int autoload);
int zephir_interface_exists(const zval *interface_name, int autoload);
void zephir_get_called_class(zval *return_value);
zend_class_entry *zephir_fetch_class(const zval *class_name);
zend_class_entry *zephir_fetch_class_str_ex(char *class_name, size_t length, int fetch_type);
void zephir_get_class(zval *result, zval *object, int lower);
void zephir_get_class_ns(zval *result, zval *object, int lower TSRMLS_DC);
void zephir_get_ns_class(zval *result, zval *object, int lower TSRMLS_DC);
/** Cloning/Instance of */
int zephir_clone(zval *destination, zval *obj);
int zephir_is_instance_of(zval *object, const char *class_name, unsigned int class_length);
int zephir_instance_of_ev(const zval *object, const zend_class_entry *ce);
int zephir_zval_is_traversable(zval *object);
/** Method exists */
int zephir_method_exists(const zval *object, const zval *method_name);
/** Isset properties */
int zephir_isset_property(zval *object, const char *property_name, unsigned int property_length);
int zephir_isset_property_zval(zval *object, const zval *property);
/** Reading properties */
int zephir_read_property(zval *result, zval *object, const char *property_name, zend_uint property_length, int silent);
int zephir_read_property_zval(zval *result, zval *object, zval *property, int silent);
int zephir_return_property(zval *return_value, zval *object, char *property_name, unsigned int property_length);
int zephir_fetch_property(zval *result, zval *object, const char *property_name, zend_uint property_length, int silent);
int zephir_fetch_property_zval(zval *result, zval *object, zval *property, int silent);
/** Updating properties */
int zephir_update_property_zval(zval *obj, const char *property_name, unsigned int property_length, zval *value);
int zephir_update_property_zval_zval(zval *obj, zval *property, zval *value);
/** Updating array properties */
int zephir_update_property_array(zval *object, const char *property, zend_uint property_length, const zval *index, zval *value);
int zephir_update_property_array_string(zval *object, char *property, unsigned int property_length, char *index, unsigned int index_length, zval *value);
int zephir_update_property_array_append(zval *object, char *property, unsigned int property_length, zval *value);
int zephir_update_property_array_multi(zval *object, const char *property, zend_uint property_length, zval *value, const char *types, int types_length, int types_count, ...);
/** Unset properties */
int zephir_unset_property(zval* object, const char* name);
int zephir_unset_property_array(zval *object, char *property, unsigned int property_length, zval *index);
/** Static properties */
int zephir_read_static_property_ce(zval *result, zend_class_entry *ce, const char *property, int len, int flags);
int zephir_update_static_property_ce(zend_class_entry *ce, const char *name, int len, zval *value);
int zephir_update_static_property_array_multi_ce(zend_class_entry *ce, const char *property, zend_uint property_length, zval *value, const char *types, int types_length, int types_count, ...);
/** Create closures */
int zephir_create_closure_ex(zval *return_value, zval *this_ptr, zend_class_entry *ce, const char *method_name, zend_uint method_length);
/** Create instances */
int zephir_create_instance(zval *return_value, const zval *class_name);
/** Increment/Decrement properties */
#define zephir_property_incr(object, property) zephir_property_incr_decr(object, property, 1)
#define zephir_property_decr(object, property) zephir_property_incr_decr(object, property, 0)
int zephir_property_incr_decr(zval *object, char *property_name, unsigned int property_length, unsigned int increment);
#define zephir_fetch_safe_class(destination, var) { \
if (Z_TYPE(var) == IS_STRING) { \
ZEPHIR_CPY_WRT(&destination, &var); \
} else { \
ZEPHIR_INIT_NVAR(&destination); \
ZVAL_STRING(&destination, "<undefined class>"); \
} \
}
#endif
|
{
"content_hash": "62e888ee7f0842b420fa843351b5d8f4",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 192,
"avg_line_length": 50.397590361445786,
"alnum_prop": 0.7487449199139373,
"repo_name": "part-lang/part",
"id": "b9a2cbdec91a7bdcb547d82d7795b46b65d52b24",
"size": "5420",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "ext/kernel/object.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "320656"
},
{
"name": "HTML",
"bytes": "44"
},
{
"name": "Shell",
"bytes": "2246"
},
{
"name": "Zephir",
"bytes": "23641"
}
],
"symlink_target": ""
}
|
package C2;
public class Ejercicio12 {
public static void main(String[] args) {
int numero = LibLeer.entero("Introduce un número para calcular su factorial: ");
long factorial = 1;
for (int i = 1; i <= numero; i++) factorial *= i;
System.out.println(numero + "! = " + factorial);
}
}
|
{
"content_hash": "dbbca43f4c2942d19642c280a320d181",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 82,
"avg_line_length": 24,
"alnum_prop": 0.5773809523809523,
"repo_name": "xChasingWaves/clase",
"id": "309f95eecc57eb9e6f81dd83db1c808d5c31050f",
"size": "336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Programacion/Unidad03/C2/Ejercicio12.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "108486"
}
],
"symlink_target": ""
}
|
using System.Collections.Generic;
using System.Linq;
using Hermes.DataObjects.Application;
using Hermes.DataObjects.Channel;
using Hermes.DataObjects.Notification;
using Hermes.Entity.Models;
namespace Hermes.Services.Helpers
{
public static class DtoBuilder
{
public static ApplicationDto ToDto(this Application application)
{
return new ApplicationDto {Id = application.application_id, Name = application.application_name};
}
public static ChannelDto ToDto(this Channel channel)
{
return new ChannelDto
{
Id = channel.channel_id,
ApplicationId = channel.application_id,
Name = channel.channel_name
};
}
public static NotificationDto ToDto(this Notification notification)
{
return new NotificationDto
{
ApplicationId = notification.Channel != null ? notification.Channel.application_id : 0,
ApplicationName = (notification.Channel != null && notification.Channel.Application != null) ? notification.Channel.Application.application_name : null,
ChannelId = notification.channel_id,
ChannelName = notification.Channel != null ? notification.Channel.channel_name : "",
Id = notification.notification_id,
Persistent = true,
Time = notification.notification_time,
Message = notification.notification_message,
Code = notification.notification_code,
Tags = notification.NotificationTags != null ? notification.NotificationTags.ToDictionary(t => t.notification_tag_key, t => t.notification_tag_value) : new Dictionary<string, string>()
};
}
}
}
|
{
"content_hash": "30a8449ab1849f9c97e79562944cc64b",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 200,
"avg_line_length": 39.52173913043478,
"alnum_prop": 0.6314631463146315,
"repo_name": "Mithra/hermes",
"id": "24cc5d8c42bfe2d9b93ed0e6caf630b0ee77da2a",
"size": "1818",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/_Common/Hermes.Services/Helpers/DtoBuilder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "123784"
}
],
"symlink_target": ""
}
|
<?php
namespace Google\Service\Contentwarehouse;
class GoogleCloudDocumentaiV1DocumentPageToken extends \Google\Collection
{
protected $collection_key = 'detectedLanguages';
protected $detectedBreakType = GoogleCloudDocumentaiV1DocumentPageTokenDetectedBreak::class;
protected $detectedBreakDataType = '';
protected $detectedLanguagesType = GoogleCloudDocumentaiV1DocumentPageDetectedLanguage::class;
protected $detectedLanguagesDataType = 'array';
protected $layoutType = GoogleCloudDocumentaiV1DocumentPageLayout::class;
protected $layoutDataType = '';
protected $provenanceType = GoogleCloudDocumentaiV1DocumentProvenance::class;
protected $provenanceDataType = '';
/**
* @param GoogleCloudDocumentaiV1DocumentPageTokenDetectedBreak
*/
public function setDetectedBreak(GoogleCloudDocumentaiV1DocumentPageTokenDetectedBreak $detectedBreak)
{
$this->detectedBreak = $detectedBreak;
}
/**
* @return GoogleCloudDocumentaiV1DocumentPageTokenDetectedBreak
*/
public function getDetectedBreak()
{
return $this->detectedBreak;
}
/**
* @param GoogleCloudDocumentaiV1DocumentPageDetectedLanguage[]
*/
public function setDetectedLanguages($detectedLanguages)
{
$this->detectedLanguages = $detectedLanguages;
}
/**
* @return GoogleCloudDocumentaiV1DocumentPageDetectedLanguage[]
*/
public function getDetectedLanguages()
{
return $this->detectedLanguages;
}
/**
* @param GoogleCloudDocumentaiV1DocumentPageLayout
*/
public function setLayout(GoogleCloudDocumentaiV1DocumentPageLayout $layout)
{
$this->layout = $layout;
}
/**
* @return GoogleCloudDocumentaiV1DocumentPageLayout
*/
public function getLayout()
{
return $this->layout;
}
/**
* @param GoogleCloudDocumentaiV1DocumentProvenance
*/
public function setProvenance(GoogleCloudDocumentaiV1DocumentProvenance $provenance)
{
$this->provenance = $provenance;
}
/**
* @return GoogleCloudDocumentaiV1DocumentProvenance
*/
public function getProvenance()
{
return $this->provenance;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDocumentaiV1DocumentPageToken::class, 'Google_Service_Contentwarehouse_GoogleCloudDocumentaiV1DocumentPageToken');
|
{
"content_hash": "e687f7c88208e65ac33464d6fca03d63",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 137,
"avg_line_length": 30.07792207792208,
"alnum_prop": 0.768566493955095,
"repo_name": "googleapis/google-api-php-client-services",
"id": "8a893d078b31c22ffc4eb28d819167ed0cd85f0a",
"size": "2906",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Contentwarehouse/GoogleCloudDocumentaiV1DocumentPageToken.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "55414116"
},
{
"name": "Python",
"bytes": "427325"
},
{
"name": "Shell",
"bytes": "787"
}
],
"symlink_target": ""
}
|
object Test {
def main(args: Array[String]): Unit =
classOf[java.nio.file.AccessMode].getEnumConstants
}
|
{
"content_hash": "bf3c8ad1e7816b68f04ff342ed04a3f4",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 54,
"avg_line_length": 18.833333333333332,
"alnum_prop": 0.7079646017699115,
"repo_name": "sjrd/dotty",
"id": "a7980294f8ed4df0531d8b23f0080a821b17ce93",
"size": "133",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "tests/run/i1387.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "836"
},
{
"name": "CSS",
"bytes": "136099"
},
{
"name": "HTML",
"bytes": "3463"
},
{
"name": "Java",
"bytes": "227667"
},
{
"name": "JavaScript",
"bytes": "153556"
},
{
"name": "Scala",
"bytes": "18018431"
},
{
"name": "Shell",
"bytes": "23230"
},
{
"name": "TypeScript",
"bytes": "8378"
}
],
"symlink_target": ""
}
|
module Lab4 where
import Data.List
import System.Random
import Test.QuickCheck
import SetOrd
-- Exercise 1
{- Questions :
[Ger] (Time spent reading: 2 hours) -> Chapter 4.2 & Example 4.5 the Russel paradoxes. The logic appears to make no sense at all.
Perhaps a practical example would help to make sense of what the authors are trying to tell us,
Because pseudo-haskell code only confuses me more. The rest of the chapter was pretty clear.
[Robert] (Time spent reading: 3 hours) ->
Question 1
I was wondering how I should read notion 5 in Theorem 4.38.
What does the "["insert-some-set-operations-here"]" mean compared to "("insert-someset-operations-here")" ?
Or is this a printing mistake?
Question 2
I used the term "notion" to address a part of a theorem in the question above. I was wondering if this is correct.
The beginning of the chapter briefly address the terms, however it seems not to address this specific question.
Question 3
In Haskell what is the difference between the usage of "case" and equation guarding?
To me the two seem oddly similar.
Concerning the logic in chapter 4 I have no specific questions.
[Alberto] (Time spent reading: several days in small chunks, mostly during commuting) ->
As Ger, my I didn't understand the example 4.5 about the Russel Paradox. It starts with
an acceptable assumption (most of the sets don't contain themselves) which makes sense.
For instance, a set of integeres only contains integers, not sets of integers. But after,
when supposing the opposite, I get lost in the following statements, specially in the one
that affirms that that is not possible to prove.
After, the section 4.2 is confusing as well. I have some background about the halt problem
but the whole approach (specially with the funny function) is confusing and as I wasn't even
able to understand what the author wants to prove, I decided to just read the section quickly.
-}
-- Exercise 2
-- Using the Random class from the Haskell library does not apply to our type Set a.
-- The Random class specifically needs a type of * while Set is of type *->*. This causes clashes in the Random class.
-- I try to write a Wrapper as suggest on some internet fora, however I did not succeed.
min_set_length :: Int
min_set_length = 0
max_set_length :: Int
max_set_length = 30
min_random_value :: Int
min_random_value = -1000
max_random_value :: Int
max_random_value = 1000
exercise2:: IO()
exercise2 = do
seed <- newStdGen
let (int1, seed2) = randomInt seed
let rs = randomlist int1 seed2
let s = list2set rs
print $ (show s)
randomInt :: StdGen -> (Int, StdGen)
randomInt gen = randomR (min_set_length, max_set_length) gen
randomlist :: Int -> StdGen -> [Int]
randomlist n gen = take n (randomRs (min_random_value, max_random_value) gen)
-- Should be able to generate random list of any type
instance (Arbitrary a, Ord a) => Arbitrary (Set a) where
arbitrary = fmap list2set arbitrary
-- Use this to test the above function: verboseCheck prop_setIntEqItself
prop_setIntEqItself :: (Set Int) -> Bool
prop_setIntEqItself a = a == a
-- Exercise 3
-- unionSet is already defined in SetOrd.hs so we will only implement intersection and difference
intersectionSet :: (Ord a) => Set a -> Set a -> Set a
intersectionSet (Set []) _ = (Set [])
intersectionSet _ (Set []) = (Set [])
intersectionSet (Set (x:xs)) set2
| inSet x set2 = insertSet x (intersectionSet (Set xs) set2)
| otherwise = intersectionSet (Set xs) set2
differenceSet :: (Ord a) => Set a -> Set a -> Set a
differenceSet set1 (Set []) = set1
differenceSet (Set []) set2 = set2
differenceSet (Set (x:xs)) set2
| not $ inSet x set2 = insertSet x (differenceSet (Set xs) set2)
| otherwise = differenceSet (Set xs) (deleteSet x set2)
-- Exercise 4
{-
Questions :
[Ger] (Time spent reading: 2 hours) -> The entire chapter was very mathsy, making it long and unintersting to read. Furthermore the chapter
introduces a lot of concepts which are fragmented throughout, perhaps a summary of concepts introduced in
the chapter would be in order.
[Alberto] (Time spent reading: several days in small chunks, mostly during commuting) ->
In several of the examples (specially at around page 175 because I had to check them often
in order to do the other exercises), the the topic covered are relations and although the
definition of the functions refer to Rel, the implementation use Set. Is this a mistake?
-}
-- Exercise 5
-- Time spent : 30 minutes
type Rel a = [(a,a)]
symClos :: Ord a => Rel a -> Rel a
symClos x = sort $ nub $ generateSymClosures x
generateSymClosures :: Ord a => Rel a -> Rel a
generateSymClosures [] = []
generateSymClosures ((x,y):xs) = [(x,y)] ++ [(y,x)] ++ generateSymClosures xs
-- Exercise 6
-- Time spent : 1 hour
infixr 5 @@
(@@) :: Eq a => Rel a -> Rel a -> Rel a
r @@ s = nub [ (x,z) | (x,y) <- r, (w,z) <- s, y == w ]
-- Wrapper function since recursive nature of trClos' does not prevent duplicates
trClos :: Ord a => Rel a -> Rel a
trClos x = sort $ nub $ trClos' x
trClos' :: Ord a => Rel a -> Rel a
trClos' [] = []
trClos' [(x,y)] = [(x,y)]
trClos' ((x,y):xs) = [(x,y)] ++ generateTransClosures [(x,y)] xs [] ++ trClos' xs
-- 1st argument : Tuple to generate closures for
-- 2nd argument : Relations to generate closures against
-- 3th argument : List of already checked closures
generateTransClosures :: Ord a => Rel a -> Rel a -> Rel a -> Rel a
generateTransClosures x y z
| ((removeAlreadyChecked x z) @@ y) /= [] = ((removeAlreadyChecked x z) @@ y) ++
generateTransClosures ((removeAlreadyChecked x z) @@ y) y ((removeAlreadyChecked x z) ++ z)
| otherwise = []
-- Makes sure we do not get stuck in an infinite loop
removeAlreadyChecked :: Ord a => Rel a -> Rel a -> Rel a
removeAlreadyChecked [] _ = []
removeAlreadyChecked ((x,y):xs) z
| elem (x,y) z = removeAlreadyChecked xs z
| otherwise = (x,y) : removeAlreadyChecked xs z
-- Exercise 7
-- Time spent: 6 hours
-- The first step is to define the properties that those relations hold.
-- Starting with the symmetric relation, based on the following definition:
-- (definition from Wikipedia: https://en.wikipedia.org/wiki/Symmetric_closure)
--
-- S = R u {(x,y):(y,x) € R)
--
-- We can state that:
-- 1. S size must be smaller or equal than twice R.
-- 2. For each element of S must exist other element in S that is symmetric.
-- 3. All the elements must be ordered.
-- First property: S must be smaller or equal than twice R.
-- In case R does not contains any symmetric relation, size S == 2 * size R.
-- In case R only contains symmetric relations, size S == size R
symSizeProp :: Rel a -> Rel a -> Bool
symSizeProp r s = length s <= 2 * length r
-- Second property: Foreach element in R must be one symmetric in S and itself.
symSymProp :: Ord a => Rel a -> Rel a -> Bool
symSymProp [] [] = True -- In case R == S
symSymProp [] _ = True -- Normal base case.
symSymProp _ [] = False -- In case the size R > size S
symSymProp ((x,y):rs) s = elem (x,y) s && elem (y,x) s && (symSymProp rs s)
-- Third property: Elements must be ordered.
symOrdProp :: Ord a => Rel a -> Bool
symOrdProp [] = True
symOrdProp [(_,_)] = True
symOrdProp ((x,y):(x',y'):ss)
| x < x' = True && symOrdProp ((x',y'):ss)
| x == x' && y <= y' = True && symOrdProp ((x',y'):ss)
| otherwise = False
-- This one is specially tricky. Uncountable hours have been spent just
-- generating proper relation. The first issue to address is to generate a pair
-- of arbitrary elements. The only way to address this issue is generating two
-- elements independently and then using and if-then-else reordering them. After
-- generating a pair, we create a list based on this pair.
--
-- As the only constraint for the Relations is to be Ord a, QuickCheck by
-- default will use empty pairs ((),()) (this can be checked running
-- `verboseCheck testSymClos` after commenting the following lines). Therefore,
-- I added the type Num to the definition to force QuickCheck to use meaningful
-- data.
instance (Num a, Ord a, Arbitrary a) => Arbitrary (Rel a) where
arbitrary = listOf $ do
x <- arbitrary
y <- arbitrary
if x < y then return (x,y)
else return (y,x)
-- Test function for the symmetric closures. In order to supress the warning,
-- Integer can be used insted of a. In order to define the most general test
-- possible, the anonymous type has been preserved.
--
-- Run using:
-- quickCheck testSymClos
testSymClos :: Ord a => Rel a -> Bool
testSymClos r = let s = symClos r in symOrdProp s && symSizeProp r s && symSymProp r s
-- For the transitive relation, we apply the same idea
-- 1. R is contained in R+
-- 2. R+ is ordered.
-- 3. R+ is transitive.
-- 4. R+ is the minimal union of R^i
-- First property: To check that the elements of R are contained in R+ is almost
-- trivial.
trContainsProp :: Ord a => Rel a -> Rel a -> Bool
trContainsProp r rp = all (\x -> x `elem` rp) r
-- Second property: This is not a real property of the transitive closure, but
-- the description says that the relation is ordered. Therefore, we will reuse
-- the same implementation used with the symmetric closure.
trOrdProp :: Ord a => Rel a -> Bool
trOrdProp = symOrdProp
-- Third property: In order to test this property we will just follow the
-- guidelines in the pages 175 and 177 of the book to check the transitivity.
trTransProp :: Ord a => Rel a -> Bool
trTransProp [] = True
trTransProp rp = and [trans pair rp | pair <- rp] where
trans (x,y) rp' =
and [(x,v) `elem` rp' | (u,v) <- rp', u == y ]
-- To check the last property is not viable due to the combinatorial explosion
-- that can be generated when trying to check for every element of R+ in which
-- R^i it is placed (in relations big enough it can grow really big with a high
-- i value, in addition to be difficult to decide when to stop checking new
-- iterations). It would be a hard test on the software because it will
-- secure not only the property but also if it is complete. As we learnt during
-- week 2 testing the dearrangements, it is not viable to do it and other
-- properties (like property number 3) should be tested instead.
-- Test function for the transitive closures. In order to supress the warning,
-- Integer can be used insted of a. In order to define the most general test
-- possible, the anonymous type has been preserved.
--
-- Run using:
-- quickCheck testTrClos
testTrClos :: Ord a => Rel a -> Bool
testTrClos r = let rp = trClos r in trContainsProp r rp && trOrdProp rp && trTransProp rp
-- Exercise 8
{-
As example we can use the basic relation from exercise 5 and 6.
GHCI Code :
*Lab4> symClos $ trClos [(1,2),(2,3),(3,4)]
[(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(2,3),(3,2),(2,4),(4,2),(3,4),(4,3)]
*Lab4> trClos $ symClos [(1,2),(2,3),(3,4)]
[(1,2),(1,1),(1,3),(1,4),(2,1),(2,3),(2,2),(2,4),(3,2),(3,4),(3,3),(4,3)]
As you can see these aren't the same, this is because if you first apply the symmetric closure and then the transitive closure,
you will always get a link from a node to itself, as you can always get back to the starting point in two hops. Whereas, if you
first apply the transitive closure and then the symmetric one. You will get no relations from a node to itself if they weren't there
before.
-}
|
{
"content_hash": "d0fd6659db25b278ff11265521776afe",
"timestamp": "",
"source": "github",
"line_count": 286,
"max_line_length": 143,
"avg_line_length": 40.03496503496503,
"alnum_prop": 0.6907423580786026,
"repo_name": "Gurrt/software-testing",
"id": "408bdfb2c07353d2044305e0f51a46fcd51e81d6",
"size": "11452",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "week-4/Lab4.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "125018"
}
],
"symlink_target": ""
}
|
package it.polimi.genomics.spark.test
import it.polimi.genomics.GMQLServer.{DefaultRegionsToRegionFactory, GmqlServer}
import it.polimi.genomics.core.DataStructures.MetaJoinCondition.{Default, MetaJoinCondition}
import it.polimi.genomics.core.DataStructures.RegionAggregate.RegionsToRegion
import it.polimi.genomics.core.ParsingType.PARSING_TYPE
import it.polimi.genomics.core.{GDouble, GString, GValue, ParsingType}
import it.polimi.genomics.spark.implementation.GMQLSparkExecutor
import it.polimi.genomics.spark.implementation.loaders.test3Parser
import org.apache.spark.{SparkConf, SparkContext}
/**
* The entry point of the application
* It initialize the server, call server's methods to build the query and invoke the server's run method to start the execution.
*/
object Map {
def main(args : Array[String]) {
val mainPath = "/home/abdulrahman/IDEA/GMQL_V2/GMQL-Flink/src/test/datasets/"
val ex_data_path = List(mainPath + "map/exp/")
val ex_data_path_optional = List(mainPath + "map/ref/")
val output_path = mainPath + "res3/"
val what = 0 // simple map
//val what = 1 // map with aggregation
// val what = 2 // map with grouping and aggregation
val conf = new SparkConf()
.setAppName("GMQL V2 Spark")
.setMaster("local[*]")
.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
val sc:SparkContext =new SparkContext(conf)
val server = new GmqlServer(new GMQLSparkExecutor(sc = sc))
val dataAsTheyAre = server READ ex_data_path USING test3Parser()
val optionalDS = server READ ex_data_path_optional USING test3Parser()
val map = what match{
case 0 =>
// MAP
optionalDS.MAP(None, List(), dataAsTheyAre)
case 1 =>
// MAP with aggregation
dataAsTheyAre.MAP(None, List( DefaultRegionsToRegionFactory.get("MAX",0,Some("newScore")) ), optionalDS)
case 2 =>
//MAP with grouping and aggregation
dataAsTheyAre.MAP(
Some(new MetaJoinCondition(List(Default("bert_value1")))),
List(
new RegionsToRegion {
override val resType = ParsingType.DOUBLE
override val index: Int = 0
override val associative: Boolean = true
override val funOut: (GValue,(Int, Int)) => GValue = {(v1,v2)=>v1}
override val fun: (List[GValue]) => GValue = {
(line) =>{val ss = line.map(_.asInstanceOf[GDouble].v)
if(!ss.isEmpty) GDouble(ss.reduce(_ + _))else GDouble (0)
}
}},
new RegionsToRegion {
override val resType: PARSING_TYPE = ParsingType.STRING
override val index: Int = 1
override val associative: Boolean = false
override val funOut: (GValue, (Int, Int)) => GValue = { (v1, v2) => v1 }
override val fun: (List[GValue]) => GValue = {
(list) => GString(list.map((gvalue) => gvalue.asInstanceOf[GString].v).reduce((word1: String, word2: String) => word1 + " " + word2))
}
}
),
optionalDS
)
}
server setOutputPath output_path MATERIALIZE map
server.run()
}
}
|
{
"content_hash": "7772cf866479d8f3448867d8174467cb",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 147,
"avg_line_length": 38.35294117647059,
"alnum_prop": 0.6334355828220859,
"repo_name": "DEIB-GECO/GMQL",
"id": "b889d01e16fe9506f17a06bff9891f270a37759a",
"size": "3260",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GMQL-Spark/src/main/scala/it/polimi/genomics/spark/test/Map.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "2801"
},
{
"name": "Scala",
"bytes": "881931"
}
],
"symlink_target": ""
}
|
<?php
/**
* @package toolkit
*/
/**
* The Section class represents a Symphony Section object. A section is a model
* of a data structure using one or more Fields. Sections are stored in the database
* and are used as repositories for Entry objects, which are a model for this data
* structure. This class contains functions for finding Fields within a Section and
* saving a Section's settings.
*/
class Section
{
/**
* An array of the Section's settings
* @var array
*/
protected $_data = array();
/**
* A setter function that will save a section's setting into
* the poorly named `$this->_data` variable
*
* @param string $setting
* The setting name
* @param string $value
* The setting value
*/
public function set($setting, $value)
{
$this->_data[$setting] = $value;
}
/**
* An accessor function for this Section's settings. If the
* $setting param is omitted, an array of all settings will
* be returned. Otherwise it will return the data for
* the setting given.
*
* @param null|string $setting
* @return array|string
* If setting is provided, returns a string, if setting is omitted
* returns an associative array of this Section's settings
*/
public function get($setting = null)
{
if (is_null($setting)) {
return $this->_data;
}
return $this->_data[$setting];
}
/**
* Returns the default field this Section will be sorted by.
* This is determined by the first visible field that is allowed to
* to be sorted (defined by the field's `isSortable()` function).
* If no fields exist or none of them are visible in the entries table,
* 'id' is returned instead.
*
* @since Symphony 2.3
* @throws Exception
* @return string
* Either the field ID or the string 'id'.
*/
public function getDefaultSortingField()
{
$fields = $this->fetchVisibleColumns();
foreach ($fields as $field) {
if (!$field->isSortable()) {
continue;
}
return $field->get('id');
}
return 'id';
}
/**
* Returns the field this Section will be sorted by, or calls
* `getDefaultSortingField()` if the configuration file doesn't
* contain any settings for that Section.
*
* @since Symphony 2.3
* @throws Exception
* @return string
* Either the field ID or the string 'id'.
*/
public function getSortingField()
{
$result = Symphony::Configuration()->get('section_' . $this->get('handle') . '_sortby', 'sorting');
return (is_null($result) ? $this->getDefaultSortingField() : $result);
}
/**
* Returns the sort order for this Section. Defaults to 'asc'.
*
* @since Symphony 2.3
* @return string
* Either 'asc' or 'desc'.
*/
public function getSortingOrder()
{
$result = Symphony::Configuration()->get('section_' . $this->get('handle') . '_order', 'sorting');
return (is_null($result) ? 'asc' : $result);
}
/**
* Saves the new field this Section will be sorted by.
*
* @since Symphony 2.3
* @param string $sort
* The field ID or the string 'id'.
* @param boolean $write
* If false, the new settings won't be written on the configuration file.
* Defaults to true.
*/
public function setSortingField($sort, $write = true)
{
Symphony::Configuration()->set('section_' . $this->get('handle') . '_sortby', $sort, 'sorting');
if ($write) {
Symphony::Configuration()->write();
}
}
/**
* Saves the new sort order for this Section.
*
* @since Symphony 2.3
* @param string $order
* Either 'asc' or 'desc'.
* @param boolean $write
* If false, the new settings won't be written on the configuration file.
* Defaults to true.
*/
public function setSortingOrder($order, $write = true)
{
Symphony::Configuration()->set('section_' . $this->get('handle') . '_order', $order, 'sorting');
if ($write) {
Symphony::Configuration()->write();
}
}
/**
* Returns any section associations this section has with other sections
* linked using fields. Has an optional parameter, `$respect_visibility` that
* will only return associations that are deemed visible by a field that
* created the association. eg. An articles section may link to the authors
* section, but the field that links these sections has hidden this association
* so an Articles column will not appear on the Author's Publish Index
*
* @deprecated This function will be removed in Symphony 3.0. Use `SectionManager::fetchChildAssociations` instead.
* @param boolean $respect_visibility
* Whether to return all the section associations regardless of if they
* are deemed visible or not. Defaults to false, which will return all
* associations.
* @return array
*/
public function fetchAssociatedSections($respect_visibility = false)
{
if (Symphony::Log()) {
Symphony::Log()->pushDeprecateWarningToLog('Section::fetchAssociatedSections()', 'SectionManager::fetchChildAssociations()');
}
return SectionManager::fetchChildAssociations($this->get('id'), $respect_visibility);
}
/**
* Returns any section associations this section has with other sections
* linked using fields, and where this section is the parent in the association.
* Has an optional parameter, `$respect_visibility` that
* will only return associations that are deemed visible by a field that
* created the association. eg. An articles section may link to the authors
* section, but the field that links these sections has hidden this association
* so an Articles column will not appear on the Author's Publish Index
*
* @since Symphony 2.3.3
* @param boolean $respect_visibility
* Whether to return all the section associations regardless of if they
* are deemed visible or not. Defaults to false, which will return all
* associations.
* @return array
*/
public function fetchChildAssociations($respect_visibility = false)
{
return SectionManager::fetchChildAssociations($this->get('id'), $respect_visibility);
}
/**
* Returns any section associations this section has with other sections
* linked using fields, and where this section is the child in the association.
* Has an optional parameter, `$respect_visibility` that
* will only return associations that are deemed visible by a field that
* created the association. eg. An articles section may link to the authors
* section, but the field that links these sections has hidden this association
* so an Articles column will not appear on the Author's Publish Index
*
* @since Symphony 2.3.3
* @param boolean $respect_visibility
* Whether to return all the section associations regardless of if they
* are deemed visible or not. Defaults to false, which will return all
* associations.
* @return array
*/
public function fetchParentAssociations($respect_visibility = false)
{
return SectionManager::fetchParentAssociations($this->get('id'), $respect_visibility);
}
/**
* Returns an array of all the fields in this section that are to be displayed
* on the entries table page ordered by the order in which they appear
* in the Section Editor interface
*
* @throws Exception
* @return array
*/
public function fetchVisibleColumns()
{
return FieldManager::fetch(null, $this->get('id'), 'ASC', 'sortorder', null, null, " AND t1.show_column = 'yes' ");
}
/**
* Returns an array of all the fields in this section optionally filtered by
* the field type or it's location within the section.
*
* @param string $type
* The field type (it's handle as returned by `$field->handle()`)
* @param string $location
* The location of the fields in the entry creator, whether they are
* 'main' or 'sidebar'
* @throws Exception
* @return array
*/
public function fetchFields($type = null, $location = null)
{
return FieldManager::fetch(null, $this->get('id'), 'ASC', 'sortorder', $type, $location);
}
/**
* Returns an array of all the fields that can be filtered.
*
* @param string $location
* The location of the fields in the entry creator, whether they are
* 'main' or 'sidebar'
* @throws Exception
* @return array
*/
public function fetchFilterableFields($location = null)
{
return FieldManager::fetch(null, $this->get('id'), 'ASC', 'sortorder', null, $location, null, Field::__FILTERABLE_ONLY__);
}
/**
* Returns an array of all the fields that can be toggled. This function
* is used to help build the With Selected drop downs on the Publish
* Index pages
*
* @param string $location
* The location of the fields in the entry creator, whether they are
* 'main' or 'sidebar'
* @throws Exception
* @return array
*/
public function fetchToggleableFields($location = null)
{
return FieldManager::fetch(null, $this->get('id'), 'ASC', 'sortorder', null, $location, null, Field::__TOGGLEABLE_ONLY__);
}
/**
* Returns the Schema of this section which includes all this sections
* fields and their settings.
*
* @return array
*/
public function fetchFieldsSchema()
{
return FieldManager::fetchFieldsSchema($this->get('id'));
}
/**
* Commit the settings of this section from the section editor to
* create an instance of this section in `tbl_sections`. This function
* loops of each of the fields in this section and calls their commit
* function.
*
* @see toolkit.Field#commit()
* @return boolean
* true if the commit was successful, false otherwise.
*/
public function commit()
{
$settings = $this->_data;
if (isset($settings['id'])) {
$id = $settings['id'];
unset($settings['id']);
$section_id = SectionManager::edit($id, $settings);
if ($section_id) {
$section_id = $id;
}
} else {
$section_id = SectionManager::add($settings);
}
if (is_numeric($section_id) && $section_id !== false) {
for ($ii = 0, $length = count($this->_fields); $ii < $length; $ii++) {
$this->_fields[$ii]->set('parent_section', $section_id);
$this->_fields[$ii]->commit();
}
}
}
}
|
{
"content_hash": "e2333857a0dc37fcb3a0e52d6ce2afc3",
"timestamp": "",
"source": "github",
"line_count": 321,
"max_line_length": 137,
"avg_line_length": 34.33021806853583,
"alnum_prop": 0.6165154264972776,
"repo_name": "michael-e/symphony-2",
"id": "1fec5c158a954320fa63beb3dd5a0c429d6f895c",
"size": "11020",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "symphony/lib/toolkit/class.section.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "61994"
},
{
"name": "JavaScript",
"bytes": "258688"
},
{
"name": "PHP",
"bytes": "1771544"
},
{
"name": "Smarty",
"bytes": "6108"
},
{
"name": "XSLT",
"bytes": "628"
}
],
"symlink_target": ""
}
|
#define LOG_TAG "AudioCache"
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#include "audio/win32/AudioCache.h"
#include <thread>
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "audio/win32/AudioDecoderManager.h"
#include "audio/win32/AudioDecoder.h"
#define VERY_VERY_VERBOSE_LOGGING
#ifdef VERY_VERY_VERBOSE_LOGGING
#define ALOGVV ALOGV
#else
#define ALOGVV(...) do{} while(false)
#endif
namespace {
unsigned int __idIndex = 0;
}
#define INVALID_AL_BUFFER_ID 0xFFFFFFFF
#define PCMDATA_CACHEMAXSIZE 1048576
using namespace cocos2d;
using namespace cocos2d::experimental;
AudioCache::AudioCache()
: _totalFrames(0)
, _framesRead(0)
, _format(-1)
, _duration(0.0f)
, _alBufferId(INVALID_AL_BUFFER_ID)
, _pcmData(nullptr)
, _queBufferFrames(0)
, _state(State::INITIAL)
, _isDestroyed(std::make_shared<bool>(false))
, _id(++__idIndex)
, _isLoadingFinished(false)
, _isSkipReadDataTask(false)
{
ALOGVV("AudioCache() %p, id=%u", this, _id);
for (int i = 0; i < QUEUEBUFFER_NUM; ++i)
{
_queBuffers[i] = nullptr;
_queBufferSize[i] = 0;
}
}
AudioCache::~AudioCache()
{
ALOGVV("~AudioCache() %p, id=%u, begin", this, _id);
*_isDestroyed = true;
while (!_isLoadingFinished)
{
if (_isSkipReadDataTask)
{
ALOGV("id=%u, Skip read data task, don't continue to wait!", _id);
break;
}
ALOGVV("id=%u, waiting readData thread to finish ...", _id);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
//wait for the 'readDataTask' task to exit
_readDataTaskMutex.lock();
_readDataTaskMutex.unlock();
if (_pcmData)
{
if (_state == State::READY)
{
if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId))
{
ALOGV("~AudioCache(id=%u), delete buffer: %u", _id, _alBufferId);
alDeleteBuffers(1, &_alBufferId);
_alBufferId = INVALID_AL_BUFFER_ID;
}
}
else
{
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state);
}
free(_pcmData);
}
if (_queBufferFrames > 0)
{
for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
{
free(_queBuffers[index]);
}
}
ALOGVV("~AudioCache() %p, id=%u, end", this, _id);
}
void AudioCache::readDataTask(unsigned int selfId)
{
//Note: It's in sub thread
ALOGVV("readDataTask begin, cache id=%u", selfId);
_readDataTaskMutex.lock();
_state = State::LOADING;
AudioDecoder* decoder = AudioDecoderManager::createDecoder(_fileFullPath.c_str());
do
{
if (decoder == nullptr || !decoder->open(_fileFullPath.c_str()))
break;
const uint32_t originalTotalFrames = decoder->getTotalFrames();
const uint32_t bytesPerFrame = decoder->getBytesPerFrame();
const uint32_t sampleRate = decoder->getSampleRate();
const uint32_t channelCount = decoder->getChannelCount();
uint32_t totalFrames = originalTotalFrames;
uint32_t dataSize = totalFrames * bytesPerFrame;
uint32_t remainingFrames = totalFrames;
uint32_t adjustFrames = 0;
_format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
_sampleRate = (ALsizei)sampleRate;
_duration = 1.0f * totalFrames / sampleRate;
_totalFrames = totalFrames;
if (dataSize <= PCMDATA_CACHEMAXSIZE)
{
uint32_t framesRead = 0;
const uint32_t framesToReadOnce = std::min(totalFrames, static_cast<uint32_t>(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM));
std::vector<char> adjustFrameBuf;
if (decoder->seek(totalFrames))
{
char* tmpBuf = (char*)malloc(framesToReadOnce * bytesPerFrame);
adjustFrameBuf.reserve(framesToReadOnce * bytesPerFrame);
// Adjust total frames by setting position to the end of frames and try to read more data.
// This is a workaround for https://github.com/cocos2d/cocos2d-x/issues/16938
do
{
framesRead = decoder->read(framesToReadOnce, tmpBuf);
if (framesRead > 0)
{
adjustFrames += framesRead;
adjustFrameBuf.insert(adjustFrameBuf.end(), tmpBuf, tmpBuf + framesRead * bytesPerFrame);
}
} while (framesRead > 0);
if (adjustFrames > 0)
{
ALOGV("Orignal total frames: %u, adjust frames: %u, current total frames: %u", totalFrames, adjustFrames, totalFrames + adjustFrames);
totalFrames += adjustFrames;
_totalFrames = remainingFrames = totalFrames;
}
// Reset dataSize
dataSize = totalFrames * bytesPerFrame;
free(tmpBuf);
}
// Reset to frame 0
BREAK_IF_ERR_LOG(!decoder->seek(0), "AudioDecoder::seek(0) failed!");
_pcmData = (char*)malloc(dataSize);
memset(_pcmData, 0x00, dataSize);
if (adjustFrames > 0)
{
memcpy(_pcmData + (dataSize - adjustFrameBuf.size()), adjustFrameBuf.data(), adjustFrameBuf.size());
}
alGenBuffers(1, &_alBufferId);
auto alError = alGetError();
if (alError != AL_NO_ERROR) {
ALOGE("%s: attaching audio to buffer fail: %x", __FUNCTION__, alError);
break;
}
if (*_isDestroyed)
break;
framesRead = decoder->readFixedFrames(std::min(framesToReadOnce, remainingFrames), _pcmData + _framesRead * bytesPerFrame);
_framesRead += framesRead;
remainingFrames -= framesRead;
if (*_isDestroyed)
break;
uint32_t frames = 0;
while (!*_isDestroyed && _framesRead < originalTotalFrames)
{
frames = std::min(framesToReadOnce, remainingFrames);
if (_framesRead + frames > originalTotalFrames)
{
frames = originalTotalFrames - _framesRead;
}
framesRead = decoder->read(frames, _pcmData + _framesRead * bytesPerFrame);
if (framesRead == 0)
break;
_framesRead += framesRead;
remainingFrames -= framesRead;
}
if (*_isDestroyed)
break;
if (_framesRead < originalTotalFrames)
{
memset(_pcmData + _framesRead * bytesPerFrame, 0x00, (totalFrames - _framesRead) * bytesPerFrame);
}
ALOGV("pcm buffer was loaded successfully, total frames: %u, total read frames: %u, adjust frames: %u, remainingFrames: %u", totalFrames, _framesRead, adjustFrames, remainingFrames);
_framesRead += adjustFrames;
alBufferData(_alBufferId, _format, _pcmData, (ALsizei)dataSize, (ALsizei)sampleRate);
_state = State::READY;
}
else
{
_queBufferFrames = sampleRate * QUEUEBUFFER_TIME_STEP;
BREAK_IF_ERR_LOG(_queBufferFrames == 0, "_queBufferFrames == 0");
const uint32_t queBufferBytes = _queBufferFrames * bytesPerFrame;
for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
{
_queBuffers[index] = (char*)malloc(queBufferBytes);
_queBufferSize[index] = queBufferBytes;
decoder->readFixedFrames(_queBufferFrames, _queBuffers[index]);
}
_state = State::READY;
}
} while (false);
if (decoder != nullptr)
{
decoder->close();
}
AudioDecoderManager::destroyDecoder(decoder);
if (_state != State::READY)
{
_state = State::FAILED;
if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId))
{
ALOGV("readDataTask failed, delete buffer: %u", _alBufferId);
alDeleteBuffers(1, &_alBufferId);
_alBufferId = INVALID_AL_BUFFER_ID;
}
}
//FIXME: Why to invoke play callback first? Should it be after 'load' callback?
invokingPlayCallbacks();
invokingLoadCallbacks();
_isLoadingFinished = true;
_readDataTaskMutex.unlock();
ALOGVV("readDataTask end, cache id=%u", selfId);
}
void AudioCache::addPlayCallback(const std::function<void()>& callback)
{
std::lock_guard<std::mutex> lk(_playCallbackMutex);
switch (_state)
{
case State::INITIAL:
case State::LOADING:
_playCallbacks.push_back(callback);
break;
case State::READY:
// If state is failure, we still need to invoke the callback
// since the callback will set the 'AudioPlayer::_removeByAudioEngine' flag to true.
case State::FAILED:
callback();
break;
default:
ALOGE("Invalid state: %d", _state);
break;
}
}
void AudioCache::invokingPlayCallbacks()
{
std::lock_guard<std::mutex> lk(_playCallbackMutex);
for (auto&& cb : _playCallbacks)
{
cb();
}
_playCallbacks.clear();
}
void AudioCache::addLoadCallback(const std::function<void(bool)>& callback)
{
switch (_state)
{
case State::INITIAL:
case State::LOADING:
_loadCallbacks.push_back(callback);
break;
case State::READY:
callback(true);
break;
case State::FAILED:
callback(false);
break;
default:
ALOGE("Invalid state: %d", _state);
break;
}
}
void AudioCache::invokingLoadCallbacks()
{
if (*_isDestroyed)
{
ALOGV("AudioCache (%p) was destroyed, don't invoke preload callback ...", this);
return;
}
auto isDestroyed = _isDestroyed;
auto scheduler = Director::getInstance()->getScheduler();
scheduler->performFunctionInCocosThread([&, isDestroyed](){
if (*isDestroyed)
{
ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this);
return;
}
for (auto&& cb : _loadCallbacks)
{
cb(_state == State::READY);
}
_loadCallbacks.clear();
});
}
#endif
|
{
"content_hash": "9694641366e868c41838bd48caffadc7",
"timestamp": "",
"source": "github",
"line_count": 357,
"max_line_length": 194,
"avg_line_length": 29.753501400560225,
"alnum_prop": 0.5648653737525889,
"repo_name": "literacyapp-org/nyas-space-quest",
"id": "30cfc529068557f177402ff90e11b46c24b34136",
"size": "11895",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "cocos2d/cocos/audio/win32/AudioCache.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "120"
},
{
"name": "C",
"bytes": "1346009"
},
{
"name": "C++",
"bytes": "14419498"
},
{
"name": "CMake",
"bytes": "248761"
},
{
"name": "GLSL",
"bytes": "63563"
},
{
"name": "Java",
"bytes": "362740"
},
{
"name": "JavaScript",
"bytes": "30728"
},
{
"name": "Lua",
"bytes": "15057"
},
{
"name": "Makefile",
"bytes": "55039"
},
{
"name": "Objective-C",
"bytes": "461485"
},
{
"name": "Objective-C++",
"bytes": "490428"
},
{
"name": "PLSQL",
"bytes": "83223"
},
{
"name": "Python",
"bytes": "55976"
},
{
"name": "Shell",
"bytes": "24596"
}
],
"symlink_target": ""
}
|
cask 'pdfsam-basic' do
version '4.0.3'
sha256 'c96d058f625fc181830adad47e901cb739a71c11a7dc82e759973753511f6212'
# github.com/torakiki/pdfsam was verified as official when first introduced to the cask
url "https://github.com/torakiki/pdfsam/releases/download/v#{version}/PDFsam-#{version}.dmg"
appcast 'https://github.com/torakiki/pdfsam/releases.atom'
name 'PDFsam Basic'
homepage 'https://www.pdfsam.org/'
pkg "PDFsam Basic-#{version}.pkg"
uninstall pkgutil: 'org.pdfsam.basic'
end
|
{
"content_hash": "5d73e09e1a76fb1e85c0fd8a8212e74c",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 94,
"avg_line_length": 36.07142857142857,
"alnum_prop": 0.7603960396039604,
"repo_name": "cblecker/homebrew-cask",
"id": "5a1d8703eeeb89f01ded162d0c8647d125015a63",
"size": "505",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Casks/pdfsam-basic.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "778"
},
{
"name": "HCL",
"bytes": "1658"
},
{
"name": "Python",
"bytes": "3532"
},
{
"name": "Ruby",
"bytes": "2073569"
},
{
"name": "Shell",
"bytes": "36113"
}
],
"symlink_target": ""
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Generator extends CI_Controller {
/**
* Generate forms
*/
// default page
public function index()
{
$this->load->view('generate');
}
}
|
{
"content_hash": "7b5dbf617fe7d37fa0b08a76c896ba01",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 63,
"avg_line_length": 14.125,
"alnum_prop": 0.6504424778761062,
"repo_name": "comp4711/example-forms",
"id": "542f59de2dad5f6efefd3aecfd4f3759b6ea2735",
"size": "226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/controllers/Generator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "485"
},
{
"name": "HTML",
"bytes": "1710"
},
{
"name": "PHP",
"bytes": "83176"
}
],
"symlink_target": ""
}
|
package org.drools.workbench.models.datamodel.oracle;
import java.util.Iterator;
import java.util.List;
public class MethodInfo {
private String name;
private List<String> params;
private String returnClassType;
private String parametricReturnType;
private String genericType;
public MethodInfo() {
}
/**
* @param name method name
* @param params method params list
* @param returnType method's return type
*/
public MethodInfo( final String name,
final List<String> params,
final Class<?> returnType,
final String parametricReturnType,
final String genericType ) {
this.name = name;
this.params = params;
this.returnClassType = returnType.getName();
this.parametricReturnType = parametricReturnType;
this.genericType = genericType;
}
/**
* @param name method name
* @param params method params list
* @param returnType method's return type
*/
public MethodInfo( final String name,
final List<String> params,
final String returnType,
final String parametricReturnType,
final String genericType ) {
this.name = name;
this.params = params;
this.returnClassType = returnType;
this.parametricReturnType = parametricReturnType;
this.genericType = genericType;
}
public String getNameWithParameters() {
if ( params.isEmpty() ) {
return name + "()";
}
StringBuilder p = new StringBuilder();
for ( Iterator<String> iterator = params.iterator(); iterator.hasNext(); ) {
p.append( ", " ).append( iterator.next() );
}
return name + "(" + p.substring( 2 ) + ")";
}
public String getName() {
return name;
}
public List<String> getParams() {
return params;
}
public String getReturnClassType() {
return returnClassType;
}
public String getParametricReturnType() {
return parametricReturnType;
}
public String getGenericType() {
return genericType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( name == null ) ? 0 : name.hashCode() );
result = ~~result;
result = prime
* result
+ ( ( parametricReturnType == null ) ? 0 : parametricReturnType
.hashCode() );
result = ~~result;
result = prime * result + ( ( params == null ) ? 0 : params.hashCode() );
result = ~~result;
result = prime * result
+ ( ( returnClassType == null ) ? 0 : returnClassType.hashCode() );
result = ~~result;
return result;
}
@Override
public boolean equals( Object obj ) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
MethodInfo other = (MethodInfo) obj;
if ( name == null ) {
if ( other.name != null ) {
return false;
}
} else if ( !name.equals( other.name ) ) {
return false;
}
if ( parametricReturnType == null ) {
if ( other.parametricReturnType != null ) {
return false;
}
} else if ( !parametricReturnType.equals( other.parametricReturnType ) ) {
return false;
}
if ( params == null ) {
if ( other.params != null ) {
return false;
}
} else if ( !params.equals( other.params ) ) {
return false;
}
if ( returnClassType == null ) {
if ( other.returnClassType != null ) {
return false;
}
} else if ( !returnClassType.equals( other.returnClassType ) ) {
return false;
}
return true;
}
@Override
public String toString() {
return getNameWithParameters();
}
}
|
{
"content_hash": "41ad0f76e59a68c60a98d7ad06d82eda",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 84,
"avg_line_length": 28.230263157894736,
"alnum_prop": 0.5241202516895829,
"repo_name": "rokn/Count_Words_2015",
"id": "84037b8505ccf74f2234e30001c475eb5e3c3688",
"size": "4912",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "testing/drools-master/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/MethodInfo.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "61802"
},
{
"name": "Ruby",
"bytes": "18888605"
}
],
"symlink_target": ""
}
|
FROM debian:jessie
# Install Git and basic packages.
RUN apt-get update && apt-get install -y \
autoconf \
autotools-dev \
build-essential \
bzip2 \
ccache \
curl \
dnsutils \
gcc \
gcc-multilib \
git \
golang \
gyp \
lcov \
libc6 \
libc6-dbg \
libc6-dev \
libgtest-dev \
libtool \
make \
perl \
strace \
python-dev \
python-setuptools \
python-yaml \
telnet \
unzip \
wget \
zip && apt-get clean
#================
# Build profiling
RUN apt-get update && apt-get install -y time && apt-get clean
# Google Cloud platform API libraries
RUN apt-get update && apt-get install -y python-pip && apt-get clean
RUN pip install --upgrade google-api-python-client
#====================
# Python dependencies
# Install dependencies
RUN apt-get update && apt-get install -y \
python-all-dev \
python3-all-dev \
python-pip
# Install Python packages from PyPI
RUN pip install --upgrade pip==10.0.1
RUN pip install virtualenv
RUN pip install futures==2.2.0 enum34==1.0.4 protobuf==3.5.2.post1 six==1.10.0 twisted==17.5.0
#=================
# C++ dependencies
RUN apt-get update && apt-get -y install libgflags-dev libgtest-dev libc++-dev clang && apt-get clean
#=================
# Use cmake 3.6 from jessie-backports
# should only be used for images based on debian jessie.
RUN echo "deb http://ftp.debian.org/debian jessie-backports main" | tee /etc/apt/sources.list.d/jessie-backports.list
RUN apt-get update && apt-get install -t jessie-backports -y cmake && apt-get clean
#=================
# Update clang to a version with improved tsan and fuzzing capabilities
RUN git clone -n -b release_38 http://llvm.org/git/llvm.git && \
cd llvm && git checkout ad57503 && cd ..
RUN git clone -n -b release_38 http://llvm.org/git/clang.git && \
cd clang && git checkout ad2c56e && cd ..
RUN git clone -n -b release_38 http://llvm.org/git/compiler-rt.git && \
cd compiler-rt && git checkout 3176922 && cd ..
RUN git clone -n -b release_38 \
http://llvm.org/git/clang-tools-extra.git && cd clang-tools-extra && \
git checkout c288525 && cd ..
RUN git clone -n -b release_38 http://llvm.org/git/libcxx.git && \
cd libcxx && git checkout fda3549 && cd ..
RUN git clone -n -b release_38 http://llvm.org/git/libcxxabi.git && \
cd libcxxabi && git checkout 8d4e51d && cd ..
RUN mv clang llvm/tools
RUN mv compiler-rt llvm/projects
RUN mv clang-tools-extra llvm/tools/clang/tools
RUN mv libcxx llvm/projects
RUN mv libcxxabi llvm/projects
RUN mkdir llvm-build
RUN cd llvm-build && cmake \
-DCMAKE_BUILD_TYPE:STRING=Release \
-DCMAKE_INSTALL_PREFIX:STRING=/usr \
-DLLVM_TARGETS_TO_BUILD:STRING=X86 \
../llvm
RUN make -C llvm-build -j 12 && make -C llvm-build install && rm -rf llvm-build
RUN mkdir /var/local/jenkins
RUN clang++ -c -g -O2 -std=c++11 llvm/lib/Fuzzer/*.cpp -IFuzzer
RUN ar ruv libFuzzer.a Fuzzer*.o
RUN mv libFuzzer.a /usr/lib
RUN rm -f Fuzzer*.o
# Define the default command.
CMD ["bash"]
|
{
"content_hash": "779b4141ab42e14aeef66273a1488dca",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 117,
"avg_line_length": 27.88785046728972,
"alnum_prop": 0.6702412868632708,
"repo_name": "ncteisen/grpc",
"id": "986cfcbada508e1d5477f33565f4d96e5caff0e1",
"size": "3562",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tools/dockerfile/test/fuzzer/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "31298"
},
{
"name": "C",
"bytes": "1463357"
},
{
"name": "C#",
"bytes": "1716417"
},
{
"name": "C++",
"bytes": "29660769"
},
{
"name": "CMake",
"bytes": "544571"
},
{
"name": "CSS",
"bytes": "1519"
},
{
"name": "DTrace",
"bytes": "147"
},
{
"name": "Dockerfile",
"bytes": "140067"
},
{
"name": "Go",
"bytes": "27069"
},
{
"name": "HTML",
"bytes": "14"
},
{
"name": "Java",
"bytes": "6907"
},
{
"name": "JavaScript",
"bytes": "51190"
},
{
"name": "M4",
"bytes": "45082"
},
{
"name": "Makefile",
"bytes": "1136766"
},
{
"name": "Objective-C",
"bytes": "282061"
},
{
"name": "Objective-C++",
"bytes": "37952"
},
{
"name": "PHP",
"bytes": "468767"
},
{
"name": "Python",
"bytes": "2354695"
},
{
"name": "Ruby",
"bytes": "762902"
},
{
"name": "Shell",
"bytes": "398538"
},
{
"name": "Swift",
"bytes": "3435"
},
{
"name": "XSLT",
"bytes": "9910"
}
],
"symlink_target": ""
}
|
* html .u0_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u0_normal.png");
}
* html .u2_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u2_normal.png");
}
* html .u4_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u4_normal.png");
}
* html .u7_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u7_normal.png");
}
* html .u9_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u9_normal.png");
}
* html .u11_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u11_normal.png");
}
* html .u13_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u13_normal.png");
}
* html .u15_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u13_normal.png");
}
* html .u17_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u17_normal.png");
}
* html .u19_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u19_normal.png");
}
* html .u24_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u24_normal.png");
}
* html .u26_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u13_normal.png");
}
* html .u29_normal {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="每日新增学员数_files/u19_normal.png");
}
|
{
"content_hash": "d8497d33d5e079d234688df0ffab2c7c",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 99,
"avg_line_length": 30.661538461538463,
"alnum_prop": 0.7255393878575013,
"repo_name": "tiansiyuan/SQA",
"id": "cdb365daafa9eb5f5a5b8fdf79cff4c93543e9b8",
"size": "2177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/dd/prototype/每日新增学员数_files/axurerp_pagespecificstyles_ie6.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "757181"
},
{
"name": "C++",
"bytes": "291245"
},
{
"name": "CSS",
"bytes": "2793343"
},
{
"name": "Objective-C",
"bytes": "2562"
},
{
"name": "Shell",
"bytes": "492"
},
{
"name": "Tcl",
"bytes": "225650"
}
],
"symlink_target": ""
}
|
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.append(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default'],
})
)
module.exports = environment
|
{
"content_hash": "5beca2c92f2106089619fe120f49aae6",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 51,
"avg_line_length": 22.384615384615383,
"alnum_prop": 0.6185567010309279,
"repo_name": "srct/schedules",
"id": "6b8aac7de844c2dd53192e4f52b72c066dcb776c",
"size": "291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "schedules/config/webpack/environment.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7641"
},
{
"name": "HTML",
"bytes": "29996"
},
{
"name": "JavaScript",
"bytes": "14626"
},
{
"name": "Ruby",
"bytes": "79536"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com" rel="preconnect" crossorigin="">
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono:400,500,700&display=fallback">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_collapsed" href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_collapsed.html" />
<link rel="prev" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.endog" href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.endog.html" />
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels 0.11.0</span>
<span class="md-header-nav__topic"> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.html" class="md-tabs__link">statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels 0.11.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-filter-augmented--page-root">statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented<a class="headerlink" href="#generated-statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-filter-augmented--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="attribute">
<dt id="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented">
<code class="sig-prename descclassname">SimulationSmoother.</code><code class="sig-name descname">filter_augmented</code><em class="property"> = False</em><a class="headerlink" href="#statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.endog.html" title="Material"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.endog </span>
</div>
</a>
<a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_collapsed.html" title="Admonition"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_collapsed </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Jan 22, 2020.
<br/>
Created using
<a href="http://sphinx-doc.org/">Sphinx</a> 2.3.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
{
"content_hash": "b2d92156d89d427e80f630f61a6264e1",
"timestamp": "",
"source": "github",
"line_count": 410,
"max_line_length": 999,
"avg_line_length": 43.990243902439026,
"alnum_prop": 0.6170436903969838,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "32e7a5032bd70e9b6ca1e77079f65c8c6f77d142",
"size": "18040",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.11.0/generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter_augmented.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
var AnalyticsController = require('analyticService/analyticService');
Alloy.Globals.analyticsController = new AnalyticsController();
var AdminModeController = require('adminModeService/AdminModeController');
Alloy.Globals.adminModeController = new AdminModeController();
var StorageService = require('storageService/storageService');
Alloy.Globals.storageService = new StorageService();
Alloy.Globals.isInDefaultWordpressEnviroment = function(){
return this.rootWebServiceUrl == Alloy.CFG.excl.wordpressEnvironments["prod"];
};
Alloy.Globals.setRootWebServiceFromUrls = function(key){
if( Alloy.CFG.excl.wordpressEnvironments[key] ){
Alloy.Globals.setRootWebServiceUrl(Alloy.CFG.excl.wordpressEnvironments[key]);
}
};
Alloy.Globals.setRootWebServiceUrl = function(url){
if( url ) {
Alloy.Globals.rootWebServiceUrl = url;
Alloy.Globals.storageService.setStringProperty("rootWebServiceURL", url);
}
};
if (Alloy.Globals.storageService.getStringProperty("rootWebServiceURL")) {
Alloy.Globals.setRootWebServiceUrl(Alloy.Globals.storageService.getStringProperty("rootWebServiceURL"));
} else {
Alloy.Globals.setRootWebServiceFromUrls("prod");
}
Alloy.Globals.setPathForLibDirectory = function(libFile){
if ( typeof Titanium == 'undefined') {
lib = require("../../lib/" + libFile);
} else {
lib = require(libFile);
}
return lib;
};
Alloy.Globals.isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
Alloy.Globals.isAlpha = function(ch){
return ch.search(/[^A-Za-z\s]/) == -1;
};
Alloy.Globals.rotate180 = Ti.UI.create2DMatrix().rotate(-180);
Alloy.Globals.rotate90 = Ti.UI.create2DMatrix().rotate(90);
Alloy.Globals.rotate270 = Ti.UI.create2DMatrix().rotate(270);
Alloy.Globals.rotate60 = Ti.UI.create2DMatrix().rotate(60);
Alloy.Globals.rotate130 = Ti.UI.create2DMatrix().rotate(130);
Alloy.Globals.rotate145 = Ti.UI.create2DMatrix().rotate(145);
Alloy.Globals.rotate245 = Ti.UI.create2DMatrix().rotate(245);
Alloy.Globals.rotate220 = Ti.UI.create2DMatrix().rotate(210);
// do not remove: initialization of global backbone models
Alloy.Models.app = Alloy.Models.instance('app');
Alloy.Models.app.on('change:currentLanguage', function() {
Alloy.Models.app.restart( function() {
var message = Alloy.Globals.museumJSON.data.museum.internationalization_message;
if (message != '') {
var dialogService = Alloy.Globals.setPathForLibDirectory('customCalls/dialogService');
dialogService = new dialogService();
alertDialog = dialogService.createAlertDialog(message);
alertDialog.buttonNames = ["Ok"];
alertDialog.show();
}
});
});
Alloy.Collections.filter = Alloy.Collections.instance('filter');
Alloy.Models.app.start();
|
{
"content_hash": "18876cc396c9467e006a9d0f23e29ab1",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 105,
"avg_line_length": 34.935064935064936,
"alnum_prop": 0.7594795539033458,
"repo_name": "lhs/excl-mobile",
"id": "eed7d5211e23328f787774933be031bfda9d891f",
"size": "3742",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/alloy.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1140"
},
{
"name": "JavaScript",
"bytes": "267116"
},
{
"name": "Python",
"bytes": "5251"
},
{
"name": "Shell",
"bytes": "177"
}
],
"symlink_target": ""
}
|
// Template Source: BaseMethodRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.ReportRoot;
import com.microsoft.graph.requests.ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCountsRequest;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.models.ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCountsParameterSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Report Root Get Skype For Business Peer To Peer Activity Minute Counts Request.
*/
public class ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCountsRequest extends BaseRequest<java.io.InputStream> {
/**
* The request for this ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCounts
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCountsRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, java.io.InputStream.class);
}
/**
* Gets the java.io.InputStream
*
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<java.io.InputStream> getAsync() {
return sendAsync(HttpMethod.GET, null);
}
/**
* Gets the java.io.InputStream
*
* @return the java.io.InputStream
* @throws ClientException an exception occurs if there was an error while the request was sent
*/
@Nullable
public java.io.InputStream get() throws ClientException {
return send(HttpMethod.GET, null);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCountsRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCountsRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
}
|
{
"content_hash": "895329a7c21716298275bf0c0de4ef32",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 244,
"avg_line_length": 38.2125,
"alnum_prop": 0.6954530585541381,
"repo_name": "microsoftgraph/msgraph-sdk-java",
"id": "c27395540b3379fbe90a329a5048d22538f33eca",
"size": "3057",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/main/java/com/microsoft/graph/requests/ReportRootGetSkypeForBusinessPeerToPeerActivityMinuteCountsRequest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27286837"
},
{
"name": "PowerShell",
"bytes": "5635"
}
],
"symlink_target": ""
}
|
package org.apache.camel.builder;
import java.util.Map;
import org.apache.camel.Expression;
import org.apache.camel.builder.xml.Namespaces;
import org.apache.camel.model.ExpressionNode;
import org.apache.camel.model.language.ExpressionDefinition;
/**
* Represents an expression clause within the DSL which when the expression is
* complete the clause continues to another part of the DSL
*
* @version
*/
public class ExpressionClause<T> extends ExpressionDefinition {
private ExpressionClauseSupport<T> delegate;
public ExpressionClause(T result) {
this.delegate = new ExpressionClauseSupport<T>(result);
}
public static <T extends ExpressionNode> ExpressionClause<T> createAndSetExpression(T result) {
ExpressionClause<T> clause = new ExpressionClause<T>(result);
result.setExpression(clause);
return clause;
}
// Helper expressions
// -------------------------------------------------------------------------
/**
* Specify an {@link Expression} instance
*/
public T expression(Expression expression) {
return delegate.expression(expression);
}
/**
* Specify the constant expression value
*/
public T constant(Object value) {
return delegate.constant(value);
}
/**
* An expression of the exchange
*/
public T exchange() {
return delegate.exchange();
}
/**
* An expression of an inbound message
*/
public T inMessage() {
return delegate.inMessage();
}
/**
* An expression of an inbound message
*/
public T outMessage() {
return delegate.outMessage();
}
/**
* An expression of an inbound message body
*/
public T body() {
return delegate.body();
}
/**
* An expression of an inbound message body converted to the expected type
*/
public T body(Class<?> expectedType) {
return delegate.body(expectedType);
}
/**
* An expression of an outbound message body
*/
public T outBody() {
return delegate.outBody();
}
/**
* An expression of an outbound message body converted to the expected type
*/
public T outBody(Class<?> expectedType) {
return delegate.outBody(expectedType);
}
/**
* An expression of an inbound message header of the given name
*/
public T header(String name) {
return delegate.header(name);
}
/**
* An expression of the inbound headers
*/
public T headers() {
return delegate.headers();
}
/**
* An expression of an outbound message header of the given name
*/
public T outHeader(String name) {
return delegate.outHeader(name);
}
/**
* An expression of the outbound headers
*/
public T outHeaders() {
return delegate.outHeaders();
}
/**
* An expression of the inbound message attachments
*/
public T attachments() {
return delegate.attachments();
}
/**
* An expression of an exchange property of the given name
*
* @deprecated use {@link #exchangeProperty(String)} instead
*/
@Deprecated
public T property(String name) {
return exchangeProperty(name);
}
/**
* An expression of an exchange property of the given name
*/
public T exchangeProperty(String name) {
return delegate.exchangeProperty(name);
}
/**
* An expression of the exchange properties
*/
public T properties() {
return delegate.properties();
}
// Languages
// -------------------------------------------------------------------------
/**
* Evaluates an expression using the <a
* href="http://camel.apache.org/bean-language.html">bean language</a>
* which basically means the bean is invoked to determine the expression
* value.
*
* @param bean the name of the bean looked up the registry
* @return the builder to continue processing the DSL
*/
public T method(String bean) {
return delegate.method(bean);
}
/**
* Evaluates an expression using the <a
* href="http://camel.apache.org/bean-language.html">bean language</a>
* which basically means the bean is invoked to determine the expression
* value.
*
* @param instance the instance of the bean
* @return the builder to continue processing the DSL
*/
public T method(Object instance) {
return delegate.method(instance);
}
/**
* Evaluates an expression using the <a
* href="http://camel.apache.org/bean-language.html">bean language</a>
* which basically means the bean is invoked to determine the expression
* value.
*
* @param beanType the Class of the bean which we want to invoke
* @return the builder to continue processing the DSL
*/
public T method(Class<?> beanType) {
return delegate.method(beanType);
}
/**
* Evaluates an expression using the <a
* href="http://camel.apache.org/bean-language.html">bean language</a>
* which basically means the bean is invoked to determine the expression
* value.
*
* @param bean the name of the bean looked up the registry
* @param method the name of the method to invoke on the bean
* @return the builder to continue processing the DSL
*/
public T method(String bean, String method) {
return delegate.method(bean, method);
}
/**
* Evaluates an expression using the <a
* href="http://camel.apache.org/bean-language.html">bean language</a>
* which basically means the bean is invoked to determine the expression
* value.
*
* @param instance the instance of the bean
* @param method the name of the method to invoke on the bean
* @return the builder to continue processing the DSL
*/
public T method(Object instance, String method) {
return delegate.method(instance, method);
}
/**
* Evaluates an expression using the <a
* href="http://camel.apache.org/bean-language.html">bean language</a>
* which basically means the bean is invoked to determine the expression
* value.
*
* @param beanType the Class of the bean which we want to invoke
* @param method the name of the method to invoke on the bean
* @return the builder to continue processing the DSL
*/
public T method(Class<?> beanType, String method) {
return delegate.method(beanType, method);
}
/**
* Evaluates the <a href="http://camel.apache.org/el.html">EL
* Language from JSP and JSF</a> using the <a
* href="http://camel.apache.org/juel.html">JUEL library</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T el(String text) {
return delegate.el(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/groovy.html">Groovy
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T groovy(String text) {
return delegate.groovy(text);
}
/**
* Evaluates a <a
* href="http://camel.apache.org/java-script.html">JavaScript
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T javaScript(String text) {
return delegate.javaScript(text);
}
/**
* Evaluates a <a
* href="http://camel.apache.org/jsonpath.html">Json Path
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T jsonpath(String text) {
return delegate.jsonpath(text);
}
/**
* Evaluates a <a
* href="http://camel.apache.org/jsonpath.html">Json Path
* expression</a>
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @return the builder to continue processing the DSL
*/
public T jsonpath(String text, Class<?> resultType) {
return delegate.jsonpath(text, resultType);
}
/**
* Evaluates a <a href="http://commons.apache.org/jxpath/">JXPath expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T jxpath(String text) {
return delegate.jxpath(text);
}
/**
* Evaluates a <a href="http://commons.apache.org/jxpath/">JXPath expression</a>
*
* @param text the expression to be evaluated
* @param lenient to configure whether lenient is in use or not
* @return the builder to continue processing the DSL
*/
public T jxpath(String text, boolean lenient) {
return delegate.jxpath(text, lenient);
}
/**
* Evaluates an <a href="http://camel.apache.org/ognl.html">OGNL
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T ognl(String text) {
return delegate.ognl(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/mvel.html">MVEL
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T mvel(String text) {
return delegate.mvel(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/php.html">PHP
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T php(String text) {
return delegate.php(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/python.html">Python
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T python(String text) {
return delegate.python(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/ref-language.html">Ref
* expression</a>
*
* @param ref refers to the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T ref(String ref) {
return delegate.ref(ref);
}
/**
* Evaluates a <a href="http://camel.apache.org/ruby.html">Ruby
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T ruby(String text) {
return delegate.ruby(text);
}
/**
* Evaluates an <a href="http://camel.apache.org/sql.html">SQL
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T sql(String text) {
return delegate.sql(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/spel.html">SpEL
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T spel(String text) {
return delegate.spel(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/simple.html">Simple
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T simple(String text) {
return delegate.simple(text);
}
/**
* Evaluates a <a href="http://camel.apache.org/simple.html">Simple
* expression</a>
*
* @param text the expression to be evaluated
* @param resultType the result type
* @return the builder to continue processing the DSL
*/
public T simple(String text, Class<?> resultType) {
return delegate.simple(text, resultType);
}
/**
* Evaluates a token expression on the message body
*
* @param token the token
* @return the builder to continue processing the DSL
*/
public T tokenize(String token) {
return delegate.tokenize(token);
}
/**
* Evaluates a token expression on the message body
*
* @param token the token
* @param regex whether the token is a regular expression or not
* @return the builder to continue processing the DSL
*/
public T tokenize(String token, boolean regex) {
return delegate.tokenize(token, regex);
}
/**
* Evaluates a token expression on the message body
*
* @param token the token
* @param regex whether the token is a regular expression or not
* @param group to group by the given number
* @return the builder to continue processing the DSL
*/
public T tokenize(String token, boolean regex, int group) {
return delegate.tokenize(token, regex);
}
/**
* Evaluates a token expression on the message body
*
* @param token the token
* @param group to group by the given number
* @return the builder to continue processing the DSL
*/
public T tokenize(String token, int group) {
return delegate.tokenize(token, group);
}
/**
* Evaluates a token expression on the given header
*
* @param token the token
* @param headerName name of header to tokenize
* @return the builder to continue processing the DSL
*/
public T tokenize(String token, String headerName) {
return delegate.tokenize(token, headerName);
}
/**
* Evaluates a token expression on the given header
*
* @param token the token
* @param headerName name of header to tokenize
* @param regex whether the token is a regular expression or not
* @return the builder to continue processing the DSL
*/
public T tokenize(String token, String headerName, boolean regex) {
return delegate.tokenize(token, headerName, regex);
}
/**
* Evaluates a token pair expression on the message body.
* <p/>
* Tokens is not included.
*
* @param startToken the start token
* @param endToken the end token
* @return the builder to continue processing the DSL
*/
public T tokenizePair(String startToken, String endToken) {
return tokenizePair(startToken, endToken, false);
}
/**
* Evaluates a token pair expression on the message body
*
* @param startToken the start token
* @param endToken the end token
* @param includeTokens whether to include tokens
* @return the builder to continue processing the DSL
*/
public T tokenizePair(String startToken, String endToken, boolean includeTokens) {
return delegate.tokenizePair(startToken, endToken, includeTokens);
}
/**
* Evaluates a XML token expression on the message body with XML content
*
* @param tagName the the tag name of the child nodes to tokenize
* @return the builder to continue processing the DSL
*/
public T tokenizeXML(String tagName) {
return tokenizeXML(tagName, null);
}
/**
* Evaluates a XML token expression on the message body with XML content
*
* @param tagName the the tag name of the child nodes to tokenize
* @param group to group by the given number
* @return the builder to continue processing the DSL
*/
public T tokenizeXML(String tagName, int group) {
return tokenizeXML(tagName, null, group);
}
/**
* Evaluates a token pair expression on the message body with XML content
*
* @param tagName the the tag name of the child nodes to tokenize
* @param inheritNamespaceTagName parent or root tag name that contains namespace(s) to inherit
* @return the builder to continue processing the DSL
*/
public T tokenizeXML(String tagName, String inheritNamespaceTagName) {
return tokenizeXML(tagName, inheritNamespaceTagName, 0);
}
/**
* Evaluates a token pair expression on the message body with XML content
*
* @param tagName the the tag name of the child nodes to tokenize
* @param inheritNamespaceTagName parent or root tag name that contains namespace(s) to inherit
* @param group to group by the given number
* @return the builder to continue processing the DSL
*/
public T tokenizeXML(String tagName, String inheritNamespaceTagName, int group) {
return delegate.tokenizeXMLPair(tagName, inheritNamespaceTagName, group);
}
public T xtokenize(String path, Namespaces namespaces) {
return xtokenize(path, 'i', namespaces);
}
public T xtokenize(String path, char mode, Namespaces namespaces) {
return xtokenize(path, mode, namespaces, 0);
}
public T xtokenize(String path, char mode, Namespaces namespaces, int group) {
return delegate.xtokenize(path, mode, namespaces, group);
}
/**
* Evaluates an <a href="http://camel.apache.org/vtdxml.html">XPath
* expression using the VTD-XML library</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T vtdxml(String text) {
return delegate.vtdxml(text);
}
/**
* Evaluates an <a href="http://camel.apache.org/vtdxml.html">XPath
* expression using the VTD-XML library</a>
* with the specified set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T vtdxml(String text, Namespaces namespaces) {
return delegate.vtdxml(text, namespaces);
}
/**
* Evaluates an <a href="http://camel.apache.org/vtdxml.html">XPath
* expression using the VTD-XML library</a>
* with the specified set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T vtdxml(String text, Map<String, String> namespaces) {
return delegate.vtdxml(text, namespaces);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T xpath(String text) {
return delegate.xpath(text);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> on the supplied header name's contents
*
* @param text the expression to be evaluated
* @param headerName the name of the header to apply the expression to
* @return the builder to continue processing the DSL
*/
public T xpath(String text, String headerName) {
return delegate.xpath(text, headerName);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> with the specified result type
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @return the builder to continue processing the DSL
*/
public T xpath(String text, Class<?> resultType) {
return delegate.xpath(text, resultType);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> with the specified result type on the supplied
* header name's contents
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param headerName the name of the header to apply the expression to
* @return the builder to continue processing the DSL
*/
public T xpath(String text, Class<?> resultType, String headerName) {
return delegate.xpath(text, resultType, headerName);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> with the specified result type and set of namespace
* prefixes and URIs
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xpath(String text, Class<?> resultType, Namespaces namespaces) {
return delegate.xpath(text, resultType, namespaces);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> with the specified result type and set of namespace
* prefixes and URIs on the supplied header name's contents
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param headerName the name of the header to apply the expression to
* @param namespaces the namespace prefix and URIs to use
*
* @return the builder to continue processing the DSL
*/
public T xpath(String text, Class<?> resultType, Namespaces namespaces, String headerName) {
return delegate.xpath(text, resultType, namespaces, headerName);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> with the specified result type and set of namespace
* prefixes and URIs
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xpath(String text, Class<?> resultType, Map<String, String> namespaces) {
return delegate.xpath(text, resultType, namespaces);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> with the specified set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xpath(String text, Namespaces namespaces) {
return delegate.xpath(text, namespaces);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> with the specified set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xpath(String text, Map<String, String> namespaces) {
return delegate.xpath(text, namespaces);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
*
* @param text the expression to be evaluated
* @return the builder to continue processing the DSL
*/
public T xquery(String text) {
return delegate.xquery(text);
}
/**
* Evaluates an <a href="http://camel.apache.org/xpath.html">XPath
* expression</a> on the supplied header name's contents
*
* @param text the expression to be evaluated
* @param headerName the name of the header to apply the expression to
* @return the builder to continue processing the DSL
*/
public T xquery(String text, String headerName) {
return delegate.xquery(text, headerName);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
* with the specified result type
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @return the builder to continue processing the DSL
*/
public T xquery(String text, Class<?> resultType) {
return delegate.xquery(text, resultType);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
* with the specified result type
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param headerName the name of the header to apply the expression to
* @return the builder to continue processing the DSL
*/
public T xquery(String text, Class<?> resultType, String headerName) {
return delegate.xquery(text, resultType, headerName);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
* with the specified result type and set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xquery(String text, Class<?> resultType, Namespaces namespaces) {
return delegate.xquery(text, resultType, namespaces);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
* with the specified result type
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param headerName the name of the header to apply the expression to
* @param namespaces the namespace prefix and URIs to use
*
* @return the builder to continue processing the DSL
*/
public T xquery(String text, Class<?> resultType, Namespaces namespaces, String headerName) {
return delegate.xquery(text, resultType, namespaces, headerName);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
* with the specified result type and set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param resultType the return type expected by the expression
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xquery(String text, Class<?> resultType, Map<String, String> namespaces) {
return delegate.xquery(text, resultType, namespaces);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
* with the specified set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xquery(String text, Namespaces namespaces) {
return delegate.xquery(text, namespaces);
}
/**
* Evaluates an <a
* href="http://camel.apache.org/xquery.html">XQuery expression</a>
* with the specified set of namespace prefixes and URIs
*
* @param text the expression to be evaluated
* @param namespaces the namespace prefix and URIs to use
* @return the builder to continue processing the DSL
*/
public T xquery(String text, Map<String, String> namespaces) {
return delegate.xquery(text, namespaces);
}
/**
* Evaluates a given language name with the expression text
*
* @param language the name of the language
* @param expression the expression in the given language
* @return the builder to continue processing the DSL
*/
public T language(String language, String expression) {
return delegate.language(language, expression);
}
// Properties
// -------------------------------------------------------------------------
@Override
public Expression getExpressionValue() {
return delegate.getExpressionValue();
}
@Override
protected void setExpressionValue(Expression expressionValue) {
delegate.setExpressionValue(expressionValue);
}
@Override
public ExpressionDefinition getExpressionType() {
return delegate.getExpressionType();
}
@Override
protected void setExpressionType(ExpressionDefinition expressionType) {
delegate.setExpressionType(expressionType);
}
}
|
{
"content_hash": "d28b804b34de9cc8388cb95f64fac28f",
"timestamp": "",
"source": "github",
"line_count": 887,
"max_line_length": 100,
"avg_line_length": 32.36076662908681,
"alnum_prop": 0.6388308249721293,
"repo_name": "ramonmaruko/camel",
"id": "2fc59bc36eca1417b87028e6ecb41f483c2cf98f",
"size": "29507",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "camel-core/src/main/java/org/apache/camel/builder/ExpressionClause.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18641"
},
{
"name": "Eagle",
"bytes": "2898"
},
{
"name": "Elm",
"bytes": "5970"
},
{
"name": "Groovy",
"bytes": "23444"
},
{
"name": "HTML",
"bytes": "191526"
},
{
"name": "Java",
"bytes": "44730910"
},
{
"name": "JavaScript",
"bytes": "88124"
},
{
"name": "Protocol Buffer",
"bytes": "578"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "13262"
},
{
"name": "Scala",
"bytes": "303651"
},
{
"name": "Shell",
"bytes": "12930"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "XQuery",
"bytes": "1483"
},
{
"name": "XSLT",
"bytes": "284036"
}
],
"symlink_target": ""
}
|
import utils
import sys
import sortClass
class InsertionSort(sortClass.SortClass):
@staticmethod
def findSlot(myList, value, max):
for i in range(max):
if (value < myList[i]):
return i
return max-1
@staticmethod
def basicSort(myList):
# If the length is one or zero
# Nothing more to do.
# List is already sorted.
size = len(myList)
if size <= 1:
return myList;
for i in range(1,size):
if (myList[i].compareKeys(myList[i-1]) < 0):
value = myList.pop(i)
slot = InsertionSort.findSlot(myList, value, i)
myList.insert(slot, value)
return myList
#end
if __name__ == "__main__":
sys.setrecursionlimit(10000)
sizes = [5, 100]
for size in sizes:
myList = utils.createInputArray(size)
print myList
InsertionSort.basicSort(myList)
print myList
|
{
"content_hash": "0c1156c01db81c660502cab36b2f86d0",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 51,
"avg_line_length": 21.026315789473685,
"alnum_prop": 0.6795994993742178,
"repo_name": "bhagatyj/algorithms",
"id": "1c4bb4446a5d7975051bf48b0d599b0bc6f51ac0",
"size": "819",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sorting/python/insertionSort.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "268434"
},
{
"name": "C++",
"bytes": "168902"
},
{
"name": "Makefile",
"bytes": "5400"
},
{
"name": "Python",
"bytes": "50556"
},
{
"name": "Shell",
"bytes": "1193"
}
],
"symlink_target": ""
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.operator.scalar;
import com.google.common.collect.ImmutableList;
import io.prestosql.metadata.Metadata;
import io.prestosql.operator.DriverYieldSignal;
import io.prestosql.operator.project.PageProcessor;
import io.prestosql.spi.Page;
import io.prestosql.spi.PageBuilder;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.BlockBuilder;
import io.prestosql.spi.type.ArrayType;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.gen.ExpressionCompiler;
import io.prestosql.sql.gen.PageFunctionCompiler;
import io.prestosql.sql.relational.CallExpression;
import io.prestosql.sql.relational.ConstantExpression;
import io.prestosql.sql.relational.InputReferenceExpression;
import io.prestosql.sql.relational.LambdaDefinitionExpression;
import io.prestosql.sql.relational.RowExpression;
import io.prestosql.sql.relational.VariableReferenceExpression;
import io.prestosql.sql.tree.QualifiedName;
import io.prestosql.type.FunctionType;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.google.common.base.Verify.verify;
import static io.prestosql.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext;
import static io.prestosql.metadata.MetadataManager.createTestMetadataManager;
import static io.prestosql.spi.function.OperatorType.GREATER_THAN;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.sql.analyzer.TypeSignatureProvider.fromTypes;
import static io.prestosql.testing.TestingConnectorSession.SESSION;
@SuppressWarnings("MethodMayBeStatic")
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(2)
@Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkArrayTransform
{
private static final int POSITIONS = 100_000;
private static final int ARRAY_SIZE = 4;
private static final int NUM_TYPES = 1;
private static final List<Type> TYPES = ImmutableList.of(BIGINT);
static {
verify(NUM_TYPES == TYPES.size());
}
@Benchmark
@OperationsPerInvocation(POSITIONS * ARRAY_SIZE * NUM_TYPES)
public Object benchmark(BenchmarkData data)
{
return ImmutableList.copyOf(
data.getPageProcessor().process(
SESSION,
new DriverYieldSignal(),
newSimpleAggregatedMemoryContext().newLocalMemoryContext(PageProcessor.class.getSimpleName()),
data.getPage()));
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BenchmarkData
{
private PageBuilder pageBuilder;
private Page page;
private PageProcessor pageProcessor;
@Setup
public void setup()
{
Metadata metadata = createTestMetadataManager();
ExpressionCompiler compiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0));
ImmutableList.Builder<RowExpression> projectionsBuilder = ImmutableList.builder();
Block[] blocks = new Block[TYPES.size()];
for (int i = 0; i < TYPES.size(); i++) {
Type elementType = TYPES.get(i);
ArrayType arrayType = new ArrayType(elementType);
projectionsBuilder.add(new CallExpression(
metadata.resolveFunction(
QualifiedName.of("transform"),
fromTypes(arrayType, new FunctionType(ImmutableList.of(BIGINT), BOOLEAN))),
ImmutableList.of(
new InputReferenceExpression(0, arrayType),
new LambdaDefinitionExpression(
ImmutableList.of(BIGINT),
ImmutableList.of("x"),
new CallExpression(
metadata.resolveOperator(GREATER_THAN, ImmutableList.of(BIGINT, BIGINT)),
ImmutableList.of(new VariableReferenceExpression("x", BIGINT), new ConstantExpression(0L, BIGINT)))))));
blocks[i] = createChannel(POSITIONS, ARRAY_SIZE, arrayType);
}
ImmutableList<RowExpression> projections = projectionsBuilder.build();
pageProcessor = compiler.compilePageProcessor(Optional.empty(), projections).get();
pageBuilder = new PageBuilder(projections.stream().map(RowExpression::getType).collect(Collectors.toList()));
page = new Page(blocks);
}
private static Block createChannel(int positionCount, int arraySize, ArrayType arrayType)
{
BlockBuilder blockBuilder = arrayType.createBlockBuilder(null, positionCount);
for (int position = 0; position < positionCount; position++) {
BlockBuilder entryBuilder = blockBuilder.beginBlockEntry();
for (int i = 0; i < arraySize; i++) {
if (arrayType.getElementType().getJavaType() == long.class) {
arrayType.getElementType().writeLong(entryBuilder, ThreadLocalRandom.current().nextLong());
}
else {
throw new UnsupportedOperationException();
}
}
blockBuilder.closeEntry();
}
return blockBuilder.build();
}
public PageProcessor getPageProcessor()
{
return pageProcessor;
}
public Page getPage()
{
return page;
}
public PageBuilder getPageBuilder()
{
return pageBuilder;
}
}
public static void main(String[] args)
throws Exception
{
// assure the benchmarks are valid before running
BenchmarkData data = new BenchmarkData();
data.setup();
new BenchmarkArrayTransform().benchmark(data);
Options options = new OptionsBuilder()
.verbosity(VerboseMode.NORMAL)
.include(".*" + BenchmarkArrayTransform.class.getSimpleName() + ".*")
.build();
new Runner(options).run();
}
}
|
{
"content_hash": "766311238a0bb8ad919452de11c32e16",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 152,
"avg_line_length": 42.52717391304348,
"alnum_prop": 0.6702875399361022,
"repo_name": "martint/presto",
"id": "143d49a07ecceb411d8633909fca94bfa3b23a22",
"size": "7825",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "presto-main/src/test/java/io/prestosql/operator/scalar/BenchmarkArrayTransform.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "30339"
},
{
"name": "CSS",
"bytes": "17830"
},
{
"name": "Dockerfile",
"bytes": "1419"
},
{
"name": "Groovy",
"bytes": "1547"
},
{
"name": "HTML",
"bytes": "24210"
},
{
"name": "Java",
"bytes": "41450945"
},
{
"name": "JavaScript",
"bytes": "219907"
},
{
"name": "PLSQL",
"bytes": "2990"
},
{
"name": "Python",
"bytes": "9304"
},
{
"name": "SQLPL",
"bytes": "926"
},
{
"name": "Shell",
"bytes": "42170"
},
{
"name": "TSQL",
"bytes": "169681"
},
{
"name": "Thrift",
"bytes": "12598"
}
],
"symlink_target": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.