text
stringlengths
2
1.04M
meta
dict
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v2.model; /** * The response message for a webhook call. This response is validated by the Dialogflow server. If * validation fails, an error will be returned in the QueryResult.diagnostic_info field. Setting * JSON fields to an empty value with the wrong type is a common error. To avoid this error: - Use * `""` for empty strings - Use `{}` or `null` for empty objects - Use `[]` or `null` for empty * arrays For more information, see the [Protocol Buffers Language * Guide](https://developers.google.com/protocol-buffers/docs/proto3#json). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowV2beta1WebhookResponse extends com.google.api.client.json.GenericJson { /** * Optional. Indicates that this intent ends an interaction. Some integrations (e.g., Actions on * Google or Dialogflow phone gateway) use this information to close interaction with an end user. * Default is false. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean endInteraction; /** * Optional. Invokes the supplied events. When this field is set, Dialogflow ignores the * `fulfillment_text`, `fulfillment_messages`, and `payload` fields. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2beta1EventInput followupEventInput; /** * Optional. The rich response messages intended for the end-user. When provided, Dialogflow uses * this field to populate QueryResult.fulfillment_messages sent to the integration or API caller. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDialogflowV2beta1IntentMessage> fulfillmentMessages; static { // hack to force ProGuard to consider GoogleCloudDialogflowV2beta1IntentMessage used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowV2beta1IntentMessage.class); } /** * Optional. The text response message intended for the end-user. It is recommended to use * `fulfillment_messages.text.text[0]` instead. When provided, Dialogflow uses this field to * populate QueryResult.fulfillment_text sent to the integration or API caller. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fulfillmentText; /** * Indicates that a live agent should be brought in to handle the interaction with the user. In * most cases, when you set this flag to true, you would also want to set end_interaction to true * as well. Default is false. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean liveAgentHandoff; /** * Optional. The collection of output contexts that will overwrite currently active contexts for * the session and reset their lifespans. When provided, Dialogflow uses this field to populate * QueryResult.output_contexts sent to the integration or API caller. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDialogflowV2beta1Context> outputContexts; static { // hack to force ProGuard to consider GoogleCloudDialogflowV2beta1Context used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowV2beta1Context.class); } /** * Optional. This field can be used to pass custom data from your webhook to the integration or * API caller. Arbitrary JSON objects are supported. When provided, Dialogflow uses this field to * populate QueryResult.webhook_payload sent to the integration or API caller. This field is also * used by the [Google Assistant * integration](https://cloud.google.com/dialogflow/docs/integrations/aog) for rich response * messages. See the format definition at [Google Assistant Dialogflow webhook * format](https://developers.google.com/assistant/actions/build/json/dialogflow-webhook-json) * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.Object> payload; /** * Optional. Additional session entity types to replace or extend developer entity types with. The * entity synonyms apply to all languages and persist for the session. Setting this data from a * webhook overwrites the session entity types that have been set using `detectIntent`, * `streamingDetectIntent` or SessionEntityType management methods. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDialogflowV2beta1SessionEntityType> sessionEntityTypes; static { // hack to force ProGuard to consider GoogleCloudDialogflowV2beta1SessionEntityType used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowV2beta1SessionEntityType.class); } /** * Optional. A custom field used to identify the webhook source. Arbitrary strings are supported. * When provided, Dialogflow uses this field to populate QueryResult.webhook_source sent to the * integration or API caller. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String source; /** * Optional. Indicates that this intent ends an interaction. Some integrations (e.g., Actions on * Google or Dialogflow phone gateway) use this information to close interaction with an end user. * Default is false. * @return value or {@code null} for none */ public java.lang.Boolean getEndInteraction() { return endInteraction; } /** * Optional. Indicates that this intent ends an interaction. Some integrations (e.g., Actions on * Google or Dialogflow phone gateway) use this information to close interaction with an end user. * Default is false. * @param endInteraction endInteraction or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setEndInteraction(java.lang.Boolean endInteraction) { this.endInteraction = endInteraction; return this; } /** * Optional. Invokes the supplied events. When this field is set, Dialogflow ignores the * `fulfillment_text`, `fulfillment_messages`, and `payload` fields. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2beta1EventInput getFollowupEventInput() { return followupEventInput; } /** * Optional. Invokes the supplied events. When this field is set, Dialogflow ignores the * `fulfillment_text`, `fulfillment_messages`, and `payload` fields. * @param followupEventInput followupEventInput or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setFollowupEventInput(GoogleCloudDialogflowV2beta1EventInput followupEventInput) { this.followupEventInput = followupEventInput; return this; } /** * Optional. The rich response messages intended for the end-user. When provided, Dialogflow uses * this field to populate QueryResult.fulfillment_messages sent to the integration or API caller. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDialogflowV2beta1IntentMessage> getFulfillmentMessages() { return fulfillmentMessages; } /** * Optional. The rich response messages intended for the end-user. When provided, Dialogflow uses * this field to populate QueryResult.fulfillment_messages sent to the integration or API caller. * @param fulfillmentMessages fulfillmentMessages or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setFulfillmentMessages(java.util.List<GoogleCloudDialogflowV2beta1IntentMessage> fulfillmentMessages) { this.fulfillmentMessages = fulfillmentMessages; return this; } /** * Optional. The text response message intended for the end-user. It is recommended to use * `fulfillment_messages.text.text[0]` instead. When provided, Dialogflow uses this field to * populate QueryResult.fulfillment_text sent to the integration or API caller. * @return value or {@code null} for none */ public java.lang.String getFulfillmentText() { return fulfillmentText; } /** * Optional. The text response message intended for the end-user. It is recommended to use * `fulfillment_messages.text.text[0]` instead. When provided, Dialogflow uses this field to * populate QueryResult.fulfillment_text sent to the integration or API caller. * @param fulfillmentText fulfillmentText or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setFulfillmentText(java.lang.String fulfillmentText) { this.fulfillmentText = fulfillmentText; return this; } /** * Indicates that a live agent should be brought in to handle the interaction with the user. In * most cases, when you set this flag to true, you would also want to set end_interaction to true * as well. Default is false. * @return value or {@code null} for none */ public java.lang.Boolean getLiveAgentHandoff() { return liveAgentHandoff; } /** * Indicates that a live agent should be brought in to handle the interaction with the user. In * most cases, when you set this flag to true, you would also want to set end_interaction to true * as well. Default is false. * @param liveAgentHandoff liveAgentHandoff or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setLiveAgentHandoff(java.lang.Boolean liveAgentHandoff) { this.liveAgentHandoff = liveAgentHandoff; return this; } /** * Optional. The collection of output contexts that will overwrite currently active contexts for * the session and reset their lifespans. When provided, Dialogflow uses this field to populate * QueryResult.output_contexts sent to the integration or API caller. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDialogflowV2beta1Context> getOutputContexts() { return outputContexts; } /** * Optional. The collection of output contexts that will overwrite currently active contexts for * the session and reset their lifespans. When provided, Dialogflow uses this field to populate * QueryResult.output_contexts sent to the integration or API caller. * @param outputContexts outputContexts or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setOutputContexts(java.util.List<GoogleCloudDialogflowV2beta1Context> outputContexts) { this.outputContexts = outputContexts; return this; } /** * Optional. This field can be used to pass custom data from your webhook to the integration or * API caller. Arbitrary JSON objects are supported. When provided, Dialogflow uses this field to * populate QueryResult.webhook_payload sent to the integration or API caller. This field is also * used by the [Google Assistant * integration](https://cloud.google.com/dialogflow/docs/integrations/aog) for rich response * messages. See the format definition at [Google Assistant Dialogflow webhook * format](https://developers.google.com/assistant/actions/build/json/dialogflow-webhook-json) * @return value or {@code null} for none */ public java.util.Map<String, java.lang.Object> getPayload() { return payload; } /** * Optional. This field can be used to pass custom data from your webhook to the integration or * API caller. Arbitrary JSON objects are supported. When provided, Dialogflow uses this field to * populate QueryResult.webhook_payload sent to the integration or API caller. This field is also * used by the [Google Assistant * integration](https://cloud.google.com/dialogflow/docs/integrations/aog) for rich response * messages. See the format definition at [Google Assistant Dialogflow webhook * format](https://developers.google.com/assistant/actions/build/json/dialogflow-webhook-json) * @param payload payload or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setPayload(java.util.Map<String, java.lang.Object> payload) { this.payload = payload; return this; } /** * Optional. Additional session entity types to replace or extend developer entity types with. The * entity synonyms apply to all languages and persist for the session. Setting this data from a * webhook overwrites the session entity types that have been set using `detectIntent`, * `streamingDetectIntent` or SessionEntityType management methods. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDialogflowV2beta1SessionEntityType> getSessionEntityTypes() { return sessionEntityTypes; } /** * Optional. Additional session entity types to replace or extend developer entity types with. The * entity synonyms apply to all languages and persist for the session. Setting this data from a * webhook overwrites the session entity types that have been set using `detectIntent`, * `streamingDetectIntent` or SessionEntityType management methods. * @param sessionEntityTypes sessionEntityTypes or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setSessionEntityTypes(java.util.List<GoogleCloudDialogflowV2beta1SessionEntityType> sessionEntityTypes) { this.sessionEntityTypes = sessionEntityTypes; return this; } /** * Optional. A custom field used to identify the webhook source. Arbitrary strings are supported. * When provided, Dialogflow uses this field to populate QueryResult.webhook_source sent to the * integration or API caller. * @return value or {@code null} for none */ public java.lang.String getSource() { return source; } /** * Optional. A custom field used to identify the webhook source. Arbitrary strings are supported. * When provided, Dialogflow uses this field to populate QueryResult.webhook_source sent to the * integration or API caller. * @param source source or {@code null} for none */ public GoogleCloudDialogflowV2beta1WebhookResponse setSource(java.lang.String source) { this.source = source; return this; } @Override public GoogleCloudDialogflowV2beta1WebhookResponse set(String fieldName, Object value) { return (GoogleCloudDialogflowV2beta1WebhookResponse) super.set(fieldName, value); } @Override public GoogleCloudDialogflowV2beta1WebhookResponse clone() { return (GoogleCloudDialogflowV2beta1WebhookResponse) super.clone(); } }
{ "content_hash": "c17465b6b301ebf47157ab46a6cb53cb", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 182, "avg_line_length": 46.14244186046512, "alnum_prop": 0.752031752031752, "repo_name": "googleapis/google-api-java-client-services", "id": "ee9d3ef41f341e0670ac0371acbfc9ebcc12d1cf", "size": "15873", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "clients/google-api-services-dialogflow/v2/2.0.0/com/google/api/services/dialogflow/v2/model/GoogleCloudDialogflowV2beta1WebhookResponse.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.nifi.controller.scheduling; import org.apache.nifi.components.state.StateManager; import org.apache.nifi.components.state.StateManagerProvider; import org.apache.nifi.connectable.Connectable; import org.apache.nifi.controller.repository.ContentRepository; import org.apache.nifi.controller.repository.CounterRepository; import org.apache.nifi.controller.repository.FlowFileEventRepository; import org.apache.nifi.controller.repository.FlowFileRepository; import org.apache.nifi.controller.repository.RepositoryContext; import org.apache.nifi.controller.repository.StandardRepositoryContext; import org.apache.nifi.provenance.ProvenanceRepository; import java.util.concurrent.atomic.AtomicLong; public class RepositoryContextFactory { private final ContentRepository contentRepo; private final FlowFileRepository flowFileRepo; private final FlowFileEventRepository flowFileEventRepo; private final CounterRepository counterRepo; private final ProvenanceRepository provenanceRepo; private final StateManagerProvider stateManagerProvider; public RepositoryContextFactory(final ContentRepository contentRepository, final FlowFileRepository flowFileRepository, final FlowFileEventRepository flowFileEventRepository, final CounterRepository counterRepository, final ProvenanceRepository provenanceRepository, final StateManagerProvider stateManagerProvider) { this.contentRepo = contentRepository; this.flowFileRepo = flowFileRepository; this.flowFileEventRepo = flowFileEventRepository; this.counterRepo = counterRepository; this.provenanceRepo = provenanceRepository; this.stateManagerProvider = stateManagerProvider; } public RepositoryContext newProcessContext(final Connectable connectable, final AtomicLong connectionIndex) { final StateManager stateManager = stateManagerProvider.getStateManager(connectable.getIdentifier()); return new StandardRepositoryContext(connectable, connectionIndex, contentRepo, flowFileRepo, flowFileEventRepo, counterRepo, provenanceRepo, stateManager); } public ContentRepository getContentRepository() { return contentRepo; } public FlowFileRepository getFlowFileRepository() { return flowFileRepo; } public ProvenanceRepository getProvenanceRepository() { return provenanceRepo; } }
{ "content_hash": "9524f9718293f8c2c6152d8c52e4d0da", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 164, "avg_line_length": 44.851851851851855, "alnum_prop": 0.8075970272502064, "repo_name": "jfrazee/nifi", "id": "45540f997d9a8053513d42ebaf9c757baba2737d", "size": "3223", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/RepositoryContextFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "44090" }, { "name": "C++", "bytes": "652" }, { "name": "CSS", "bytes": "286195" }, { "name": "Clojure", "bytes": "3993" }, { "name": "Dockerfile", "bytes": "24505" }, { "name": "GAP", "bytes": "31169" }, { "name": "Groovy", "bytes": "2205715" }, { "name": "HTML", "bytes": "1120188" }, { "name": "Handlebars", "bytes": "38564" }, { "name": "Java", "bytes": "54569943" }, { "name": "JavaScript", "bytes": "4035982" }, { "name": "Lua", "bytes": "983" }, { "name": "Mustache", "bytes": "2438" }, { "name": "Python", "bytes": "26583" }, { "name": "Ruby", "bytes": "23018" }, { "name": "SCSS", "bytes": "22032" }, { "name": "Shell", "bytes": "166750" }, { "name": "TypeScript", "bytes": "1337" }, { "name": "XSLT", "bytes": "7835" } ], "symlink_target": "" }
package br.ufrj.cos.minisiga.config; import io.github.jhipster.config.JHipsterProperties; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.spi.ContextAwareBase; import net.logstash.logback.appender.LogstashSocketAppender; import net.logstash.logback.stacktrace.ShortenedThrowableConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class LoggingConfiguration { private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class); private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); private final String appName; private final String serverPort; private final JHipsterProperties jHipsterProperties; public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, JHipsterProperties jHipsterProperties) { this.appName = appName; this.serverPort = serverPort; this.jHipsterProperties = jHipsterProperties; if (jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashAppender(context); // Add context listener LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener(); loggerContextListener.setContext(context); context.addListener(loggerContextListener); } } public void addLogstashAppender(LoggerContext context) { log.info("Initializing Logstash logging"); LogstashSocketAppender logstashAppender = new LogstashSocketAppender(); logstashAppender.setName("LOGSTASH"); logstashAppender.setContext(context); String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"}"; // Set the Logstash appender config from JHipster properties logstashAppender.setSyslogHost(jHipsterProperties.getLogging().getLogstash().getHost()); logstashAppender.setPort(jHipsterProperties.getLogging().getLogstash().getPort()); logstashAppender.setCustomFields(customFields); // Limit the maximum length of the forwarded stacktrace so that it won't exceed the 8KB UDP limit of logstash ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setMaxLength(7500); throwableConverter.setRootCauseFirst(true); logstashAppender.setThrowableConverter(throwableConverter); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName("ASYNC_LOGSTASH"); asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger("ROOT").addAppender(asyncLogstashAppender); } /** * Logback configuration is achieved by configuration file and API. * When configuration file change is detected, the configuration is reset. * This listener ensures that the programmatic configuration is also re-applied after reset. */ class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener { @Override public boolean isResetResistant() { return true; } @Override public void onStart(LoggerContext context) { addLogstashAppender(context); } @Override public void onReset(LoggerContext context) { addLogstashAppender(context); } @Override public void onStop(LoggerContext context) { // Nothing to do. } @Override public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) { // Nothing to do. } } }
{ "content_hash": "2fd379f12a2239a2d46217d6769cddbd", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 128, "avg_line_length": 38.99090909090909, "alnum_prop": 0.7190487293075309, "repo_name": "Hguimaraes/mini-siga", "id": "6485c4fbf9810f085a62f2e832b8e79e8cad90b3", "size": "4289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/br/ufrj/cos/minisiga/config/LoggingConfiguration.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9286" }, { "name": "HTML", "bytes": "188139" }, { "name": "Java", "bytes": "450828" }, { "name": "JavaScript", "bytes": "17397" }, { "name": "TypeScript", "bytes": "315989" } ], "symlink_target": "" }
package com.xebia.akka.jigsaw import akka.actor.{ActorRef, Props, Actor} object EventProcessor { def props(journal: Journal) = Props(classOf[EventProcessor], journal) } class EventProcessor(journal: Journal) extends Actor { override def receive: Receive = { case eventWrapper: EventWrapper => val event = EventWrapper.unwrap(eventWrapper) event match { case e: UserJoined => onUserJoined(sender()) case _=> } journal.log(event) publish(eventWrapper) } private def onUserJoined(worker: ActorRef) { println(s"start replaying ${journal.eventLog.size} events to $worker") journal.eventLog.foreach(e => worker ! "replay" -> EventWrapper.wrap(e)) println(s"subsribe $worker") subscribe(worker) } private def publish(eventWrapper: EventWrapper) { val topic = "all" context.system.eventStream.publish(topic, eventWrapper) println(s"published to topic $topic: $eventWrapper") } private def subscribe(worker: ActorRef) { context.system.eventStream.subscribe(worker, classOf[(String, EventWrapper)]) } }
{ "content_hash": "33a8edf6c7bc898c17ebe32034445acc", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 81, "avg_line_length": 28.94736842105263, "alnum_prop": 0.6981818181818182, "repo_name": "xebia/akka-jigsaw", "id": "68d1b5ffbb031ba6af9dad9a6845fae925c3b853", "size": "1100", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/src/main/scala/com/xebia/akka/jigsaw/EventProcessor.scala", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package engine import ( "github.com/cockroachdb/cockroach/proto" "github.com/cockroachdb/cockroach/util/log" gogoproto "github.com/gogo/protobuf/proto" ) // GarbageCollector GCs MVCC key/values using a zone-specific GC // policy allows either the union or intersection of maximum # of // versions and maximum age. type GarbageCollector struct { expiration proto.Timestamp policy proto.GCPolicy } // NewGarbageCollector allocates and returns a new GC, with expiration // computed based on current time and policy.TTLSeconds. func NewGarbageCollector(now proto.Timestamp, policy proto.GCPolicy) *GarbageCollector { ttlNanos := int64(policy.TTLSeconds) * 1E9 return &GarbageCollector{ expiration: proto.Timestamp{WallTime: now.WallTime - ttlNanos}, policy: policy, } } // Filter makes decisions about garbage collection based on the // garbage collection policy for batches of values for the same key. // Returns the timestamp including, and after which, all values should // be garbage collected. If no values should be GC'd, returns // proto.ZeroTimestamp. func (gc *GarbageCollector) Filter(keys []proto.EncodedKey, values [][]byte) proto.Timestamp { if gc.policy.TTLSeconds <= 0 { return proto.ZeroTimestamp } if len(keys) == 0 { return proto.ZeroTimestamp } // Loop over values. All should be MVCC versions. delTS := proto.ZeroTimestamp survivors := false for i, key := range keys { _, ts, isValue := MVCCDecodeKey(key) if !isValue { log.Errorf("unexpected MVCC metadata encountered: %q", key) return proto.ZeroTimestamp } mvccVal := MVCCValue{} if err := gogoproto.Unmarshal(values[i], &mvccVal); err != nil { log.Errorf("unable to unmarshal MVCC value %q: %v", key, err) return proto.ZeroTimestamp } if i == 0 { // If the first value isn't a deletion tombstone, don't consider // it for GC. It should always survive if non-deleted. if !mvccVal.Deleted { survivors = true continue } } // If we encounter a version older than our GC timestamp, mark for deletion. if ts.Less(gc.expiration) { delTS = ts break } else if !mvccVal.Deleted { survivors = true } } // If there are no non-deleted survivors, return timestamp of first key // to delete all entries. if !survivors { _, ts, _ := MVCCDecodeKey(keys[0]) return ts } return delTS }
{ "content_hash": "02587d2478bcfcc9e7a6b3e562b07a74", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 94, "avg_line_length": 30.493506493506494, "alnum_prop": 0.7180579216354344, "repo_name": "chrisseto/cockroach", "id": "08c941c84445a58ef16ad7821824c7ba8f19b83a", "size": "3057", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "storage/engine/gc.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "6523" }, { "name": "C++", "bytes": "45143" }, { "name": "CSS", "bytes": "4443" }, { "name": "Go", "bytes": "2790566" }, { "name": "HTML", "bytes": "3051" }, { "name": "Makefile", "bytes": "12316" }, { "name": "Protocol Buffer", "bytes": "97049" }, { "name": "Shell", "bytes": "21359" }, { "name": "TypeScript", "bytes": "92512" }, { "name": "Yacc", "bytes": "92777" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { public function index() { $this->load->view('home'); } }
{ "content_hash": "7dac74bc7b591bec57f899e88e72db96", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 63, "avg_line_length": 19, "alnum_prop": 0.6842105263157895, "repo_name": "diantama86/CI_Lelang", "id": "8bccaef8f6ccac2a346247c936e8101620034c63", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/Welcome.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "675" }, { "name": "CSS", "bytes": "420763" }, { "name": "HTML", "bytes": "93476" }, { "name": "JavaScript", "bytes": "715231" }, { "name": "PHP", "bytes": "1842788" } ], "symlink_target": "" }
a#cdo-introLink img { background-image : url(graphics/cdo.gif); } a#cdo-introLink:hover img { background-image : url(graphics/cdo_hov.gif); }
{ "content_hash": "08c4fce1a9a010623b5c93cc4f8c4f8d", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 75, "avg_line_length": 70.5, "alnum_prop": 0.7375886524822695, "repo_name": "kribe48/wasp-mbse", "id": "e348642a27f9613c1d9ca9b46770ea9c89ef7e48", "size": "142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WASP-turtlebot-DSL/.metadata/.plugins/org.eclipse.pde.core/Eclipse Application/org.eclipse.osgi/142/0/.cp/intro/css/cdo.css", "mode": "33188", "license": "mit", "language": [ { "name": "CMake", "bytes": "6732" }, { "name": "CSS", "bytes": "179891" }, { "name": "GAP", "bytes": "163745" }, { "name": "HTML", "bytes": "1197667" }, { "name": "Java", "bytes": "1369191" }, { "name": "JavaScript", "bytes": "1555" }, { "name": "Python", "bytes": "11033" }, { "name": "Roff", "bytes": "303" }, { "name": "Xtend", "bytes": "13981" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers\Frontend; class ApplicationDocumentsController extends Controller { public function index(){ return view('frontend.applicationdocuments'); } }
{ "content_hash": "8f1a506eafa22a2b8008cef3f0beb34e", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 55, "avg_line_length": 18.09090909090909, "alnum_prop": 0.7386934673366834, "repo_name": "mlechler/Bewerbungscoaching", "id": "5a387f672eb16492d2ebccf76566294efe45afbb", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Http/Controllers/Frontend/ApplicationDocumentsController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "HTML", "bytes": "307589" }, { "name": "JavaScript", "bytes": "65745" }, { "name": "PHP", "bytes": "486504" }, { "name": "Vue", "bytes": "561" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../spec_helper.rb' describe "ActiveCouch::Base #before_delete method with a Symbol as argument" do before(:each) do class Person < ActiveCouch::Base site 'http://localhost:5984/' has :name has :age, :which_is => :number # Callback, before the actual save happens before_delete :zero_age private def zero_age self.age = 0 end end # Migration needed for this spec ActiveCouch::Migrator.create_database('http://localhost:5984/', 'people') end after(:each) do # Migration needed for this spec ActiveCouch::Migrator.delete_database('http://localhost:5984/', 'people') Object.send(:remove_const, :Person) end it "should have a class method called before_save" do Person.methods.include?('before_delete').should == true end it "should call the method specified as an argument to before_delete, *before* deleting the object from CouchDB" do # First save the object p = Person.create(:name => 'McLovin', :age => 10) # Before deleting, age must be 10 p.age.should == 10 # Delete the object, and... p.delete.should == true # ...age must equal 0 p.age.should == 0 end end describe "ActiveCouch::Base #before_save method with a block as argument" do before(:each) do class Person < ActiveCouch::Base site 'http://localhost:5984/' has :name has :age, :which_is => :number # Callback, before the actual save happens before_delete { |record| record.age = 0 } end # Migration needed for this spec ActiveCouch::Migrator.create_database('http://localhost:5984/', 'people') end after(:each) do # Migration needed for this spec ActiveCouch::Migrator.delete_database('http://localhost:5984/', 'people') Object.send(:remove_const, :Person) end it "should execute the block as a param to before_save" do # First save the object p = Person.create(:name => 'McLovin', :age => 10) # Before deleting, age must be 10 p.age.should == 10 # Delete the object, and... p.delete.should == true # ...age must equal 0 p.age.should == 0 end end describe "ActiveCouch::Base #before_save method with an Object (which implements before_save) as argument" do before(:each) do class AgeSetter def before_delete(record) record.age = 0 end end class Person < ActiveCouch::Base site 'http://localhost:5984/' has :name has :age, :which_is => :number # Callback, before the actual save happens before_delete AgeSetter.new end # Migration needed for this spec ActiveCouch::Migrator.create_database('http://localhost:5984/', 'people') end after(:each) do # Migration needed for this spec ActiveCouch::Migrator.delete_database('http://localhost:5984/', 'people') Object.send(:remove_const, :Person) end it "should call before_save in the object passed as a param to before_delete" do # First save the object p = Person.create(:name => 'McLovin', :age => 10) # Before deleting, age must be 10 p.age.should == 10 # Delete the object, and... p.delete.should == true # ...age must equal 0 p.age.should == 0 end end
{ "content_hash": "196518b6b8c4f151dba8cea5df316c9c", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 117, "avg_line_length": 30.477064220183486, "alnum_prop": 0.6384708007224563, "repo_name": "google-code/activecouch", "id": "4f4df7051b6b0bccc28280429ac8fed5c7720297", "size": "3322", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/base/before_delete_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "121479" } ], "symlink_target": "" }
.class public Lo/l; .super Ljava/lang/Object; # interfaces .implements Landroid/os/Parcelable$Creator; # annotations .annotation system Ldalvik/annotation/Signature; value = { "Ljava/lang/Object;Landroid/os/Parcelable$Creator<Lcom/google/android/gms/fitness/request/y;>;" } .end annotation # direct methods .method public constructor <init>()V .locals 0 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method .method public static ˊ(Lcom/google/android/gms/fitness/request/y;Landroid/os/Parcel;I)V .locals 4 invoke-static {p1}, Lo/ż;->ˊ(Landroid/os/Parcel;)I move-result v3 invoke-virtual {p0}, Lcom/google/android/gms/fitness/request/y;->ˊ()Ljava/lang/String; move-result-object v0 const/4 v1, 0x1 const/4 v2, 0x0 invoke-static {p1, v1, v0, v2}, Lo/ż;->ˊ(Landroid/os/Parcel;ILjava/lang/String;Z)V invoke-virtual {p0}, Lcom/google/android/gms/fitness/request/y;->ˎ()I move-result v0 const/16 v1, 0x3e8 invoke-static {p1, v1, v0}, Lo/ż;->ˊ(Landroid/os/Parcel;II)V invoke-virtual {p0}, Lcom/google/android/gms/fitness/request/y;->ˋ()Ljava/lang/String; move-result-object v0 const/4 v1, 0x2 const/4 v2, 0x0 invoke-static {p1, v1, v0, v2}, Lo/ż;->ˊ(Landroid/os/Parcel;ILjava/lang/String;Z)V invoke-static {p1, v3}, Lo/ż;->ˊ(Landroid/os/Parcel;I)V return-void .end method # virtual methods .method public synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object; .locals 1 invoke-virtual {p0, p1}, Lo/l;->ˊ(Landroid/os/Parcel;)Lcom/google/android/gms/fitness/request/y; move-result-object v0 return-object v0 .end method .method public synthetic newArray(I)[Ljava/lang/Object; .locals 1 invoke-virtual {p0, p1}, Lo/l;->ˊ(I)[Lcom/google/android/gms/fitness/request/y; move-result-object v0 return-object v0 .end method .method public ˊ(Landroid/os/Parcel;)Lcom/google/android/gms/fitness/request/y; .locals 8 invoke-static {p1}, Lo/Ŷ;->ˋ(Landroid/os/Parcel;)I move-result v3 const/4 v4, 0x0 const/4 v5, 0x0 const/4 v6, 0x0 :goto_0 invoke-virtual {p1}, Landroid/os/Parcel;->dataPosition()I move-result v0 if-ge v0, v3, :cond_0 invoke-static {p1}, Lo/Ŷ;->ˊ(Landroid/os/Parcel;)I move-result v7 invoke-static {v7}, Lo/Ŷ;->ˊ(I)I move-result v0 sparse-switch v0, :sswitch_data_0 goto :goto_1 :sswitch_0 invoke-static {p1, v7}, Lo/Ŷ;->ˌ(Landroid/os/Parcel;I)Ljava/lang/String; move-result-object v5 goto :goto_2 :sswitch_1 invoke-static {p1, v7}, Lo/Ŷ;->ʼ(Landroid/os/Parcel;I)I move-result v4 goto :goto_2 :sswitch_2 invoke-static {p1, v7}, Lo/Ŷ;->ˌ(Landroid/os/Parcel;I)Ljava/lang/String; move-result-object v6 goto :goto_2 :goto_1 invoke-static {p1, v7}, Lo/Ŷ;->ˋ(Landroid/os/Parcel;I)V :goto_2 goto :goto_0 :cond_0 invoke-virtual {p1}, Landroid/os/Parcel;->dataPosition()I move-result v0 if-eq v0, v3, :cond_1 new-instance v0, Lo/Ŷ$if; new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string v2, "Overread allowed size end=" invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, v3}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-direct {v0, v1, p1}, Lo/Ŷ$if;-><init>(Ljava/lang/String;Landroid/os/Parcel;)V throw v0 :cond_1 new-instance v7, Lcom/google/android/gms/fitness/request/y; invoke-direct {v7, v4, v5, v6}, Lcom/google/android/gms/fitness/request/y;-><init>(ILjava/lang/String;Ljava/lang/String;)V return-object v7 nop :sswitch_data_0 .sparse-switch 0x1 -> :sswitch_0 0x2 -> :sswitch_2 0x3e8 -> :sswitch_1 .end sparse-switch .end method .method public ˊ(I)[Lcom/google/android/gms/fitness/request/y; .locals 1 new-array v0, p1, [Lcom/google/android/gms/fitness/request/y; return-object v0 .end method
{ "content_hash": "2b70cb5c8d0926c4eed7e3f772bd0e7b", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 126, "avg_line_length": 21.515, "alnum_prop": 0.6627933999535208, "repo_name": "gelldur/jak_oni_to_robia_prezentacja", "id": "726ff6b2c6870cf58deee0616ef4954f811480c9", "size": "4337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Starbucks/output/smali/o/l.smali", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "8427" }, { "name": "Shell", "bytes": "2303" }, { "name": "Smali", "bytes": "57557982" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Revis. gen. pl. (Leipzig) 3: 472 (1898) #### Original name Engizostoma ellisii Kuntze ### Remarks null
{ "content_hash": "3fc6fba48b98aee13d1ed45e21a7c753", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 12.76923076923077, "alnum_prop": 0.6927710843373494, "repo_name": "mdoering/backbone", "id": "01c99909402c621a43058cd88500527f6fdabfd2", "size": "216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Valsaceae/Engizostoma/Engizostoma ellisii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package mktdata import ( "bytes" "fmt" "os" "testing" ) func TestPreallocated(t *testing.T) { in := &MDIncrementalRefreshBook32{ TransactTime: 1, NoMDEntries: []MDIncrementalRefreshBook32NoMDEntries{ { MDEntryPx: PRICENULL{}, MDEntrySize: 5, SecurityID: 1, }, { MDEntryPx: PRICENULL{}, MDEntrySize: 6, SecurityID: 1, }, }, } min := NewSbeGoMarshaller() buf := &bytes.Buffer{} if err := in.Encode(min, buf, true); err != nil { fmt.Println("Encoding Error", err) os.Exit(1) } out := &MDIncrementalRefreshBook32{} if err := out.Decode(min, buf, in.SbeSchemaVersion(), in.SbeBlockLength(), true); err != nil { fmt.Println("Decoding Error", err) os.Exit(1) } if len(out.NoMDEntries) != len(in.NoMDEntries) { fmt.Printf("expected %d entries, got %d\n", len(in.NoMDEntries), len(out.NoMDEntries)) os.Exit(1) } // decode a message with fewer entries on top of existing message in = &MDIncrementalRefreshBook32{ TransactTime: 1, NoMDEntries: []MDIncrementalRefreshBook32NoMDEntries{ { MDEntryPx: PRICENULL{}, MDEntrySize: 5, SecurityID: 1, }, }, } buf.Reset() if err := in.Encode(min, buf, true); err != nil { fmt.Println("Encoding Error", err) os.Exit(1) } if err := out.Decode(min, buf, in.SbeSchemaVersion(), in.SbeBlockLength(), true); err != nil { fmt.Println("Decoding Error", err) os.Exit(1) } if len(out.NoMDEntries) != len(in.NoMDEntries) { fmt.Printf("expected %d entries, got %d\n", len(in.NoMDEntries), len(out.NoMDEntries)) os.Exit(1) } }
{ "content_hash": "c8d3186ce9e16575e357aae256bb9b99", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 95, "avg_line_length": 22.797101449275363, "alnum_prop": 0.6478067387158296, "repo_name": "real-logic/simple-binary-encoding", "id": "962db2c4a5161ca4b4e41b256176f7371c796ed0", "size": "1573", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gocode/src/mktdata/preallocated_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1909" }, { "name": "C", "bytes": "876" }, { "name": "C#", "bytes": "205453" }, { "name": "C++", "bytes": "364206" }, { "name": "CMake", "bytes": "17861" }, { "name": "Go", "bytes": "86466" }, { "name": "Java", "bytes": "1554845" }, { "name": "Makefile", "bytes": "2580" }, { "name": "Rust", "bytes": "39476" }, { "name": "Shell", "bytes": "3745" } ], "symlink_target": "" }
Thiner Server ============ Todas as informações sobre o servidor podem ser encontradas no nosso [Wiki](https://github.com/Thiner-LES/thiner-server/wiki).
{ "content_hash": "05b6f7c55a76ffc8b24aec4e171b8eaa", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 126, "avg_line_length": 26.166666666666668, "alnum_prop": 0.7197452229299363, "repo_name": "UFCGProjects/thiner-server", "id": "684b8e020d9f70fa67d930bdc92a756aa1c8817a", "size": "159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "110" }, { "name": "JavaScript", "bytes": "17090" } ], "symlink_target": "" }
package com.evolveum.midpoint.model.common; import org.apache.commons.configuration.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration; /** * @author semancik * */ @Component public class ConstantsManager { @Autowired private MidpointConfiguration midpointConfiguration; private Configuration constConfig; public ConstantsManager() { } /** * For testing. */ public ConstantsManager(Configuration config) { this.constConfig = config; } private Configuration getConstConfig() { if (constConfig == null) { constConfig = midpointConfiguration.getConfiguration(MidpointConfiguration.CONSTANTS_CONFIGURATION); } return constConfig; } public String getConstantValue(String constName) { String val = getConstConfig().getString(constName); return val; } }
{ "content_hash": "5fb1d554c9ffc986124b96b039e50ccc", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 112, "avg_line_length": 23.431818181818183, "alnum_prop": 0.7138700290979632, "repo_name": "bshp/midPoint", "id": "8afc05f93de3a60b82fbed4dce3d77c4b712ee91", "size": "1216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "model/model-common/src/main/java/com/evolveum/midpoint/model/common/ConstantsManager.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
The Helm project accepts contributions via GitHub pull requests. This document outlines the process to help get your contribution accepted. ## Reporting a Security Issue Most of the time, when you find a bug in Helm, it should be reported using [GitHub issues](https://github.com/helm/helm/issues). However, if you are reporting a _security vulnerability_, please email a report to [cncf-helm-security@lists.cncf.io](mailto:cncf-helm-security@lists.cncf.io). This will give us a chance to try to fix the issue before it is exploited in the wild. ## Sign Your Work The sign-off is a simple line at the end of the explanation for a commit. All commits needs to be signed. Your signature certifies that you wrote the patch or otherwise have the right to contribute the material. The rules are pretty simple, if you can certify the below (from [developercertificate.org](https://developercertificate.org/)): ``` Developer Certificate of Origin Version 1.1 Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 1 Letterman Drive Suite D4700 San Francisco, CA, 94129 Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` Then you just add a line to every git commit message: Signed-off-by: Joe Smith <joe.smith@example.com> Use your real name (sorry, no pseudonyms or anonymous contributions.) If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. Note: If your git config information is set properly then viewing the `git log` information for your commit will look something like this: ``` Author: Joe Smith <joe.smith@example.com> Date: Thu Feb 2 11:41:15 2018 -0800 Update README Signed-off-by: Joe Smith <joe.smith@example.com> ``` Notice the `Author` and `Signed-off-by` lines match. If they don't your PR will be rejected by the automated DCO check. ## Support Channels Whether you are a user or contributor, official support channels include: - [Issues](https://github.com/helm/helm/issues) - Slack: - User: [#helm-users](https://kubernetes.slack.com/messages/C0NH30761/details/) - Contributor: [#helm-dev](https://kubernetes.slack.com/messages/C51E88VDG/) Before opening a new issue or submitting a new pull request, it's helpful to search the project - it's likely that another user has already reported the issue you're facing, or it's a known issue that we're already aware of. It is also worth asking on the Slack channels. ## Milestones We use milestones to track progress of specific planned releases. For example, if the latest currently-released version is `3.2.1`, an issue/PR which pertains to a specific upcoming bugfix or feature release could fall into one of two different active milestones: `3.2.2` or `3.3.0`. Issues and PRs which are deemed backwards-incompatible may be added to the discussion items for Helm 4 with [label:v4.x](https://github.com/helm/helm/labels/v4.x). An issue or PR that we are not sure we will be addressing will not be added to any milestone. A milestone (and hence release) can be closed when all outstanding issues/PRs have been closed or moved to another milestone and the associated release has been published. ## Semantic Versioning Helm maintains a strong commitment to backward compatibility. All of our changes to protocols and formats are backward compatible from one major release to the next. No features, flags, or commands are removed or substantially modified (unless we need to fix a security issue). We also try very hard to not change publicly accessible Go library definitions inside of the `pkg/` directory of our source code. For a quick summary of our backward compatibility guidelines for releases between 3.0 and 4.0: - Command line commands, flags, and arguments MUST be backward compatible - File formats (such as Chart.yaml) MUST be backward compatible - Any chart that worked on a previous version of Helm 3 MUST work on a new version of Helm 3 (barring the cases where (a) Kubernetes itself changed, and (b) the chart worked because it exploited a bug) - Chart repository functionality MUST be backward compatible - Go libraries inside of `pkg/` SHOULD remain backward compatible, though code inside of `cmd/` and `internal/` may be changed from release to release without notice. ## Support Contract for Helm 2 With Helm 2's current release schedule, we want to take into account any migration issues for users due to the upcoming holiday shopping season and tax season. We also want to clarify what actions may occur after the support contract ends for Helm 2, so that users will not be surprised or caught off guard. After Helm 2.15.0 is released, Helm 2 will go into "maintenance mode". We will continue to accept bug fixes and fix any security issues that arise, but no new features will be accepted for Helm 2. All feature development will be moved over to Helm 3. 6 months after Helm 3.0.0's public release, Helm 2 will stop accepting bug fixes. Only security issues will be accepted. 12 months after Helm 3.0.0's public release, support for Helm 2 will formally end. Download links for the Helm 2 client through Google Cloud Storage, the Docker image for Tiller stored in Google Container Registry, and the Google Cloud buckets for the stable and incubator chart repositories may no longer work at any point. Client downloads through `get.helm.sh` will continue to work, and we will distribute a Tiller image that will be made available at an alternative location which can be updated with `helm init --tiller-image`. ## Issues Issues are used as the primary method for tracking anything to do with the Helm project. ### Issue Types There are 5 types of issues (each with their own corresponding [label](#labels)): - `question/support`: These are support or functionality inquiries that we want to have a record of for future reference. Generally these are questions that are too complex or large to store in the Slack channel or have particular interest to the community as a whole. Depending on the discussion, these can turn into `feature` or `bug` issues. - `proposal`: Used for items (like this one) that propose a new ideas or functionality that require a larger community discussion. This allows for feedback from others in the community before a feature is actually developed. This is not needed for small additions. Final word on whether or not a feature needs a proposal is up to the core maintainers. All issues that are proposals should both have a label and an issue title of "Proposal: [the rest of the title]." A proposal can become a `feature` and does not require a milestone. - `feature`: These track specific feature requests and ideas until they are complete. They can evolve from a `proposal` or can be submitted individually depending on the size. - `bug`: These track bugs with the code - `docs`: These track problems with the documentation (i.e. missing or incomplete) ### Issue Lifecycle The issue lifecycle is mainly driven by the core maintainers, but is good information for those contributing to Helm. All issue types follow the same general lifecycle. Differences are noted below. 1. Issue creation 2. Triage - The maintainer in charge of triaging will apply the proper labels for the issue. This includes labels for priority, type, and metadata (such as `good first issue`). The only issue priority we will be tracking is whether or not the issue is "critical." If additional levels are needed in the future, we will add them. - (If needed) Clean up the title to succinctly and clearly state the issue. Also ensure that proposals are prefaced with "Proposal: [the rest of the title]". - Add the issue to the correct milestone. If any questions come up, don't worry about adding the issue to a milestone until the questions are answered. - We attempt to do this process at least once per work day. 3. Discussion - Issues that are labeled `feature` or `proposal` must write a Helm Improvement Proposal (HIP). See [Proposing an Idea](#proposing-an-idea). Smaller quality-of-life enhancements are exempt. - Issues that are labeled as `feature` or `bug` should be connected to the PR that resolves it. - Whoever is working on a `feature` or `bug` issue (whether a maintainer or someone from the community), should either assign the issue to themself or make a comment in the issue saying that they are taking it. - `proposal` and `support/question` issues should stay open until resolved or if they have not been active for more than 30 days. This will help keep the issue queue to a manageable size and reduce noise. Should the issue need to stay open, the `keep open` label can be added. 4. Issue closure ## Proposing an Idea Before proposing a new idea to the Helm project, please make sure to write up a [Helm Improvement Proposal](https://github.com/helm/community/tree/master/hips). A Helm Improvement Proposal is a design document that describes a new feature for the Helm project. The proposal should provide a concise technical specification and rationale for the feature. It is also worth considering vetting your idea with the community via the [cncf-helm](mailto:cncf-helm@lists.cncf.io) mailing list. Vetting an idea publicly before going as far as writing a proposal is meant to save the potential author time. Many ideas have been proposed; it's quite likely there are others in the community who may be working on a similar proposal, or a similar proposal may have already been written. HIPs are submitted to the [helm/community repository](https://github.com/helm/community). [HIP 1](https://github.com/helm/community/blob/master/hips/hip-0001.md) describes the process to write a HIP as well as the review process. After your proposal has been approved, follow the [developer's guide](https://helm.sh/docs/community/developers/) to get started. ## How to Contribute a Patch 1. Identify or create the related issue. If you're proposing a larger change to Helm, see [Proposing an Idea](#proposing-an-idea). 2. Fork the desired repo; develop and test your code changes. 3. Submit a pull request, making sure to sign your work and link the related issue. Coding conventions and standards are explained in the [official developer docs](https://helm.sh/docs/developers/). ## Pull Requests Like any good open source project, we use Pull Requests (PRs) to track code changes. ### PR Lifecycle 1. PR creation - PRs are usually created to fix or else be a subset of other PRs that fix a particular issue. - We more than welcome PRs that are currently in progress. They are a great way to keep track of important work that is in-flight, but useful for others to see. If a PR is a work in progress, it **must** be prefaced with "WIP: [title]". Once the PR is ready for review, remove "WIP" from the title. - It is preferred, but not required, to have a PR tied to a specific issue. There can be circumstances where if it is a quick fix then an issue might be overkill. The details provided in the PR description would suffice in this case. 2. Triage - The maintainer in charge of triaging will apply the proper labels for the issue. This should include at least a size label, `bug` or `feature`, and `awaiting review` once all labels are applied. See the [Labels section](#labels) for full details on the definitions of labels. - Add the PR to the correct milestone. This should be the same as the issue the PR closes. 3. Assigning reviews - Once a review has the `awaiting review` label, maintainers will review them as schedule permits. The maintainer who takes the issue should self-request a review. - PRs from a community member with the label `size/S` or larger requires 2 review approvals from maintainers before it can be merged. Those with `size/XS` are per the judgement of the maintainers. For more detail see the [Size Labels](#size-labels) section. 4. Reviewing/Discussion - All reviews will be completed using GitHub review tool. - A "Comment" review should be used when there are questions about the code that should be answered, but that don't involve code changes. This type of review does not count as approval. - A "Changes Requested" review indicates that changes to the code need to be made before they will be merged. - Reviewers should update labels as needed (such as `needs rebase`) 5. Address comments by answering questions or changing code 6. LGTM (Looks good to me) - Once a Reviewer has completed a review and the code looks ready to merge, an "Approve" review is used to signal to the contributor and to other maintainers that you have reviewed the code and feel that it is ready to be merged. 7. Merge or close - PRs should stay open until merged or if they have not been active for more than 30 days. This will help keep the PR queue to a manageable size and reduce noise. Should the PR need to stay open (like in the case of a WIP), the `keep open` label can be added. - Before merging a PR, refer to the topic on [Size Labels](#size-labels) below to determine if the PR requires more than one LGTM to merge. - If the owner of the PR is listed in the `OWNERS` file, that user **must** merge their own PRs or explicitly request another OWNER do that for them. - If the owner of a PR is _not_ listed in `OWNERS`, any core maintainer may merge the PR. #### Documentation PRs Documentation PRs will follow the same lifecycle as other PRs. They will also be labeled with the `docs` label. For documentation, special attention will be paid to spelling, grammar, and clarity (whereas those things don't matter *as* much for comments in code). ## The Triager Each week, one of the core maintainers will serve as the designated "triager" starting after the public stand-up meetings on Thursday. This person will be in charge triaging new PRs and issues throughout the work week. ## Labels The following tables define all label types used for Helm. It is split up by category. ### Common | Label | Description | | ----- | ----------- | | `bug` | Marks an issue as a bug or a PR as a bugfix | | `critical` | Marks an issue or PR as critical. This means that addressing the PR or issue is top priority and must be addressed as soon as possible | | `docs` | Indicates the issue or PR is a documentation change | | `feature` | Marks the issue as a feature request or a PR as a feature implementation | | `keep open` | Denotes that the issue or PR should be kept open past 30 days of inactivity | | `refactor` | Indicates that the issue is a code refactor and is not fixing a bug or adding additional functionality | ### Issue Specific | Label | Description | | ----- | ----------- | | `help wanted` | Marks an issue needs help from the community to solve | | `proposal` | Marks an issue as a proposal | | `question/support` | Marks an issue as a support request or question | | `good first issue` | Marks an issue as a good starter issue for someone new to Helm | | `wont fix` | Marks an issue as discussed and will not be implemented (or accepted in the case of a proposal) | ### PR Specific | Label | Description | | ----- | ----------- | | `awaiting review` | Indicates a PR has been triaged and is ready for someone to review | | `breaking` | Indicates a PR has breaking changes (such as API changes) | | `in progress` | Indicates that a maintainer is looking at the PR, even if no review has been posted yet | | `needs rebase` | Indicates a PR needs to be rebased before it can be merged | | `needs pick` | Indicates a PR needs to be cherry-picked into a feature branch (generally bugfix branches). Once it has been, the `picked` label should be applied and this one removed | | `picked` | This PR has been cherry-picked into a feature branch | #### Size labels Size labels are used to indicate how "dangerous" a PR is. The guidelines below are used to assign the labels, but ultimately this can be changed by the maintainers. For example, even if a PR only makes 30 lines of changes in 1 file, but it changes key functionality, it will likely be labeled as `size/L` because it requires sign off from multiple people. Conversely, a PR that adds a small feature, but requires another 150 lines of tests to cover all cases, could be labeled as `size/S` even though the number of lines is greater than defined below. Any changes from the community labeled as `size/S` or larger should be thoroughly tested before merging and always requires approval from 2 core maintainers. PRs submitted by a core maintainer, regardless of size, only requires approval from one additional maintainer. This ensures there are at least two maintainers who are aware of any significant PRs introduced to the codebase. | Label | Description | | ----- | ----------- | | `size/XS` | Denotes a PR that changes 0-9 lines, ignoring generated files. Very little testing may be required depending on the change. | | `size/S` | Denotes a PR that changes 10-29 lines, ignoring generated files. Only small amounts of manual testing may be required. | | `size/M` | Denotes a PR that changes 30-99 lines, ignoring generated files. Manual validation should be required. | | `size/L` | Denotes a PR that changes 100-499 lines, ignoring generated files. | | `size/XL` | Denotes a PR that changes 500-999 lines, ignoring generated files. | | `size/XXL` | Denotes a PR that changes 1000+ lines, ignoring generated files. |
{ "content_hash": "ea463f90e7d956f9be916251b7e3b0d2", "timestamp": "", "source": "github", "line_count": 350, "max_line_length": 186, "avg_line_length": 53.66, "alnum_prop": 0.7548586337255737, "repo_name": "bacongobbler/helm", "id": "37627e716c7b59ceb193d6a6a188cfeb7eb50410", "size": "18808", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "CONTRIBUTING.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1649534" }, { "name": "Makefile", "bytes": "7784" }, { "name": "Shell", "bytes": "32580" } ], "symlink_target": "" }
if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') { PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js"; Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE); nitpick = createNitpick(Script.resolvePath(".")); } nitpick.perform("Read GLTF model", Script.resolvePath("."), "secondary", undefined, function(testType) { var assetsRootPath = nitpick.getAssetsRootPath(); var LIFETIME = 60.0; var position = nitpick.getOriginFrame(); Script.include(nitpick.getUtilsRootPath() + "test_stage.js"); var initData = { flags : { hasKeyLight: true, hasAmbientLight: true, hasKeyLightShadow: true, }, originFrame: nitpick.getOriginFrame() }; var createdEntities = setupStage(initData); var testEntity = Entities.addEntity({ lifetime: LIFETIME, type: "Model", // https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/Lantern modelURL: assetsRootPath + 'models/gltf_models/glb/Lantern.glb', position: Vec3.sum(position, {x: 0.0, y: 0.8, z: -1.75 }), rotation: Quat.fromPitchYawRollDegrees(0.0, 0.0, 0.0), visible: true, userData: JSON.stringify({ grabbableKey: { grabbable: false } }) }); createdEntities.push(testEntity); nitpick.addStep("Scale to 1m", function () { var properties = Entities.getEntityProperties(testEntity); var scale = Math.max(properties.dimensions.x, properties.dimensions.y, properties.dimensions.z); if (scale > 0) { Entities.editEntity(testEntity, { dimensions: { x: properties.dimensions.x / scale, y: properties.dimensions.y / scale, z: properties.dimensions.z / scale} }); } }); nitpick.addStepSnapshot("Lantern.glb Model is visible"); nitpick.addStep("Clean up after test", function () { for (var i = 0; i < createdEntities.length; i++) { Entities.deleteEntity(createdEntities[i]); } }); var result = nitpick.runTest(testType); });
{ "content_hash": "015d4a61d0f23b8c83158cd37c259634", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 171, "avg_line_length": 39.58181818181818, "alnum_prop": 0.6293063849333945, "repo_name": "highfidelity/hifi_tests", "id": "f3d00b0e9467dbf27436d356dcc58b0ebd2eb22f", "size": "2177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/content/entity/model/modelReaders/gltfReader/glbTestSuite/lantern/test.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2633" }, { "name": "CSS", "bytes": "1354" }, { "name": "F*", "bytes": "7176" }, { "name": "GLSL", "bytes": "1368" }, { "name": "HTML", "bytes": "2407" }, { "name": "JavaScript", "bytes": "972684" }, { "name": "PowerShell", "bytes": "246" }, { "name": "Python", "bytes": "6298" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>qgis._core.QgsColorBrewerPalette</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="QGIS-AIMS-Plugin-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> qgis :: _core :: QgsColorBrewerPalette :: Class&nbsp;QgsColorBrewerPalette </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="qgis._core.QgsColorBrewerPalette-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class QgsColorBrewerPalette</h1><p class="nomargin-top"></p> <pre class="base-tree"> object --+ | sip.simplewrapper --+ | sip.wrapper --+ | <strong class="uidshort">QgsColorBrewerPalette</strong> </pre> <hr /> <p>QgsColorBrewerPalette() QgsColorBrewerPalette(QgsColorBrewerPalette)</p> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="listSchemeColors"></a><span class="summary-sig-name">listSchemeColors</span>(<span class="summary-sig-arg">...</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="listSchemeVariants"></a><span class="summary-sig-name">listSchemeVariants</span>(<span class="summary-sig-arg">...</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="listSchemes"></a><span class="summary-sig-name">listSchemes</span>(<span class="summary-sig-arg">...</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>sip.simplewrapper</code></b>: <code>__init__</code>, <code>__new__</code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__delattr__</code>, <code>__format__</code>, <code>__getattribute__</code>, <code>__hash__</code>, <code>__reduce__</code>, <code>__reduce_ex__</code>, <code>__repr__</code>, <code>__setattr__</code>, <code>__sizeof__</code>, <code>__str__</code>, <code>__subclasshook__</code> </p> </td> </tr> </table> <!-- ==================== CLASS VARIABLES ==================== --> <a name="section-ClassVariables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Class Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-ClassVariables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="brewerString"></a><span class="summary-name">brewerString</span> = <code title="&lt;sip.variabledescriptor object at 0x7f88da66c9b0&gt;">&lt;sip.variabledescriptor object at 0x7f88da66c9b0&gt;</code> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__class__</code> </p> </td> </tr> </table> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="QGIS-AIMS-Plugin-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Tue Jun 14 13:29:18 2016 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
{ "content_hash": "69790afe4501b18ed78d6ad74089f79a", "timestamp": "", "source": "github", "line_count": 257, "max_line_length": 216, "avg_line_length": 34.797665369649806, "alnum_prop": 0.5508218718550821, "repo_name": "linz/QGIS-AIMS-Plugin", "id": "2e8d2bccfcf13243205a3df268d5182d4ca06b18", "size": "8943", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/Aims-Plugin_Doc/qgis._core.QgsColorBrewerPalette-class.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "1572" }, { "name": "Python", "bytes": "594004" }, { "name": "QML", "bytes": "112051" } ], "symlink_target": "" }
package org.apache.hadoop.hbase.io.encoding; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.KeyValue.Type; import org.apache.hadoop.hbase.LargeTests; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.test.RedundantKVGenerator; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Test all of the data block encoding algorithms for correctness. * Most of the class generate data which will test different branches in code. */ @Category(LargeTests.class) @RunWith(Parameterized.class) public class TestDataBlockEncoders { static int NUMBER_OF_KV = 10000; static int NUM_RANDOM_SEEKS = 10000; private static int ENCODED_DATA_OFFSET = HConstants.HFILEBLOCK_HEADER_SIZE + DataBlockEncoding.ID_SIZE; private RedundantKVGenerator generator = new RedundantKVGenerator(); private Random randomizer = new Random(42l); private final boolean includesMemstoreTS; @Parameters public static Collection<Object[]> parameters() { return HBaseTestingUtility.BOOLEAN_PARAMETERIZED; } public TestDataBlockEncoders(boolean includesMemstoreTS) { this.includesMemstoreTS = includesMemstoreTS; } private HFileBlockEncodingContext getEncodingContext( Compression.Algorithm algo, DataBlockEncoding encoding) { DataBlockEncoder encoder = encoding.getEncoder(); if (encoder != null) { return encoder.newDataBlockEncodingContext(algo, encoding, HConstants.HFILEBLOCK_DUMMY_HEADER); } else { return new HFileBlockDefaultEncodingContext(algo, encoding, HConstants.HFILEBLOCK_DUMMY_HEADER); } } private byte[] encodeBytes(DataBlockEncoding encoding, ByteBuffer dataset) throws IOException { DataBlockEncoder encoder = encoding.getEncoder(); HFileBlockEncodingContext encodingCtx = getEncodingContext(Compression.Algorithm.NONE, encoding); encoder.encodeKeyValues(dataset, includesMemstoreTS, encodingCtx); byte[] encodedBytesWithHeader = encodingCtx.getUncompressedBytesWithHeader(); byte[] encodedData = new byte[encodedBytesWithHeader.length - ENCODED_DATA_OFFSET]; System.arraycopy(encodedBytesWithHeader, ENCODED_DATA_OFFSET, encodedData, 0, encodedData.length); return encodedData; } private void testAlgorithm(ByteBuffer dataset, DataBlockEncoding encoding) throws IOException { // encode byte[] encodedBytes = encodeBytes(encoding, dataset); //decode ByteArrayInputStream bais = new ByteArrayInputStream(encodedBytes); DataInputStream dis = new DataInputStream(bais); ByteBuffer actualDataset; DataBlockEncoder encoder = encoding.getEncoder(); actualDataset = encoder.decodeKeyValues(dis, includesMemstoreTS); dataset.rewind(); actualDataset.rewind(); assertEquals("Encoding -> decoding gives different results for " + encoder, Bytes.toStringBinary(dataset), Bytes.toStringBinary(actualDataset)); } /** * Test data block encoding of empty KeyValue. * @throws IOException On test failure. */ @Test public void testEmptyKeyValues() throws IOException { List<KeyValue> kvList = new ArrayList<KeyValue>(); byte[] row = new byte[0]; byte[] family = new byte[0]; byte[] qualifier = new byte[0]; byte[] value = new byte[0]; kvList.add(new KeyValue(row, family, qualifier, 0l, Type.Put, value)); kvList.add(new KeyValue(row, family, qualifier, 0l, Type.Put, value)); testEncodersOnDataset(RedundantKVGenerator.convertKvToByteBuffer(kvList, includesMemstoreTS)); } /** * Test KeyValues with negative timestamp. * @throws IOException On test failure. */ @Test public void testNegativeTimestamps() throws IOException { List<KeyValue> kvList = new ArrayList<KeyValue>(); byte[] row = new byte[0]; byte[] family = new byte[0]; byte[] qualifier = new byte[0]; byte[] value = new byte[0]; kvList.add(new KeyValue(row, family, qualifier, -1l, Type.Put, value)); kvList.add(new KeyValue(row, family, qualifier, -2l, Type.Put, value)); testEncodersOnDataset( RedundantKVGenerator.convertKvToByteBuffer(kvList, includesMemstoreTS)); } /** * Test whether compression -> decompression gives the consistent results on * pseudorandom sample. * @throws IOException On test failure. */ @Test public void testExecutionOnSample() throws IOException { testEncodersOnDataset( RedundantKVGenerator.convertKvToByteBuffer( generator.generateTestKeyValues(NUMBER_OF_KV), includesMemstoreTS)); } /** * Test seeking while file is encoded. */ @Test public void testSeekingOnSample() throws IOException{ List<KeyValue> sampleKv = generator.generateTestKeyValues(NUMBER_OF_KV); ByteBuffer originalBuffer = RedundantKVGenerator.convertKvToByteBuffer(sampleKv, includesMemstoreTS); // create all seekers List<DataBlockEncoder.EncodedSeeker> encodedSeekers = new ArrayList<DataBlockEncoder.EncodedSeeker>(); for (DataBlockEncoding encoding : DataBlockEncoding.values()) { if (encoding.getEncoder() == null) { continue; } ByteBuffer encodedBuffer = ByteBuffer.wrap(encodeBytes(encoding, originalBuffer)); DataBlockEncoder encoder = encoding.getEncoder(); DataBlockEncoder.EncodedSeeker seeker = encoder.createSeeker(KeyValue.COMPARATOR, includesMemstoreTS); seeker.setCurrentBuffer(encodedBuffer); encodedSeekers.add(seeker); } // test it! // try a few random seeks for (boolean seekBefore : new boolean[] {false, true}) { for (int i = 0; i < NUM_RANDOM_SEEKS; ++i) { int keyValueId; if (!seekBefore) { keyValueId = randomizer.nextInt(sampleKv.size()); } else { keyValueId = randomizer.nextInt(sampleKv.size() - 1) + 1; } KeyValue keyValue = sampleKv.get(keyValueId); checkSeekingConsistency(encodedSeekers, seekBefore, keyValue); } } // check edge cases checkSeekingConsistency(encodedSeekers, false, sampleKv.get(0)); for (boolean seekBefore : new boolean[] {false, true}) { checkSeekingConsistency(encodedSeekers, seekBefore, sampleKv.get(sampleKv.size() - 1)); KeyValue midKv = sampleKv.get(sampleKv.size() / 2); KeyValue lastMidKv = midKv.createLastOnRowCol(); checkSeekingConsistency(encodedSeekers, seekBefore, lastMidKv); } } /** * Test iterating on encoded buffers. */ @Test public void testNextOnSample() { List<KeyValue> sampleKv = generator.generateTestKeyValues(NUMBER_OF_KV); ByteBuffer originalBuffer = RedundantKVGenerator.convertKvToByteBuffer(sampleKv, includesMemstoreTS); for (DataBlockEncoding encoding : DataBlockEncoding.values()) { if (encoding.getEncoder() == null) { continue; } DataBlockEncoder encoder = encoding.getEncoder(); ByteBuffer encodedBuffer = null; try { encodedBuffer = ByteBuffer.wrap(encodeBytes(encoding, originalBuffer)); } catch (IOException e) { throw new RuntimeException(String.format( "Bug while encoding using '%s'", encoder.toString()), e); } DataBlockEncoder.EncodedSeeker seeker = encoder.createSeeker(KeyValue.COMPARATOR, includesMemstoreTS); seeker.setCurrentBuffer(encodedBuffer); int i = 0; do { KeyValue expectedKeyValue = sampleKv.get(i); ByteBuffer keyValue = seeker.getKeyValueBuffer(); if (0 != Bytes.compareTo( keyValue.array(), keyValue.arrayOffset(), keyValue.limit(), expectedKeyValue.getBuffer(), expectedKeyValue.getOffset(), expectedKeyValue.getLength())) { int commonPrefix = 0; byte[] left = keyValue.array(); byte[] right = expectedKeyValue.getBuffer(); int leftOff = keyValue.arrayOffset(); int rightOff = expectedKeyValue.getOffset(); int length = Math.min(keyValue.limit(), expectedKeyValue.getLength()); while (commonPrefix < length && left[commonPrefix + leftOff] == right[commonPrefix + rightOff]) { commonPrefix++; } fail(String.format( "next() produces wrong results " + "encoder: %s i: %d commonPrefix: %d" + "\n expected %s\n actual %s", encoder.toString(), i, commonPrefix, Bytes.toStringBinary(expectedKeyValue.getBuffer(), expectedKeyValue.getOffset(), expectedKeyValue.getLength()), Bytes.toStringBinary(keyValue))); } i++; } while (seeker.next()); } } /** * Test whether the decompression of first key is implemented correctly. */ @Test public void testFirstKeyInBlockOnSample() { List<KeyValue> sampleKv = generator.generateTestKeyValues(NUMBER_OF_KV); ByteBuffer originalBuffer = RedundantKVGenerator.convertKvToByteBuffer(sampleKv, includesMemstoreTS); for (DataBlockEncoding encoding : DataBlockEncoding.values()) { if (encoding.getEncoder() == null) { continue; } DataBlockEncoder encoder = encoding.getEncoder(); ByteBuffer encodedBuffer = null; try { encodedBuffer = ByteBuffer.wrap(encodeBytes(encoding, originalBuffer)); } catch (IOException e) { throw new RuntimeException(String.format( "Bug while encoding using '%s'", encoder.toString()), e); } ByteBuffer keyBuffer = encoder.getFirstKeyInBlock(encodedBuffer); KeyValue firstKv = sampleKv.get(0); if (0 != Bytes.compareTo( keyBuffer.array(), keyBuffer.arrayOffset(), keyBuffer.limit(), firstKv.getBuffer(), firstKv.getKeyOffset(), firstKv.getKeyLength())) { int commonPrefix = 0; int length = Math.min(keyBuffer.limit(), firstKv.getKeyLength()); while (commonPrefix < length && keyBuffer.array()[keyBuffer.arrayOffset() + commonPrefix] == firstKv.getBuffer()[firstKv.getKeyOffset() + commonPrefix]) { commonPrefix++; } fail(String.format("Bug in '%s' commonPrefix %d", encoder.toString(), commonPrefix)); } } } private void checkSeekingConsistency( List<DataBlockEncoder.EncodedSeeker> encodedSeekers, boolean seekBefore, KeyValue keyValue) { ByteBuffer expectedKeyValue = null; ByteBuffer expectedKey = null; ByteBuffer expectedValue = null; for (DataBlockEncoder.EncodedSeeker seeker : encodedSeekers) { seeker.seekToKeyInBlock(keyValue.getBuffer(), keyValue.getKeyOffset(), keyValue.getKeyLength(), seekBefore); seeker.rewind(); ByteBuffer actualKeyValue = seeker.getKeyValueBuffer(); ByteBuffer actualKey = seeker.getKeyDeepCopy(); ByteBuffer actualValue = seeker.getValueShallowCopy(); if (expectedKeyValue != null) { assertEquals(expectedKeyValue, actualKeyValue); } else { expectedKeyValue = actualKeyValue; } if (expectedKey != null) { assertEquals(expectedKey, actualKey); } else { expectedKey = actualKey; } if (expectedValue != null) { assertEquals(expectedValue, actualValue); } else { expectedValue = actualValue; } } } private void testEncodersOnDataset(ByteBuffer onDataset) throws IOException{ ByteBuffer dataset = ByteBuffer.allocate(onDataset.capacity()); onDataset.rewind(); dataset.put(onDataset); onDataset.rewind(); dataset.flip(); for (DataBlockEncoding encoding : DataBlockEncoding.values()) { if (encoding.getEncoder() == null) { continue; } testAlgorithm(dataset, encoding); // ensure that dataset is unchanged dataset.rewind(); assertEquals("Input of two methods is changed", onDataset, dataset); } } }
{ "content_hash": "e012158163ce51c57d1bc5d2c2585e71", "timestamp": "", "source": "github", "line_count": 361, "max_line_length": 102, "avg_line_length": 35.199445983379505, "alnum_prop": 0.6820650035413551, "repo_name": "lilonglai/hbase-0.96.2", "id": "db9c9192f2a3d9c473832ea7a45d960b2d481fde", "size": "13502", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hbase-server/src/test/java/org/apache/hadoop/hbase/io/encoding/TestDataBlockEncoders.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.flink.streaming.connectors.kafka; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.serialization.TypeInformationSerializationSchema; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeutils.base.IntSerializer; import org.apache.flink.runtime.checkpoint.OperatorSubtaskState; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.streaming.api.operators.StreamSink; import org.apache.flink.streaming.connectors.kafka.internals.KeyedSerializationSchemaWrapper; import org.apache.flink.streaming.util.AbstractStreamOperatorTestHarness; import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness; import org.apache.flink.streaming.util.serialization.KeyedSerializationSchema; import kafka.server.KafkaServer; import org.apache.kafka.common.errors.ProducerFencedException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011.Semantic; import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011.Semantic.AT_LEAST_ONCE; import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011.Semantic.EXACTLY_ONCE; import static org.apache.flink.util.ExceptionUtils.findThrowable; import static org.apache.flink.util.Preconditions.checkState; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * IT cases for the {@link FlinkKafkaProducer011}. */ @SuppressWarnings("serial") public class FlinkKafkaProducer011ITCase extends KafkaTestBaseWithFlink { protected String transactionalId; protected Properties extraProperties; protected TypeInformationSerializationSchema<Integer> integerSerializationSchema = new TypeInformationSerializationSchema<>(BasicTypeInfo.INT_TYPE_INFO, new ExecutionConfig()); protected KeyedSerializationSchema<Integer> integerKeyedSerializationSchema = new KeyedSerializationSchemaWrapper<>(integerSerializationSchema); @Before public void before() { transactionalId = UUID.randomUUID().toString(); extraProperties = new Properties(); extraProperties.putAll(standardProps); extraProperties.put("transactional.id", transactionalId); extraProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); extraProperties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); extraProperties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); extraProperties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); extraProperties.put("isolation.level", "read_committed"); } @Test public void resourceCleanUpNone() throws Exception { resourceCleanUp(Semantic.NONE); } @Test public void resourceCleanUpAtLeastOnce() throws Exception { resourceCleanUp(AT_LEAST_ONCE); } /** * This tests checks whether there is some resource leak in form of growing threads number. */ public void resourceCleanUp(Semantic semantic) throws Exception { String topic = "flink-kafka-producer-resource-cleanup-" + semantic; final int allowedEpsilonThreadCountGrow = 50; Optional<Integer> initialActiveThreads = Optional.empty(); for (int i = 0; i < allowedEpsilonThreadCountGrow * 2; i++) { try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness1 = createTestHarness(topic, 1, 1, 0, semantic)) { testHarness1.setup(); testHarness1.open(); } if (initialActiveThreads.isPresent()) { assertThat("active threads count", Thread.activeCount(), lessThan(initialActiveThreads.get() + allowedEpsilonThreadCountGrow)); } else { initialActiveThreads = Optional.of(Thread.activeCount()); } } } /** * This test ensures that transactions reusing transactional.ids (after returning to the pool) will not clash * with previous transactions using same transactional.ids. */ @Test public void testRestoreToCheckpointAfterExceedingProducersPool() throws Exception { String topic = "flink-kafka-producer-fail-before-notify"; try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness1 = createTestHarness(topic)) { testHarness1.setup(); testHarness1.open(); testHarness1.processElement(42, 0); OperatorSubtaskState snapshot = testHarness1.snapshot(0, 0); testHarness1.processElement(43, 0); testHarness1.notifyOfCompletedCheckpoint(0); try { for (int i = 0; i < FlinkKafkaProducer011.DEFAULT_KAFKA_PRODUCERS_POOL_SIZE; i++) { testHarness1.snapshot(i + 1, 0); testHarness1.processElement(i, 0); } throw new IllegalStateException("This should not be reached."); } catch (Exception ex) { if (!isCausedBy(FlinkKafka011ErrorCode.PRODUCERS_POOL_EMPTY, ex)) { throw ex; } } // Resume transactions before testHarness1 is being closed (in case of failures close() might not be called) try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness2 = createTestHarness(topic)) { testHarness2.setup(); // restore from snapshot1, transactions with records 43 and 44 should be aborted testHarness2.initializeState(snapshot); testHarness2.open(); } assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(42)); deleteTestTopic(topic); } catch (Exception ex) { // testHarness1 will be fenced off after creating and closing testHarness2 if (!findThrowable(ex, ProducerFencedException.class).isPresent()) { throw ex; } } } @Test public void testFlinkKafkaProducer011FailBeforeNotify() throws Exception { String topic = "flink-kafka-producer-fail-before-notify"; OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic); testHarness.setup(); testHarness.open(); testHarness.processElement(42, 0); testHarness.snapshot(0, 1); testHarness.processElement(43, 2); OperatorSubtaskState snapshot = testHarness.snapshot(1, 3); int leaderId = kafkaServer.getLeaderToShutDown(topic); failBroker(leaderId); try { testHarness.processElement(44, 4); testHarness.snapshot(2, 5); fail(); } catch (Exception ex) { // expected } try { testHarness.close(); } catch (Exception ex) { } kafkaServer.restartBroker(leaderId); testHarness = createTestHarness(topic); testHarness.setup(); testHarness.initializeState(snapshot); testHarness.close(); assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(42, 43)); deleteTestTopic(topic); } /** * This tests checks whether FlinkKafkaProducer011 correctly aborts lingering transactions after a failure. * If such transactions were left alone lingering it consumers would be unable to read committed records * that were created after this lingering transaction. */ @Test public void testFailBeforeNotifyAndResumeWorkAfterwards() throws Exception { String topic = "flink-kafka-producer-fail-before-notify"; OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic); testHarness.setup(); testHarness.open(); testHarness.processElement(42, 0); testHarness.snapshot(0, 1); testHarness.processElement(43, 2); OperatorSubtaskState snapshot1 = testHarness.snapshot(1, 3); testHarness.processElement(44, 4); testHarness.snapshot(2, 5); testHarness.processElement(45, 6); // do not close previous testHarness to make sure that closing do not clean up something (in case of failure // there might not be any close) testHarness = createTestHarness(topic); testHarness.setup(); // restore from snapshot1, transactions with records 44 and 45 should be aborted testHarness.initializeState(snapshot1); testHarness.open(); // write and commit more records, after potentially lingering transactions testHarness.processElement(46, 7); testHarness.snapshot(4, 8); testHarness.processElement(47, 9); testHarness.notifyOfCompletedCheckpoint(4); //now we should have: // - records 42 and 43 in committed transactions // - aborted transactions with records 44 and 45 // - committed transaction with record 46 // - pending transaction with record 47 assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(42, 43, 46)); testHarness.close(); deleteTestTopic(topic); } @Test public void testFailAndRecoverSameCheckpointTwice() throws Exception { String topic = "flink-kafka-producer-fail-and-recover-same-checkpoint-twice"; OperatorSubtaskState snapshot1; try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic)) { testHarness.setup(); testHarness.open(); testHarness.processElement(42, 0); testHarness.snapshot(0, 1); testHarness.processElement(43, 2); snapshot1 = testHarness.snapshot(1, 3); testHarness.processElement(44, 4); } try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic)) { testHarness.setup(); // restore from snapshot1, transactions with records 44 and 45 should be aborted testHarness.initializeState(snapshot1); testHarness.open(); // write and commit more records, after potentially lingering transactions testHarness.processElement(44, 7); testHarness.snapshot(2, 8); testHarness.processElement(45, 9); } try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic)) { testHarness.setup(); // restore from snapshot1, transactions with records 44 and 45 should be aborted testHarness.initializeState(snapshot1); testHarness.open(); // write and commit more records, after potentially lingering transactions testHarness.processElement(44, 7); testHarness.snapshot(3, 8); testHarness.processElement(45, 9); } //now we should have: // - records 42 and 43 in committed transactions // - aborted transactions with records 44 and 45 assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(42, 43)); deleteTestTopic(topic); } /** * This tests checks whether FlinkKafkaProducer011 correctly aborts lingering transactions after a failure, * which happened before first checkpoint and was followed up by reducing the parallelism. * If such transactions were left alone lingering it consumers would be unable to read committed records * that were created after this lingering transaction. */ @Test public void testScaleDownBeforeFirstCheckpoint() throws Exception { String topic = "scale-down-before-first-checkpoint"; List<AutoCloseable> operatorsToClose = new ArrayList<>(); int preScaleDownParallelism = Math.max(2, FlinkKafkaProducer011.SAFE_SCALE_DOWN_FACTOR); for (int subtaskIndex = 0; subtaskIndex < preScaleDownParallelism; subtaskIndex++) { OneInputStreamOperatorTestHarness<Integer, Object> preScaleDownOperator = createTestHarness( topic, preScaleDownParallelism, preScaleDownParallelism, subtaskIndex, EXACTLY_ONCE); preScaleDownOperator.setup(); preScaleDownOperator.open(); preScaleDownOperator.processElement(subtaskIndex * 2, 0); preScaleDownOperator.snapshot(0, 1); preScaleDownOperator.processElement(subtaskIndex * 2 + 1, 2); operatorsToClose.add(preScaleDownOperator); } // do not close previous testHarnesses to make sure that closing do not clean up something (in case of failure // there might not be any close) // After previous failure simulate restarting application with smaller parallelism OneInputStreamOperatorTestHarness<Integer, Object> postScaleDownOperator1 = createTestHarness(topic, 1, 1, 0, EXACTLY_ONCE); postScaleDownOperator1.setup(); postScaleDownOperator1.open(); // write and commit more records, after potentially lingering transactions postScaleDownOperator1.processElement(46, 7); postScaleDownOperator1.snapshot(4, 8); postScaleDownOperator1.processElement(47, 9); postScaleDownOperator1.notifyOfCompletedCheckpoint(4); //now we should have: // - records 42, 43, 44 and 45 in aborted transactions // - committed transaction with record 46 // - pending transaction with record 47 assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(46)); postScaleDownOperator1.close(); // ignore ProducerFencedExceptions, because postScaleDownOperator1 could reuse transactional ids. for (AutoCloseable operatorToClose : operatorsToClose) { closeIgnoringProducerFenced(operatorToClose); } deleteTestTopic(topic); } /** * Each instance of FlinkKafkaProducer011 uses it's own pool of transactional ids. After the restore from checkpoint * transactional ids are redistributed across the subtasks. In case of scale down, the surplus transactional ids * are dropped. In case of scale up, new one are generated (for the new subtasks). This test make sure that sequence * of scaling down and up again works fine. Especially it checks whether the newly generated ids in scaling up * do not overlap with ids that were used before scaling down. For example we start with 4 ids and parallelism 4: * [1], [2], [3], [4] - one assigned per each subtask * we scale down to parallelism 2: * [1, 2], [3, 4] - first subtask got id 1 and 2, second got ids 3 and 4 * surplus ids are dropped from the pools and we scale up to parallelism 3: * [1 or 2], [3 or 4], [???] * new subtask have to generate new id(s), but he can not use ids that are potentially in use, so it has to generate * new ones that are greater then 4. */ @Test public void testScaleUpAfterScalingDown() throws Exception { String topic = "scale-down-before-first-checkpoint"; final int parallelism1 = 4; final int parallelism2 = 2; final int parallelism3 = 3; final int maxParallelism = Math.max(parallelism1, Math.max(parallelism2, parallelism3)); OperatorSubtaskState operatorSubtaskState = repartitionAndExecute( topic, new OperatorSubtaskState(), parallelism1, parallelism1, maxParallelism, IntStream.range(0, parallelism1).boxed().iterator()); operatorSubtaskState = repartitionAndExecute( topic, operatorSubtaskState, parallelism1, parallelism2, maxParallelism, IntStream.range(parallelism1, parallelism1 + parallelism2).boxed().iterator()); operatorSubtaskState = repartitionAndExecute( topic, operatorSubtaskState, parallelism2, parallelism3, maxParallelism, IntStream.range(parallelism1 + parallelism2, parallelism1 + parallelism2 + parallelism3).boxed().iterator()); // After each previous repartitionAndExecute call, we are left with some lingering transactions, that would // not allow us to read all committed messages from the topic. Thus we initialize operators from // OperatorSubtaskState once more, but without any new data. This should terminate all ongoing transactions. repartitionAndExecute( topic, operatorSubtaskState, parallelism3, 1, maxParallelism, Collections.emptyIterator()); assertExactlyOnceForTopic( createProperties(), topic, 0, IntStream.range(0, parallelism1 + parallelism2 + parallelism3).boxed().collect(Collectors.toList())); deleteTestTopic(topic); } private OperatorSubtaskState repartitionAndExecute( String topic, OperatorSubtaskState inputStates, int oldParallelism, int newParallelism, int maxParallelism, Iterator<Integer> inputData) throws Exception { List<OperatorSubtaskState> outputStates = new ArrayList<>(); List<OneInputStreamOperatorTestHarness<Integer, Object>> testHarnesses = new ArrayList<>(); for (int subtaskIndex = 0; subtaskIndex < newParallelism; subtaskIndex++) { OperatorSubtaskState initState = AbstractStreamOperatorTestHarness.repartitionOperatorState( inputStates, maxParallelism, oldParallelism, newParallelism, subtaskIndex); OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic, maxParallelism, newParallelism, subtaskIndex, EXACTLY_ONCE); testHarnesses.add(testHarness); testHarness.setup(); testHarness.initializeState(initState); testHarness.open(); if (inputData.hasNext()) { int nextValue = inputData.next(); testHarness.processElement(nextValue, 0); OperatorSubtaskState snapshot = testHarness.snapshot(0, 0); outputStates.add(snapshot); checkState(snapshot.getRawOperatorState().isEmpty(), "Unexpected raw operator state"); checkState(snapshot.getManagedKeyedState().isEmpty(), "Unexpected managed keyed state"); checkState(snapshot.getRawKeyedState().isEmpty(), "Unexpected raw keyed state"); for (int i = 1; i < FlinkKafkaProducer011.DEFAULT_KAFKA_PRODUCERS_POOL_SIZE - 1; i++) { testHarness.processElement(-nextValue, 0); testHarness.snapshot(i, 0); } } } for (OneInputStreamOperatorTestHarness<Integer, Object> testHarness : testHarnesses) { testHarness.close(); } return AbstractStreamOperatorTestHarness.repackageState( outputStates.toArray(new OperatorSubtaskState[outputStates.size()])); } @Test public void testRecoverCommittedTransaction() throws Exception { String topic = "flink-kafka-producer-recover-committed-transaction"; OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic); testHarness.setup(); testHarness.open(); // producerA - start transaction (txn) 0 testHarness.processElement(42, 0); // producerA - write 42 in txn 0 OperatorSubtaskState checkpoint0 = testHarness.snapshot(0, 1); // producerA - pre commit txn 0, producerB - start txn 1 testHarness.processElement(43, 2); // producerB - write 43 in txn 1 testHarness.notifyOfCompletedCheckpoint(0); // producerA - commit txn 0 and return to the pool testHarness.snapshot(1, 3); // producerB - pre txn 1, producerA - start txn 2 testHarness.processElement(44, 4); // producerA - write 44 in txn 2 testHarness.close(); // producerA - abort txn 2 testHarness = createTestHarness(topic); testHarness.initializeState(checkpoint0); // recover state 0 - producerA recover and commit txn 0 testHarness.close(); assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(42)); deleteTestTopic(topic); } @Test public void testRunOutOfProducersInThePool() throws Exception { String topic = "flink-kafka-run-out-of-producers"; try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic)) { testHarness.setup(); testHarness.open(); for (int i = 0; i < FlinkKafkaProducer011.DEFAULT_KAFKA_PRODUCERS_POOL_SIZE * 2; i++) { testHarness.processElement(i, i * 2); testHarness.snapshot(i, i * 2 + 1); } } catch (Exception ex) { if (!ex.getCause().getMessage().startsWith("Too many ongoing")) { throw ex; } } deleteTestTopic(topic); } @Test public void testMigrateFromAtLeastOnceToExactlyOnce() throws Exception { String topic = "testMigrateFromAtLeastOnceToExactlyOnce"; testRecoverWithChangeSemantics(topic, AT_LEAST_ONCE, EXACTLY_ONCE); assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(42, 43, 44, 45)); deleteTestTopic(topic); } @Test public void testMigrateFromAtExactlyOnceToAtLeastOnce() throws Exception { String topic = "testMigrateFromExactlyOnceToAtLeastOnce"; testRecoverWithChangeSemantics(topic, EXACTLY_ONCE, AT_LEAST_ONCE); assertExactlyOnceForTopic(createProperties(), topic, 0, Arrays.asList(42, 43, 45, 46, 47)); deleteTestTopic(topic); } private void testRecoverWithChangeSemantics( String topic, Semantic fromSemantic, Semantic toSemantic) throws Exception { OperatorSubtaskState producerSnapshot; try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic, fromSemantic)) { testHarness.setup(); testHarness.open(); testHarness.processElement(42, 0); testHarness.snapshot(0, 1); testHarness.processElement(43, 2); testHarness.notifyOfCompletedCheckpoint(0); producerSnapshot = testHarness.snapshot(1, 3); testHarness.processElement(44, 4); } try (OneInputStreamOperatorTestHarness<Integer, Object> testHarness = createTestHarness(topic, toSemantic)) { testHarness.setup(); testHarness.initializeState(producerSnapshot); testHarness.open(); testHarness.processElement(45, 7); testHarness.snapshot(2, 8); testHarness.processElement(46, 9); testHarness.notifyOfCompletedCheckpoint(2); testHarness.processElement(47, 9); } } // shut down a Kafka broker private void failBroker(int brokerId) { KafkaServer toShutDown = null; for (KafkaServer server : kafkaServer.getBrokers()) { if (kafkaServer.getBrokerId(server) == brokerId) { toShutDown = server; break; } } if (toShutDown == null) { StringBuilder listOfBrokers = new StringBuilder(); for (KafkaServer server : kafkaServer.getBrokers()) { listOfBrokers.append(kafkaServer.getBrokerId(server)); listOfBrokers.append(" ; "); } throw new IllegalArgumentException("Cannot find broker to shut down: " + brokerId + " ; available brokers: " + listOfBrokers.toString()); } else { toShutDown.shutdown(); toShutDown.awaitShutdown(); } } private void closeIgnoringProducerFenced(AutoCloseable autoCloseable) throws Exception { try { autoCloseable.close(); } catch (Exception ex) { if (!(ex.getCause() instanceof ProducerFencedException)) { throw ex; } } } private OneInputStreamOperatorTestHarness<Integer, Object> createTestHarness(String topic) throws Exception { return createTestHarness(topic, Semantic.EXACTLY_ONCE); } private OneInputStreamOperatorTestHarness<Integer, Object> createTestHarness( String topic, Semantic semantic) throws Exception { return createTestHarness(topic, 1, 1, 0, semantic); } private OneInputStreamOperatorTestHarness<Integer, Object> createTestHarness( String topic, int maxParallelism, int parallelism, int subtaskIndex, Semantic semantic) throws Exception { Properties properties = createProperties(); FlinkKafkaProducer011<Integer> kafkaProducer = new FlinkKafkaProducer011<>( topic, integerKeyedSerializationSchema, properties, semantic); return new OneInputStreamOperatorTestHarness<>( new StreamSink<>(kafkaProducer), maxParallelism, parallelism, subtaskIndex, IntSerializer.INSTANCE, new OperatorID(42, 44)); } private Properties createProperties() { Properties properties = new Properties(); properties.putAll(standardProps); properties.putAll(secureProps); properties.put(FlinkKafkaProducer011.KEY_DISABLE_METRICS, "true"); return properties; } private boolean isCausedBy(FlinkKafka011ErrorCode expectedErrorCode, Throwable ex) { Optional<FlinkKafka011Exception> cause = findThrowable(ex, FlinkKafka011Exception.class); if (cause.isPresent()) { return cause.get().getErrorCode().equals(expectedErrorCode); } return false; } }
{ "content_hash": "9e69274be5acb51e045cf269309f6c04", "timestamp": "", "source": "github", "line_count": 638, "max_line_length": 126, "avg_line_length": 36.4717868338558, "alnum_prop": 0.7609695302763333, "repo_name": "ueshin/apache-flink", "id": "5e4b0d5275aaa53e5ffd2514c28ade466e535f8d", "size": "24074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-connectors/flink-connector-kafka-0.11/src/test/java/org/apache/flink/streaming/connectors/kafka/FlinkKafkaProducer011ITCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5667" }, { "name": "CSS", "bytes": "18100" }, { "name": "Clojure", "bytes": "88796" }, { "name": "CoffeeScript", "bytes": "91220" }, { "name": "Dockerfile", "bytes": "9788" }, { "name": "HTML", "bytes": "86821" }, { "name": "Java", "bytes": "42052018" }, { "name": "JavaScript", "bytes": "8267" }, { "name": "Python", "bytes": "249644" }, { "name": "Scala", "bytes": "8365242" }, { "name": "Shell", "bytes": "398033" } ], "symlink_target": "" }
#include "config.h" #if USE(3D_GRAPHICS) || defined(QT_OPENGL_SHIMS) #define DISABLE_SHIMS #include "OpenGLShims.h" #if !PLATFORM(QT) && !PLATFORM(WIN) #include <dlfcn.h> #endif #if PLATFORM(NIX) && USE(EGL) #include <EGL/egl.h> #endif #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> namespace WebCore { OpenGLFunctionTable* openGLFunctionTable() { static OpenGLFunctionTable table; return &table; } #if PLATFORM(QT) static void* getProcAddress(const char* procName) { if (QOpenGLContext* context = QOpenGLContext::currentContext()) return reinterpret_cast<void*>(context->getProcAddress(procName)); return 0; } #elif PLATFORM(WIN) static void* getProcAddress(const char* procName) { return GetProcAddress(GetModuleHandleA("libGLESv2"), procName); } #elif PLATFORM(NIX) && USE(EGL) static void* getProcAddress(const char* procName) { return reinterpret_cast<void*>(eglGetProcAddress(procName)); } #else typedef void* (*glGetProcAddressType) (const char* procName); static void* getProcAddress(const char* procName) { static bool initialized = false; static glGetProcAddressType getProcAddressFunction = 0; if (!initialized) { getProcAddressFunction = reinterpret_cast<glGetProcAddressType>(dlsym(RTLD_DEFAULT, "glXGetProcAddress")); if (!getProcAddressFunction) getProcAddressFunction = reinterpret_cast<glGetProcAddressType>(dlsym(RTLD_DEFAULT, "glXGetProcAddressARB")); } if (!getProcAddressFunction) return dlsym(RTLD_DEFAULT, procName); return getProcAddressFunction(procName); } #endif static void* lookupOpenGLFunctionAddress(const char* functionName, bool* success = 0) { if (success && !*success) return 0; void* target = getProcAddress(functionName); if (target) return target; String fullFunctionName(functionName); fullFunctionName.append("ARB"); target = getProcAddress(fullFunctionName.utf8().data()); if (target) return target; fullFunctionName = functionName; fullFunctionName.append("EXT"); target = getProcAddress(fullFunctionName.utf8().data()); #if defined(GL_ES_VERSION_2_0) fullFunctionName = functionName; fullFunctionName.append("ANGLE"); target = getProcAddress(fullFunctionName.utf8().data()); if (target) return target; fullFunctionName = functionName; fullFunctionName.append("APPLE"); target = getProcAddress(fullFunctionName.utf8().data()); #endif // A null address is still a failure case. if (!target && success) *success = false; return target; } #if (PLATFORM(QT) && defined(QT_OPENGL_ES_2)) || (PLATFORM(NIX) && USE(OPENGL_ES_2)) // With Angle only EGL/GLES2 extensions are available through eglGetProcAddress, not the regular standardized functions. #define ASSIGN_FUNCTION_TABLE_ENTRY(FunctionName, success) \ openGLFunctionTable()->FunctionName = reinterpret_cast<FunctionName##Type>(::FunctionName) #else #define ASSIGN_FUNCTION_TABLE_ENTRY(FunctionName, success) \ openGLFunctionTable()->FunctionName = reinterpret_cast<FunctionName##Type>(lookupOpenGLFunctionAddress(#FunctionName, &success)) #endif #define ASSIGN_FUNCTION_TABLE_ENTRY_EXT(FunctionName) \ openGLFunctionTable()->FunctionName = reinterpret_cast<FunctionName##Type>(lookupOpenGLFunctionAddress(#FunctionName)) bool initializeOpenGLShims() { static bool success = true; static bool initialized = false; if (initialized) return success; initialized = true; ASSIGN_FUNCTION_TABLE_ENTRY(glActiveTexture, success); ASSIGN_FUNCTION_TABLE_ENTRY(glAttachShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindAttribLocation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindBuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindFramebuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindRenderbuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glBindVertexArray); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendColor, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendEquation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendEquationSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendFuncSeparate, success); // In GLES2 there is optional an ANGLE extension for glBlitFramebuffer #if defined(GL_ES_VERSION_2_0) ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glBlitFramebuffer); #else ASSIGN_FUNCTION_TABLE_ENTRY(glBlitFramebuffer, success); #endif ASSIGN_FUNCTION_TABLE_ENTRY(glBufferData, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBufferSubData, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCheckFramebufferStatus, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCompileShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCompressedTexImage2D, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCompressedTexSubImage2D, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCreateProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCreateShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteBuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteFramebuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteRenderbuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteShader, success); ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glDeleteVertexArrays); ASSIGN_FUNCTION_TABLE_ENTRY(glDetachShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDisableVertexAttribArray, success); ASSIGN_FUNCTION_TABLE_ENTRY(glEnableVertexAttribArray, success); ASSIGN_FUNCTION_TABLE_ENTRY(glFramebufferRenderbuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glFramebufferTexture2D, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenBuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenerateMipmap, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenFramebuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenRenderbuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glGenVertexArrays); ASSIGN_FUNCTION_TABLE_ENTRY(glGetActiveAttrib, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetActiveUniform, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetAttachedShaders, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetAttribLocation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetBufferParameteriv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetFramebufferAttachmentParameteriv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetProgramInfoLog, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetProgramiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetRenderbufferParameteriv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetShaderInfoLog, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetShaderiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetShaderSource, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetUniformfv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetUniformiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetUniformLocation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetVertexAttribfv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetVertexAttribiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetVertexAttribPointerv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsBuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsFramebuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsRenderbuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsShader, success); ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glIsVertexArray); ASSIGN_FUNCTION_TABLE_ENTRY(glLinkProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glRenderbufferStorage, success); // In GLES2 there are optional ANGLE and APPLE extensions for glRenderbufferStorageMultisample. #if defined(GL_ES_VERSION_2_0) ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glRenderbufferStorageMultisample); #else ASSIGN_FUNCTION_TABLE_ENTRY(glRenderbufferStorageMultisample, success); #endif ASSIGN_FUNCTION_TABLE_ENTRY(glSampleCoverage, success); ASSIGN_FUNCTION_TABLE_ENTRY(glShaderSource, success); ASSIGN_FUNCTION_TABLE_ENTRY(glStencilFuncSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glStencilMaskSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glStencilOpSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniformMatrix2fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniformMatrix3fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniformMatrix4fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUseProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glValidateProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib1f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib1fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib2f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib2fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib3f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib3fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib4f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib4fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttribPointer, success); if (!success) LOG_ERROR("Could not initialize OpenGL shims"); return success; } } // namespace WebCore #endif // USE(3D_GRAPHICS)
{ "content_hash": "841dd7607a1e4a2144abec640726f1fb", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 132, "avg_line_length": 41.425619834710744, "alnum_prop": 0.7605985037406484, "repo_name": "klim-iv/phantomjs-qt5", "id": "6a03bfe60000457bf7bcdff107ee13dc2d188b20", "size": "10821", "binary": false, "copies": "1", "ref": "refs/heads/qt5", "path": "src/webkit/Source/WebCore/platform/graphics/OpenGLShims.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "291913" }, { "name": "Awk", "bytes": "3965" }, { "name": "C", "bytes": "42431954" }, { "name": "C++", "bytes": "128347641" }, { "name": "CSS", "bytes": "778535" }, { "name": "CoffeeScript", "bytes": "46367" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "8191" }, { "name": "IDL", "bytes": "191984" }, { "name": "Java", "bytes": "232840" }, { "name": "JavaScript", "bytes": "16127527" }, { "name": "Objective-C", "bytes": "10465655" }, { "name": "PHP", "bytes": "1223" }, { "name": "Perl", "bytes": "1296504" }, { "name": "Python", "bytes": "5916339" }, { "name": "Ruby", "bytes": "381483" }, { "name": "Shell", "bytes": "1005210" }, { "name": "Smalltalk", "bytes": "1308" }, { "name": "VimL", "bytes": "3731" }, { "name": "XSLT", "bytes": "50637" } ], "symlink_target": "" }
Version 0.13 ------------ - `skimage.filter` has been removed. Use `skimage.filters` instead. - `skimage.filters.canny` has been removed. `canny` is available only from `skimage.feature` now. - Deprecated filters `hsobel`, `vsobel`, `hscharr`, `vscharr`, `hprewitt`, `vprewitt`, `roberts_positive_diagonal`, `roberts_negative_diagonal` have been removed from `skimage.filters.edges`. - The `sigma` parameter of `skimage.filters.gaussian` and the `selem` parameter of `skimage.filters.median` have been made optional, with default values. - The `clip_negative` parameter of `skimage.util.dtype_limits` is now set to `None` by default, equivalent to `True`, the former value. In version 0.15, will be set to `False`. - The `circle` parameter of `skimage.transform.radon` and `skimage.transform.iradon` are now set to `None` by default, equivalent to `False`, the former value. In version 0.15, will be set to `True`. Version 0.12 ------------ - ``equalize_adapthist`` now takes a ``kernel_size`` keyword argument, replacing the ``ntiles_*`` arguments. - The functions ``blob_dog``, ``blob_log`` and ``blob_doh`` now return float arrays instead of integer arrays. - ``transform.integrate`` now takes lists of tuples instead of integers to define the window over which to integrate. - `reverse_map` parameter in `skimage.transform.warp` has been removed. - `enforce_connectivity` in `skimage.segmentation.slic` defaults to ``True``. - `skimage.measure.fit.BaseModel._params`, `skimage.transform.ProjectiveTransform._matrix`, `skimage.transform.PolynomialTransform._params`, `skimage.transform.PiecewiseAffineTransform.affines_*` attributes have been removed. - `skimage.filters.denoise_*` have moved to `skimage.restoration.denoise_*`. - `skimage.data.lena` has been removed. Version 0.11 ------------ - The ``skimage.filter`` subpackage has been renamed to ``skimage.filters``. - Some edge detectors returned values greater than 1--their results are now appropriately scaled with a factor of ``sqrt(2)``. Version 0.10 ------------ - Removed ``skimage.io.video`` functionality due to broken gstreamer bindings Version 0.9 ----------- - No longer wrap ``imread`` output in an ``Image`` class - Change default value of `sigma` parameter in ``skimage.segmentation.slic`` to 0 - ``hough_circle`` now returns a stack of arrays that are the same size as the input image. Set the ``full_output`` flag to True for the old behavior. - The following functions were deprecated over two releases: `skimage.filter.denoise_tv_chambolle`, `skimage.morphology.is_local_maximum`, `skimage.transform.hough`, `skimage.transform.probabilistic_hough`,`skimage.transform.hough_peaks`. Their functionality still exists, but under different names. Version 0.4 ----------- - Switch mask and radius arguments for ``median_filter`` Version 0.3 ----------- - Remove ``as_grey``, ``dtype`` keyword from ImageCollection - Remove ``dtype`` from imread - Generalise ImageCollection to accept a load_func
{ "content_hash": "22ea02c065d249200ab1c5941a6eaba5", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 87, "avg_line_length": 44.411764705882355, "alnum_prop": 0.723841059602649, "repo_name": "vighneshbirodkar/scikit-image", "id": "2b8c7a49f0fc13c83f7c1c1c6a1a5969fdf90603", "size": "3020", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/source/api_changes.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "235642" }, { "name": "C++", "bytes": "44817" }, { "name": "Makefile", "bytes": "567" }, { "name": "Python", "bytes": "2518884" } ], "symlink_target": "" }
@interface ViewController ()<UITextViewDelegate,UITextFieldDelegate> @property (weak, nonatomic) IBOutlet UITextField *tFeild; @property (weak, nonatomic) IBOutlet UITextView *tView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.tFeild.delegate = self; self.tView.delegate = self; [self.tFeild addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; } // 💗UITextField的字符数限定方法 - (void)textFieldDidChange:(id) sender { UITextField *_field = (UITextField *)sender; NSString *str = _field.text; if (str.length > MAXINPUTNUM) { [_field setTextAndKeepCursor:str withLength:MAXINPUTNUM]; } [_field becomeFirstResponder]; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ if (textField == self.tFeild) { if (string.length == 0) {// ->用于实现删除 return YES; } // ->已存在的字符长度 NSInteger existedLength = textField.text.length; // ->已有字符长度+1的location处的长度 NSInteger selectedLength = range.length; // ->即将输入的字符长度 NSInteger replaceLength = string.length; if (existedLength - selectedLength + replaceLength > MAXINPUTNUM) { return NO; } } return YES; } // 💗UITextView的字符数限定方法 - (void)textViewDidChange:(UITextView *)textView{ if (textView.text.length > MAXINPUTNUM) { [textView setTextAndKeepCursor:textView.text withLength:MAXINPUTNUM]; } [textView becomeFirstResponder]; } - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ if ([@"\n" isEqualToString:text]) { [textView resignFirstResponder]; return NO; } if (textView == self.tView) { if (text.length == 0) {// ->用于实现删除 return YES; } // ->已存在的字符长度 NSInteger existedLength = textView.text.length; // ->已有字符长度+1的location处的长度 NSInteger selectedLength = range.length; // ->即将输入的字符长度 NSInteger replaceLength = text.length; if (existedLength - selectedLength + replaceLength > MAXINPUTNUM) { return NO; } } return YES; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self.tView resignFirstResponder]; [self.tFeild resignFirstResponder]; } - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self.tView resignFirstResponder]; [self.tFeild resignFirstResponder]; } @end
{ "content_hash": "ac4a73ac353223d26ad630e93e2bf6a9", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 125, "avg_line_length": 29.0625, "alnum_prop": 0.6587813620071684, "repo_name": "BruceFight/JHB_LimitInputTrain", "id": "acb6ee0ce733d1e350362a811ef7184b047b6961", "size": "3231", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JHB_LimitInputTrain/ViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "12376" } ], "symlink_target": "" }
import { deleteCrawler } from "../../../actions/delete-crawler.js"; import { log } from "../log.js"; /** snippet-start:[javascript.v3.glue.scenarios.basic.CleanUpCrawler] */ const cleanUpCrawlerStep = async (context) => { log(`Deleting crawler.`); try { await deleteCrawler(process.env.CRAWLER_NAME); log("Crawler deleted.", { type: "success" }); } catch (err) { if (err.name === "EntityNotFoundException") { log(`Crawler is already deleted.`); } else { throw err; } } return { ...context }; }; /** snippet-end:[javascript.v3.glue.scenarios.basic.CleanUpCrawler] */ export { cleanUpCrawlerStep };
{ "content_hash": "6ce0678a7ec75ff81b72374718868ed4", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 25.8, "alnum_prop": 0.6372093023255814, "repo_name": "awsdocs/aws-doc-sdk-examples", "id": "c7675d03f502b05fbe4e0e50166cea50d1e5bb8f", "size": "760", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-crawler.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "476653" }, { "name": "Batchfile", "bytes": "900" }, { "name": "C", "bytes": "3852" }, { "name": "C#", "bytes": "2051923" }, { "name": "C++", "bytes": "943634" }, { "name": "CMake", "bytes": "82068" }, { "name": "CSS", "bytes": "33378" }, { "name": "Dockerfile", "bytes": "2243" }, { "name": "Go", "bytes": "1764292" }, { "name": "HTML", "bytes": "319090" }, { "name": "Java", "bytes": "4966853" }, { "name": "JavaScript", "bytes": "1655476" }, { "name": "Jupyter Notebook", "bytes": "9749" }, { "name": "Kotlin", "bytes": "1099902" }, { "name": "Makefile", "bytes": "4922" }, { "name": "PHP", "bytes": "1220594" }, { "name": "Python", "bytes": "2507509" }, { "name": "Ruby", "bytes": "500331" }, { "name": "Rust", "bytes": "558811" }, { "name": "Shell", "bytes": "63776" }, { "name": "Swift", "bytes": "267325" }, { "name": "TypeScript", "bytes": "119632" } ], "symlink_target": "" }
using namespace BloombergLP; int main() { bslstl::StringRef defref; bsl::cout << defref << "\n"; bsl::string str = "This is a string"; bslstl::StringRef strref(str.begin(), str.end()); bsl::cout << strref << "\n"; bsl::cout << "Done\n"; }
{ "content_hash": "38ce014de6961190b109427440ebbd03", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 53, "avg_line_length": 20.46153846153846, "alnum_prop": 0.575187969924812, "repo_name": "bloomberg/bde-tools", "id": "09400551d50e9a5aea6369575a46a993c12cbeb6", "size": "347", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "contrib/gdb-printers/test/test_stringref.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1280" }, { "name": "C++", "bytes": "8163" }, { "name": "CMake", "bytes": "320782" }, { "name": "Emacs Lisp", "bytes": "8245" }, { "name": "Makefile", "bytes": "288" }, { "name": "Perl", "bytes": "614447" }, { "name": "Python", "bytes": "284097" }, { "name": "Shell", "bytes": "27318" } ], "symlink_target": "" }
Android-Google-Cloud-Messaging ============================== A sample application that demonstrates how to create a client app for Google Cloud Messaging using Android SDK. This example is based on Android SDK guides, but i'm adding some refactors and making more easy to understand.
{ "content_hash": "340ad93b1b800e1bc78154b63e91e39d", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 222, "avg_line_length": 71.5, "alnum_prop": 0.7307692307692307, "repo_name": "nRike/Android-Google-Cloud-Messaging", "id": "6b26d1577a3ea9084cf38997210ffe15f1cc343c", "size": "286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "16913" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <title></title> <!--<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0.1/fabric.min.css"> <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0.1/fabric.components.min.css">--> </head> <body> <div id="editionInfo" class="ms-Callout ms-Callout--arrowLeft" style="position:relative;top:-15px; font-family: Segoe UI Light"> <div class="ms-Callout-main" style="box-shadow: 0 0 0 0"> <div class="ms-Callout-header"> <p class="ms-Callout-title" style="font-weight: bold">Office Client Edition</p> </div> <div class="ms-Callout-inner"> <div class="ms-Callout-content"> <p class="ms-Callout-subText">Required. Specifies the edition of Click-to-Run for Office 365 product to use: 32- or 64-bit. The action fails if <strong>OfficeClientEdition</strong> is not set to a valid value.</p> <br> <p class="ms-Callout-subText">A <strong>configure</strong> mode action may fail if <strong>OfficeClientEdition</strong> is set incorrectly. For example, if you attempt to install a 64-bit edition of a Click-to-Run for Office 365 product on a computer that is running a 32-bit Windows operating system, or if you try to install a 32-bit Click-to-Run for Office 365 product on a computer that has a 64-bit edition of Office installed.</p> </div> </div> </div> </div> </body> </html>
{ "content_hash": "1d2b9abd6a4bfabf3cf80f6d51b88517", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 460, "avg_line_length": 65.34615384615384, "alnum_prop": 0.6215420835785757, "repo_name": "OfficeDev/Office-IT-Pro-Deployment-Scripts", "id": "257021a83e4650d9436bb01498cbc299f8f06ef4", "size": "1701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Office-ProPlus-Deployment/Microsoft.ProPlus.InstallGenerator/InstallGenWPF/HelpFiles/EditionInfo.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "420" }, { "name": "Batchfile", "bytes": "2830" }, { "name": "C", "bytes": "1364728" }, { "name": "C#", "bytes": "2408602" }, { "name": "C++", "bytes": "203990" }, { "name": "CSS", "bytes": "614538" }, { "name": "HTML", "bytes": "749349" }, { "name": "JavaScript", "bytes": "828377" }, { "name": "Objective-C", "bytes": "82768" }, { "name": "Pascal", "bytes": "32537" }, { "name": "PowerShell", "bytes": "3513423" }, { "name": "R", "bytes": "34567" }, { "name": "Visual Basic", "bytes": "9214349" }, { "name": "XSLT", "bytes": "13178" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Refactored date examples</title> <link rel="stylesheet" href="//code.jquery.com/qunit/qunit-1.18.0.css"> <script src="//code.jquery.com/qunit/qunit-1.18.0.js"></script> <script src="js/jquery.js"></script> <script src="js/indiana.js"></script> <script> QUnit.test("getThingPosition2DinDegree returns 5", function( assert ) { assert.equal(indiana.getThingPosition2DinDegree(), 5); }); QUnit.test("Test if Register and Dispatch event trigger registered function", function( assert ) { $('body').append("<div id='target'></div>"); // $('body').append("<div id='testdiv'></div>"); var okstring = 'OK'; registerThingEvent('target', function() { $('#target').text(okstring); }); //indiana should have initialized event listeners indiana.initializeEventListeners(); indiana.dispatchSpatialFocusEvent('target'); assert.equal($('#target').html(), okstring); $('#target').remove(); }); </script> </head> <body> <div id="qunit"></div> </body> </html>
{ "content_hash": "cd2d19f07c949e9976cf7d99a831b4cc", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 100, "avg_line_length": 24.2, "alnum_prop": 0.6400367309458218, "repo_name": "frostyandy2k/iot-compass", "id": "dfd0ea8df255cde3ae57ff2988a60c308e0bd30c", "size": "1089", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/indiana-test.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29364" }, { "name": "HTML", "bytes": "143007" }, { "name": "JavaScript", "bytes": "43805" } ], "symlink_target": "" }
title: Prendre des notes avec Vim (et android) permalink: notes_vim_et_android layout: post date: 2017-06-12 tags: [linux, vim] --- Cela faisait longtemps que je cherchais un moyen simple et efficace pour rédiger des notes, des memos et autres TODO lists synchronisées à la fois sur téléphone et editables avec mon editeur préféré ordinateur. ![img]({{ site.baseurl }}/images/notes_vim_android/iA.png) # Premiers essais avec Evernote et Google Keep Sur android les app pour ces deux solutions sont bien conçues, rien à dire. C'est sur ordinateur que je n'ai pas été seduit. Il n'y a pas de client officiel sous linux. On ne peut que se rabatte sur le module firefox ou chrome. Après quelques semaines d'utilisation, j'ai abandonné ces solutions car elles utilisent des formats specifiques et ne me permettaient pas de modifier les fichiers avec un editeur de texte comme gedit ou vim sauf à faire des copier-coller manuellement. # Définition des besoins Les avantages et inconvénients des solutions précédentes, m'ont conduit à la liste des besoins suivants : * sauvegarde des notes au format texte * editeur disposant d'une police monospace (alignements plus faciles) * possibilité de visualiser les notes écrites en markdown * synchronisation sur un cloud * disponible et stable sous linux * disponible et efficace sous android # Dropbox, Vim et iA Writer Sous linux, le client de synchronisation est très simple à installer et il est d'une remarquable stabilité. Ecrire des notes sous n'importe quel editeur de texte ne pose donc aucun problème et les documents sont synchronisés avec le cloud quasi-instantanément à la sauvegarde. La difficulté se situe sur le téléphone. Il faut un éditeur de texte efficace et qui gère bien la synchronisation avec dropbox. Après avoir testé plain qui ne dispose pas de police monospace j'ai passé un peu de temps avec JotterPad qui est très bon dans sa version payante (environ 5€). Finalement, j'ai choisi iA Writer qui répond à tous les critères et dispose en plus d'un raccourci pour créer et utiliser des todo lists comme celle-ci - [x] écrire un article - [ ] publier un article
{ "content_hash": "c1eba9b7a7a61953451bb1fa267346aa", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 79, "avg_line_length": 37.719298245614034, "alnum_prop": 0.7869767441860465, "repo_name": "nicolaspoulain/nicolaspoulain.github.io", "id": "c68c98db65b551315da1a942b5876ef3311ddf8d", "size": "2199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-06-15-notes_vim_android.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "2601" }, { "name": "CSS", "bytes": "70805" }, { "name": "HTML", "bytes": "19620" }, { "name": "TeX", "bytes": "3094" } ], "symlink_target": "" }
namespace Microsoft.Azure.Management.RecoveryServices.Backup.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Azure.Management.RecoveryServices.Backup; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Base class for backup item. Workload-specific backup items are derived /// from this class. /// </summary> public partial class WorkloadProtectableItemResource : Resource { /// <summary> /// Initializes a new instance of the WorkloadProtectableItemResource /// class. /// </summary> public WorkloadProtectableItemResource() { CustomInit(); } /// <summary> /// Initializes a new instance of the WorkloadProtectableItemResource /// class. /// </summary> /// <param name="id">Resource Id represents the complete path to the /// resource.</param> /// <param name="name">Resource name associated with the /// resource.</param> /// <param name="type">Resource type represents the complete path of /// the form Namespace/ResourceType/ResourceType/...</param> /// <param name="location">Resource location.</param> /// <param name="tags">Resource tags.</param> /// <param name="eTag">Optional ETag.</param> /// <param name="properties">WorkloadProtectableItemResource /// properties</param> public WorkloadProtectableItemResource(string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string eTag = default(string), WorkloadProtectableItem properties = default(WorkloadProtectableItem)) : base(id, name, type, location, tags, eTag) { Properties = properties; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets workloadProtectableItemResource properties /// </summary> [JsonProperty(PropertyName = "properties")] public WorkloadProtectableItem Properties { get; set; } } }
{ "content_hash": "1f5e6ce2066cccbcfbd737d2d5bc7ece", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 347, "avg_line_length": 40.67213114754098, "alnum_prop": 0.6436920596533656, "repo_name": "AzureAutomationTeam/azure-sdk-for-net", "id": "2f9f03a6d7dbf4a184233d1e363a7667bb66be96", "size": "2793", "binary": false, "copies": "9", "ref": "refs/heads/psSdkJson6", "path": "src/SDKs/RecoveryServices.Backup/Management.RecoveryServices.Backup/Generated/Models/WorkloadProtectableItemResource.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "Batchfile", "bytes": "19041" }, { "name": "C#", "bytes": "80818733" }, { "name": "CSS", "bytes": "685" }, { "name": "JavaScript", "bytes": "7875" }, { "name": "PowerShell", "bytes": "30922" }, { "name": "Shell", "bytes": "10166" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
package org.assertj.core.api.longarray; import static junit.framework.Assert.assertSame; import static org.mockito.MockitoAnnotations.initMocks; import java.util.Comparator; import org.assertj.core.api.LongArrayAssert; import org.assertj.core.api.LongArrayAssertBaseTest; import org.assertj.core.internal.LongArrays; import org.junit.Before; import org.mockito.Mock; /** * Tests for <code>{@link LongArrayAssert#usingComparator(java.util.Comparator)}</code>. * * @author Joel Costigliola * @author Mikhail Mazursky */ public class LongArrayAssert_usingComparator_Test extends LongArrayAssertBaseTest { @Mock private Comparator<long[]> comparator; private LongArrays arraysBefore; @Before public void before() { initMocks(this); arraysBefore = getArrays(assertions); } @Override protected LongArrayAssert invoke_api_method() { // in that test, the comparator type is not important, we only check that we correctly switch of comparator return assertions.usingComparator(comparator); } @Override protected void verify_internal_effects() { assertSame(getObjects(assertions).getComparator(), comparator); assertSame(getArrays(assertions), arraysBefore); } }
{ "content_hash": "8d25be0026a544d7bb7ea2e93e515682", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 111, "avg_line_length": 26.47826086956522, "alnum_prop": 0.7668308702791461, "repo_name": "yurloc/assertj-core", "id": "5a0ac3a7584c1f8f628cabbb780f8fe6bc44392f", "size": "1859", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/assertj/core/api/longarray/LongArrayAssert_usingComparator_Test.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef HERON_API_TOPOLOGY_OUTPUT_FIELDS_DECLARER_H_ #define HERON_API_TOPOLOGY_OUTPUT_FIELDS_DECLARER_H_ #include <string> #include "tuple/fields.h" namespace heron { namespace api { namespace topology { class OutputFieldsDeclarer { public: /** * Uses default stream id. */ virtual void declare(const tuple::Fields& fields) = 0; virtual void declareStream(const std::string& streamId, const tuple::Fields& fields) = 0; }; } // namespace topology } // namespace api } // namespace heron #endif // HERON_API_TOPOLOGY_OUTPUT_FIELDS_DECLARER_H_
{ "content_hash": "fe8c7b470f769cc4ff1bf655e39a5aba", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 91, "avg_line_length": 20.285714285714285, "alnum_prop": 0.7147887323943662, "repo_name": "lucperkins/heron", "id": "16a38a5180b22190beb66f334343f3d5fd402da7", "size": "1162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "heron/api/src/cpp/topology/output-fields-declarer.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11709" }, { "name": "C++", "bytes": "1623239" }, { "name": "CSS", "bytes": "109554" }, { "name": "HCL", "bytes": "2115" }, { "name": "HTML", "bytes": "156820" }, { "name": "Java", "bytes": "4466689" }, { "name": "JavaScript", "bytes": "1110981" }, { "name": "M4", "bytes": "17941" }, { "name": "Makefile", "bytes": "1046" }, { "name": "Objective-C", "bytes": "1929" }, { "name": "Python", "bytes": "1537910" }, { "name": "Ruby", "bytes": "1930" }, { "name": "Scala", "bytes": "72781" }, { "name": "Shell", "bytes": "166876" }, { "name": "Smarty", "bytes": "528" }, { "name": "Thrift", "bytes": "915" } ], "symlink_target": "" }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <!-- //********************************************************* // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language // governing permissions and limitations under the License. //********************************************************* --> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btn_auth" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="callOAuth" android:text="@string/btn_auth" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="35dp" android:gravity="center_horizontal" android:orientation="horizontal" > <TextView android:id="@+id/txtView_Auth" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:text="@string/auth_no" android:textAlignment="center" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="horizontal" > <EditText android:id="@+id/sectionName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="text" android:hint="@string/sectionNameHint" android:ems="10" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btn_sendHTML" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:layout_weight="1" android:onClick="btn_sendHTML_onClick" android:text="@string/btn_sendHTML" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:orientation="horizontal"> <Button android:id="@+id/btn_sendImg" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_sendImg_onClick" android:text="@string/btn_sendImg" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:orientation="horizontal" > <Button android:id="@+id/btn_sendEmbeddedHTML" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_sendEmbeddedHTML_onClick" android:text="@string/btn_sendEmbeddedHTML" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:orientation="horizontal" > <Button android:id="@+id/btn_sendURL" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_sendURL_onClick" android:text="@string/btn_sendURL" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:orientation="horizontal" > <Button android:id="@+id/btn_createPageWithAttachmentAndPdfRendering" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_sendAttachmentWithPdfRendering_onClick" android:text="@string/btn_sendAttachmentWithPdfRendering" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:orientation="horizontal" > <Button android:id="@+id/btn_signout" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_signout_onClick" android:text="@string/btn_signout" /> </LinearLayout> <TextView android:id="@+id/tvStatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/txtView_Status" /> </LinearLayout>
{ "content_hash": "d2163eca3bd8dc67b31a3a5d88ff95ba", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 74, "avg_line_length": 36.25433526011561, "alnum_prop": 0.6151147959183674, "repo_name": "OneNoteDev/OneNoteAPISampleAndroid", "id": "6472c1e4c0dd0469c1f46db337cd473935a263f1", "size": "6272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OneNoteServiceCreatePageExample/res/layout/activity_main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "47263" } ], "symlink_target": "" }
package org.apache.hadoop.hive.ql.exec.vector.expressions; import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor; import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor.Descriptor; /** * Vectorized implementation of trunc(number) function for float/double input */ public class TruncFloatNoScale extends TruncFloat { private static final long serialVersionUID = 1L; public TruncFloatNoScale() { super(); } public TruncFloatNoScale(int colNum, int outputColumnNum) { super(colNum, 0, outputColumnNum); } @Override public Descriptor getDescriptor() { VectorExpressionDescriptor.Builder b = new VectorExpressionDescriptor.Builder(); b.setMode(VectorExpressionDescriptor.Mode.PROJECTION).setNumArguments(1) .setArgumentTypes(getInputColumnType()) .setInputExpressionTypes(VectorExpressionDescriptor.InputExpressionType.COLUMN); return b.build(); } }
{ "content_hash": "17b3933e5fc7b7da164a4c3ac9d0d77c", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 88, "avg_line_length": 31.4, "alnum_prop": 0.7749469214437368, "repo_name": "sankarh/hive", "id": "abe1a096d1e1e1e85d8cba5a16bea3e78088dca6", "size": "1747", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ql/src/java/org/apache/hadoop/hive/ql/exec/vector/expressions/TruncFloatNoScale.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "55440" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "96657" }, { "name": "CSS", "bytes": "4742" }, { "name": "GAP", "bytes": "204254" }, { "name": "HTML", "bytes": "24102" }, { "name": "HiveQL", "bytes": "8290287" }, { "name": "Java", "bytes": "59285075" }, { "name": "JavaScript", "bytes": "44139" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "9105" }, { "name": "PLpgSQL", "bytes": "294996" }, { "name": "Perl", "bytes": "319742" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "383647" }, { "name": "ReScript", "bytes": "3460" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "1190" }, { "name": "Shell", "bytes": "271549" }, { "name": "TSQL", "bytes": "14126" }, { "name": "Thrift", "bytes": "164235" }, { "name": "XSLT", "bytes": "1329" }, { "name": "q", "bytes": "289182" } ], "symlink_target": "" }
package io.vertx.blueprint.microservice.cart; import io.vertx.blueprint.microservice.product.ProductTuple; import io.vertx.codegen.annotations.DataObject; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; /** * Shopping cart state object. */ @DataObject(generateConverter = true) public class ShoppingCart { private List<ProductTuple> productItems = new ArrayList<>(); private Map<String, Integer> amountMap = new HashMap<>(); public ShoppingCart() { // Empty constructor. } public ShoppingCart(JsonObject json) { ShoppingCartConverter.fromJson(json, this); } public JsonObject toJson() { JsonObject json = new JsonObject(); ShoppingCartConverter.toJson(this, json); return json; } public List<ProductTuple> getProductItems() { return productItems; } public ShoppingCart setProductItems(List<ProductTuple> productItems) { this.productItems = productItems; return this; } @GenIgnore public Map<String, Integer> getAmountMap() { return amountMap; } public boolean isEmpty() { return productItems.isEmpty(); } public ShoppingCart incorporate(CartEvent cartEvent) { // The cart event must be a add or remove command event. boolean ifValid = Stream.of(CartEventType.ADD_ITEM, CartEventType.REMOVE_ITEM) .anyMatch(cartEventType -> cartEvent.getCartEventType().equals(cartEventType)); if (ifValid) { amountMap.put(cartEvent.getProductId(), amountMap.getOrDefault(cartEvent.getProductId(), 0) + (cartEvent.getAmount() * (cartEvent.getCartEventType() .equals(CartEventType.ADD_ITEM) ? 1 : -1))); } return this; } @Override public String toString() { return this.toJson().encode(); } }
{ "content_hash": "19e4887cf142f8ad194dee7468c24327", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 82, "avg_line_length": 25.56, "alnum_prop": 0.711528429838289, "repo_name": "sczyh30/vertx-blueprint-microservice", "id": "4d788a3cf6c868151013159f0e1c2264be3e1e07", "size": "1917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shopping-cart-microservice/src/main/java/io/vertx/blueprint/microservice/cart/ShoppingCart.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2329" }, { "name": "HTML", "bytes": "20461" }, { "name": "Java", "bytes": "326933" }, { "name": "JavaScript", "bytes": "14812" }, { "name": "Shell", "bytes": "1583" } ], "symlink_target": "" }
package org.camunda.bpm.engine.test; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.camunda.bpm.engine.AuthorizationService; import org.camunda.bpm.engine.CaseService; import org.camunda.bpm.engine.DecisionService; import org.camunda.bpm.engine.ExternalTaskService; import org.camunda.bpm.engine.FilterService; import org.camunda.bpm.engine.FormService; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.IdentityService; import org.camunda.bpm.engine.ManagementService; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.ProcessEngineServices; import org.camunda.bpm.engine.RepositoryService; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.impl.ProcessEngineImpl; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.telemetry.PlatformTelemetryRegistry; import org.camunda.bpm.engine.impl.test.RequiredDatabase; import org.camunda.bpm.engine.impl.test.TestHelper; import org.camunda.bpm.engine.impl.util.ClockUtil; import org.junit.Assume; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * Convenience for ProcessEngine and services initialization in the form of a * JUnit rule. * <p> * Usage: * </p> * * <pre> * public class YourTest { * * &#64;Rule * public ProcessEngineRule processEngineRule = new ProcessEngineRule(); * * ... * } * </pre> * <p> * The ProcessEngine and the services will be made available to the test class * through the getters of the processEngineRule. The processEngine will be * initialized by default with the camunda.cfg.xml resource on the classpath. To * specify a different configuration file, pass the resource location in * {@link #ProcessEngineRule(String) the appropriate constructor}. Process * engines will be cached statically. Right before the first time the setUp is * called for a given configuration resource, the process engine will be * constructed. * </p> * <p> * You can declare a deployment with the {@link Deployment} annotation. This * base class will make sure that this deployment gets deployed before the setUp * and {@link RepositoryService#deleteDeployment(String, boolean) cascade * deleted} after the tearDown. If you add a deployment programmatically in your * test, you have to make it known to the processEngineRule by calling * {@link ProcessEngineRule#manageDeployment(org.camunda.bpm.engine.repository.Deployment)} * to have it cleaned up automatically. * </p> * <p> * The processEngineRule also lets you * {@link ProcessEngineRule#setCurrentTime(Date) set the current time used by * the process engine}. This can be handy to control the exact time that is used * by the engine in order to verify e.g., due dates of timers. Or start, end * and duration times in the history service. In the tearDown, the internal * clock will automatically be reset to use the current system time rather then * the time that was set during a test method. In other words, you don't have to * clean up your own time messing mess ;-) * </p> * <p> * If you need the history service for your tests then you can specify the * required history level of the test method or class, using the * {@link RequiredHistoryLevel} annotation. If the current history level of the * process engine is lower than the specified one then the test is skipped. * </p> * * @author Tom Baeyens */ public class ProcessEngineRule extends TestWatcher implements ProcessEngineServices { protected String configurationResource = "camunda.cfg.xml"; protected String configurationResourceCompat = "activiti.cfg.xml"; protected String deploymentId = null; protected List<String> additionalDeployments = new ArrayList<>(); protected boolean ensureCleanAfterTest = false; protected ProcessEngine processEngine; protected ProcessEngineConfigurationImpl processEngineConfiguration; protected RepositoryService repositoryService; protected RuntimeService runtimeService; protected TaskService taskService; protected HistoryService historyService; protected IdentityService identityService; protected ManagementService managementService; protected FormService formService; protected FilterService filterService; protected AuthorizationService authorizationService; protected CaseService caseService; protected ExternalTaskService externalTaskService; protected DecisionService decisionService; public ProcessEngineRule() { this(false); } public ProcessEngineRule(boolean ensureCleanAfterTest) { this.ensureCleanAfterTest = ensureCleanAfterTest; } public ProcessEngineRule(String configurationResource) { this(configurationResource, false); } public ProcessEngineRule(String configurationResource, boolean ensureCleanAfterTest) { this.configurationResource = configurationResource; this.ensureCleanAfterTest = ensureCleanAfterTest; } public ProcessEngineRule(ProcessEngine processEngine) { this(processEngine, false); } public ProcessEngineRule(ProcessEngine processEngine, boolean ensureCleanAfterTest) { this.processEngine = processEngine; this.ensureCleanAfterTest = ensureCleanAfterTest; } @Override public void starting(Description description) { deploymentId = TestHelper.annotationDeploymentSetUp(processEngine, description.getTestClass(), description.getMethodName(), description.getAnnotation(Deployment.class)); } @Override public Statement apply(final Statement base, final Description description) { if (processEngine == null) { initializeProcessEngine(); } initializeServices(); Class<?> testClass = description.getTestClass(); String methodName = description.getMethodName(); RequiredHistoryLevel reqHistoryLevel = description.getAnnotation(RequiredHistoryLevel.class); boolean hasRequiredHistoryLevel = TestHelper.annotationRequiredHistoryLevelCheck(processEngine, reqHistoryLevel, testClass, methodName); RequiredDatabase requiredDatabase = description.getAnnotation(RequiredDatabase.class); boolean runsWithRequiredDatabase = TestHelper.annotationRequiredDatabaseCheck(processEngine, requiredDatabase, testClass, methodName); return new Statement() { @Override public void evaluate() throws Throwable { Assume.assumeTrue("ignored because the current history level is too low", hasRequiredHistoryLevel); Assume.assumeTrue("ignored because the database doesn't match the required ones", runsWithRequiredDatabase); ProcessEngineRule.super.apply(base, description).evaluate(); } }; } protected void initializeProcessEngine() { try { processEngine = TestHelper.getProcessEngine(configurationResource); } catch (RuntimeException ex) { if (ex.getCause() != null && ex.getCause() instanceof FileNotFoundException) { processEngine = TestHelper.getProcessEngine(configurationResourceCompat); } else { throw ex; } } } protected void initializeServices() { processEngineConfiguration = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration(); repositoryService = processEngine.getRepositoryService(); runtimeService = processEngine.getRuntimeService(); taskService = processEngine.getTaskService(); historyService = processEngine.getHistoryService(); identityService = processEngine.getIdentityService(); managementService = processEngine.getManagementService(); formService = processEngine.getFormService(); authorizationService = processEngine.getAuthorizationService(); caseService = processEngine.getCaseService(); filterService = processEngine.getFilterService(); externalTaskService = processEngine.getExternalTaskService(); decisionService = processEngine.getDecisionService(); } protected void clearServiceReferences() { processEngineConfiguration = null; repositoryService = null; runtimeService = null; taskService = null; formService = null; historyService = null; identityService = null; managementService = null; authorizationService = null; caseService = null; filterService = null; externalTaskService = null; decisionService = null; } @Override public void finished(Description description) { identityService.clearAuthentication(); processEngine.getProcessEngineConfiguration().setTenantCheckEnabled(true); TestHelper.annotationDeploymentTearDown(processEngine, deploymentId, description.getTestClass(), description.getMethodName()); for (String additionalDeployment : additionalDeployments) { TestHelper.deleteDeployment(processEngine, additionalDeployment); } if (ensureCleanAfterTest) { TestHelper.assertAndEnsureCleanDbAndCache(processEngine); } TestHelper.resetIdGenerator(processEngineConfiguration); ClockUtil.reset(); clearServiceReferences(); PlatformTelemetryRegistry.clear(); } public void setCurrentTime(Date currentTime) { ClockUtil.setCurrentTime(currentTime); } public String getConfigurationResource() { return configurationResource; } public void setConfigurationResource(String configurationResource) { this.configurationResource = configurationResource; } public ProcessEngine getProcessEngine() { return processEngine; } public void setProcessEngine(ProcessEngine processEngine) { this.processEngine = processEngine; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; } @Override public RepositoryService getRepositoryService() { return repositoryService; } public void setRepositoryService(RepositoryService repositoryService) { this.repositoryService = repositoryService; } @Override public RuntimeService getRuntimeService() { return runtimeService; } public void setRuntimeService(RuntimeService runtimeService) { this.runtimeService = runtimeService; } @Override public TaskService getTaskService() { return taskService; } public void setTaskService(TaskService taskService) { this.taskService = taskService; } @Override public HistoryService getHistoryService() { return historyService; } public void setHistoryService(HistoryService historyService) { this.historyService = historyService; } /** * @see #setHistoryService(HistoryService) * @param historicService * the historiy service instance */ public void setHistoricDataService(HistoryService historicService) { this.setHistoryService(historicService); } @Override public IdentityService getIdentityService() { return identityService; } public void setIdentityService(IdentityService identityService) { this.identityService = identityService; } @Override public ManagementService getManagementService() { return managementService; } @Override public AuthorizationService getAuthorizationService() { return authorizationService; } public void setAuthorizationService(AuthorizationService authorizationService) { this.authorizationService = authorizationService; } @Override public CaseService getCaseService() { return caseService; } public void setCaseService(CaseService caseService) { this.caseService = caseService; } @Override public FormService getFormService() { return formService; } public void setFormService(FormService formService) { this.formService = formService; } public void setManagementService(ManagementService managementService) { this.managementService = managementService; } @Override public FilterService getFilterService() { return filterService; } public void setFilterService(FilterService filterService) { this.filterService = filterService; } @Override public ExternalTaskService getExternalTaskService() { return externalTaskService; } public void setExternalTaskService(ExternalTaskService externalTaskService) { this.externalTaskService = externalTaskService; } @Override public DecisionService getDecisionService() { return decisionService; } public void setDecisionService(DecisionService decisionService) { this.decisionService = decisionService; } public void manageDeployment(org.camunda.bpm.engine.repository.Deployment deployment) { this.additionalDeployments.add(deployment.getId()); } }
{ "content_hash": "eacb516adbedac119d056c6a4e12ec37", "timestamp": "", "source": "github", "line_count": 391, "max_line_length": 130, "avg_line_length": 32.9462915601023, "alnum_prop": 0.7710759198882161, "repo_name": "ingorichtsmeier/camunda-bpm-platform", "id": "d828a66ffe4e27b94271e8957c5106006840b9fd", "size": "13689", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "engine/src/main/java/org/camunda/bpm/engine/test/ProcessEngineRule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8608" }, { "name": "CSS", "bytes": "5486" }, { "name": "Fluent", "bytes": "3111" }, { "name": "FreeMarker", "bytes": "1442812" }, { "name": "Groovy", "bytes": "1904" }, { "name": "HTML", "bytes": "961289" }, { "name": "Java", "bytes": "44047866" }, { "name": "JavaScript", "bytes": "3063613" }, { "name": "Less", "bytes": "154956" }, { "name": "Python", "bytes": "192" }, { "name": "Ruby", "bytes": "60" }, { "name": "SQLPL", "bytes": "44180" }, { "name": "Shell", "bytes": "11634" } ], "symlink_target": "" }
package com.google.android.media.tv.companionlibrary.sync; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.media.tv.companionlibrary.model.Channel; /** * Receives broadcasts from a {@link EpgSyncJobService}. * * <p>This a single use receiver. No events are handled after the scan is complete. */ public final class SyncStatusBroadcastReceiver extends BroadcastReceiver { private static final boolean DEBUG = false; private static final String TAG = "SyncStatusBroadcastRcvr"; /** Listens for sync events broadcast by a @{link {@link EpgSyncJobService}. */ public interface SyncListener { /** * This method is used to display progress to the user. * * <p>Before this method is called for the first time amount of progress is considered * indeterminate. * * @param completedStep The number scanning steps that have been completed. * @param totalSteps The total number scanning steps. */ void onScanStepCompleted(int completedStep, int totalSteps); /** * This method will be called when a channel has been completely scanned. It can be * overridden to display custom information about this channel to the user. * * @param displayName {@link Channel#getDisplayName()} for the scanned channel. * @param displayNumber {@link Channel#getDisplayNumber()} ()} for the scanned channel. */ void onScannedChannel(CharSequence displayName, CharSequence displayNumber); /** * This method will be called when scanning ends. Developers may want to notify the user * that scanning has completed and allow them to exit the activity. */ void onScanFinished(); /** * Update the description that will be displayed underneath the progress bar. This could be * used to state the current progress of the scan. * * @param errorCode The error code causing the scan to fail. */ void onScanError(int errorCode); } private final String mInputId; private final SyncListener mSyncListener; private boolean mFinishedScan = false; public SyncStatusBroadcastReceiver(String inputId, SyncListener syncListener) { this.mInputId = inputId; this.mSyncListener = syncListener; } @Override public void onReceive(Context context, final Intent intent) { if (mFinishedScan) { return; } String syncStatusChangedInputId = intent.getStringExtra(EpgSyncJobService.BUNDLE_KEY_INPUT_ID); if (syncStatusChangedInputId != null && syncStatusChangedInputId.equals(mInputId)) { String syncStatus = intent.getStringExtra(EpgSyncJobService.SYNC_STATUS); if (syncStatus.equals(EpgSyncJobService.SYNC_STARTED)) { if (DEBUG) { Log.d(TAG, "Sync status: Started"); } } else if (syncStatus.equals(EpgSyncJobService.SYNC_SCANNED)) { int channelsScanned = intent.getIntExtra(EpgSyncJobService.BUNDLE_KEY_CHANNELS_SCANNED, 0); int channelCount = intent.getIntExtra(EpgSyncJobService.BUNDLE_KEY_CHANNEL_COUNT, 0); mSyncListener.onScanStepCompleted(channelsScanned, channelCount); String channelDisplayName = intent.getStringExtra( EpgSyncJobService.BUNDLE_KEY_SCANNED_CHANNEL_DISPLAY_NAME); String channelDisplayNumber = intent.getStringExtra( EpgSyncJobService.BUNDLE_KEY_SCANNED_CHANNEL_DISPLAY_NUMBER); if (DEBUG) { Log.d(TAG, "Sync status: Channel Scanned"); Log.d(TAG, "Scanned " + channelsScanned + " out of " + channelCount); } mSyncListener.onScannedChannel(channelDisplayName, channelDisplayNumber); } else if (syncStatus.equals(EpgSyncJobService.SYNC_FINISHED)) { if (DEBUG) { Log.d(TAG, "Sync status: Finished"); } mFinishedScan = true; mSyncListener.onScanFinished(); } else if (syncStatus.equals(EpgSyncJobService.SYNC_ERROR)) { int errorCode = intent.getIntExtra(EpgSyncJobService.BUNDLE_KEY_ERROR_REASON, 0); if (DEBUG) { Log.d(TAG, "Error occurred: " + errorCode); } mSyncListener.onScanError(errorCode); } } } }
{ "content_hash": "9bfba33375ba7b09c810c07e1dd0c46c", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 99, "avg_line_length": 42.530973451327434, "alnum_prop": 0.6200582605076987, "repo_name": "stari4ek/androidtv-sample-inputs", "id": "0f23db11aa12bff7ff349b8bcfa65ed410b5c895", "size": "5417", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "library/src/main/java/com/google/android/media/tv/companionlibrary/sync/SyncStatusBroadcastReceiver.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "538170" } ], "symlink_target": "" }
//A dictionary is stored as a sequence of text lines containing words and their explanations. //Write a program that enters a word and translates it by using the dictionary. //Sample dictionary: //input output //.NET platform for applications from Microsoft //CLR managed execution environment for .NET //namespace hierarchical organization of classes using System; using System.Text.RegularExpressions; namespace Word_Dictionary { class WordDictionary { static void Main() { string[] dictionary = { ".NET - platform for applications from Microsoft", "CLR - managed execution environment for .NET", "namespace - hierarchical - organization of classes" }; string word = "CLR"; foreach (string item in dictionary) { var fragments = Regex.Match(item, "(.*?) - (.*)").Groups; if (fragments[1].Value == word) { Console.WriteLine(fragments[1] + " - " + fragments[2]); return; } } } } }
{ "content_hash": "d2d98b624e20bc24e05e146adb583725", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 94, "avg_line_length": 30.513513513513512, "alnum_prop": 0.5783879539415412, "repo_name": "EmilPopov/C-Sharp", "id": "a8838d1a2236d31458792560a5285a351d82e16e", "size": "1131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C# Part2/Strings and Text Processing/Word Dictionary/WordDictionary.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "452" }, { "name": "C#", "bytes": "1517143" }, { "name": "CSS", "bytes": "2626" }, { "name": "HTML", "bytes": "11055" }, { "name": "JavaScript", "bytes": "13464" }, { "name": "XSLT", "bytes": "2014" } ], "symlink_target": "" }
package git import ( "bytes" "crypto/rand" "crypto/rsa" "errors" "fmt" "io" "net" "os" "os/exec" "strings" "sync" "testing" "time" "github.com/google/shlex" "golang.org/x/crypto/ssh" ) func TestListRemotes(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) remote, err := repo.Remotes.Create("test", "git://foo/bar") checkFatal(t, err) defer remote.Free() expected := []string{ "test", } actual, err := repo.Remotes.List() checkFatal(t, err) compareStringList(t, expected, actual) } func assertHostname(cert *Certificate, valid bool, hostname string, t *testing.T) error { if hostname != "github.com" { t.Fatal("hostname does not match") return errors.New("hostname does not match") } return nil } func TestCertificateCheck(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository") checkFatal(t, err) defer remote.Free() options := FetchOptions{ RemoteCallbacks: RemoteCallbacks{ CertificateCheckCallback: func(cert *Certificate, valid bool, hostname string) error { return assertHostname(cert, valid, hostname, t) }, }, } err = remote.Fetch([]string{}, &options, "") checkFatal(t, err) } func TestRemoteConnect(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository") checkFatal(t, err) defer remote.Free() err = remote.ConnectFetch(nil, nil, nil) checkFatal(t, err) } func TestRemoteConnectOption(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) config, err := repo.Config() checkFatal(t, err) err = config.SetString("url.git@github.com:.insteadof", "https://github.com/") checkFatal(t, err) option, err := DefaultRemoteCreateOptions() checkFatal(t, err) option.Name = "origin" option.Flags = RemoteCreateSkipInsteadof remote, err := repo.Remotes.CreateWithOptions("https://github.com/libgit2/TestGitRepository", option) checkFatal(t, err) defer remote.Free() err = remote.ConnectFetch(nil, nil, nil) checkFatal(t, err) } func TestRemoteLs(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository") checkFatal(t, err) defer remote.Free() err = remote.ConnectFetch(nil, nil, nil) checkFatal(t, err) heads, err := remote.Ls() checkFatal(t, err) if len(heads) == 0 { t.Error("Expected remote heads") } } func TestRemoteLsFiltering(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository") checkFatal(t, err) defer remote.Free() err = remote.ConnectFetch(nil, nil, nil) checkFatal(t, err) heads, err := remote.Ls("master") checkFatal(t, err) if len(heads) != 1 { t.Fatalf("Expected one head for master but I got %d", len(heads)) } if heads[0].Id == nil { t.Fatalf("Expected head to have an Id, but it's nil") } if heads[0].Name == "" { t.Fatalf("Expected head to have a name, but it's empty") } } func TestRemotePruneRefs(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) config, err := repo.Config() checkFatal(t, err) defer config.Free() err = config.SetBool("remote.origin.prune", true) checkFatal(t, err) remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository") checkFatal(t, err) defer remote.Free() remote, err = repo.Remotes.Lookup("origin") checkFatal(t, err) defer remote.Free() if !remote.PruneRefs() { t.Fatal("Expected remote to be configured to prune references") } } func TestRemotePrune(t *testing.T) { t.Parallel() remoteRepo := createTestRepo(t) defer cleanupTestRepo(t, remoteRepo) head, _ := seedTestRepo(t, remoteRepo) commit, err := remoteRepo.LookupCommit(head) checkFatal(t, err) defer commit.Free() remoteRef, err := remoteRepo.CreateBranch("test-prune", commit, true) checkFatal(t, err) defer remoteRef.Free() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) config, err := repo.Config() checkFatal(t, err) defer config.Free() remoteUrl := fmt.Sprintf("file://%s", remoteRepo.Workdir()) remote, err := repo.Remotes.Create("origin", remoteUrl) checkFatal(t, err) defer remote.Free() err = remote.Fetch([]string{"test-prune"}, nil, "") checkFatal(t, err) ref, err := repo.References.Create("refs/remotes/origin/test-prune", head, true, "remote reference") checkFatal(t, err) defer ref.Free() err = remoteRef.Delete() checkFatal(t, err) err = config.SetBool("remote.origin.prune", true) checkFatal(t, err) rr, err := repo.Remotes.Lookup("origin") checkFatal(t, err) defer rr.Free() err = rr.ConnectFetch(nil, nil, nil) checkFatal(t, err) err = rr.Prune(nil) checkFatal(t, err) ref, err = repo.References.Lookup("refs/remotes/origin/test-prune") if err == nil { ref.Free() t.Fatal("Expected error getting a pruned reference") } } func TestRemoteCredentialsCalled(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) remote, err := repo.Remotes.CreateAnonymous("https://github.com/libgit2/non-existent") checkFatal(t, err) defer remote.Free() errNonExistent := errors.New("non-existent repository") fetchOpts := FetchOptions{ RemoteCallbacks: RemoteCallbacks{ CredentialsCallback: func(url, username string, allowedTypes CredentialType) (*Credential, error) { return nil, errNonExistent }, }, } err = remote.Fetch(nil, &fetchOpts, "fetch") if err != errNonExistent { t.Fatalf("remote.Fetch() = %v, want %v", err, errNonExistent) } } func newChannelPipe(t *testing.T, w io.Writer, wg *sync.WaitGroup) (*os.File, error) { pr, pw, err := os.Pipe() if err != nil { return nil, err } wg.Add(1) go func() { _, err := io.Copy(w, pr) if err != nil && err != io.EOF { t.Logf("Failed to copy: %v", err) } wg.Done() }() return pw, nil } func startSSHServer(t *testing.T, hostKey ssh.Signer, authorizedKeys []ssh.PublicKey) net.Listener { t.Helper() marshaledAuthorizedKeys := make([][]byte, len(authorizedKeys)) for i, authorizedKey := range authorizedKeys { marshaledAuthorizedKeys[i] = authorizedKey.Marshal() } config := &ssh.ServerConfig{ PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { marshaledPubKey := pubKey.Marshal() for _, marshaledAuthorizedKey := range marshaledAuthorizedKeys { if bytes.Equal(marshaledPubKey, marshaledAuthorizedKey) { return &ssh.Permissions{ // Record the public key used for authentication. Extensions: map[string]string{ "pubkey-fp": ssh.FingerprintSHA256(pubKey), }, }, nil } } t.Logf("unknown public key for %q:\n\t%+v\n\t%+v\n", c.User(), pubKey.Marshal(), authorizedKeys) return nil, fmt.Errorf("unknown public key for %q", c.User()) }, } config.AddHostKey(hostKey) listener, err := net.Listen("tcp", "localhost:0") if err != nil { t.Fatalf("Failed to listen for connection: %v", err) } go func() { nConn, err := listener.Accept() if err != nil { if strings.Contains(err.Error(), "use of closed network connection") { return } t.Logf("Failed to accept incoming connection: %v", err) return } defer nConn.Close() conn, chans, reqs, err := ssh.NewServerConn(nConn, config) if err != nil { t.Logf("failed to handshake: %+v, %+v", conn, err) return } // The incoming Request channel must be serviced. go func() { for newRequest := range reqs { t.Logf("new request %v", newRequest) } }() // Service only the first channel request newChannel := <-chans defer func() { for newChannel := range chans { t.Logf("new channel %v", newChannel) newChannel.Reject(ssh.UnknownChannelType, "server closing") } }() // Channels have a type, depending on the application level // protocol intended. In the case of a shell, the type is // "session" and ServerShell may be used to present a simple // terminal interface. if newChannel.ChannelType() != "session" { newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") return } channel, requests, err := newChannel.Accept() if err != nil { t.Logf("Could not accept channel: %v", err) return } defer channel.Close() // Sessions have out-of-band requests such as "shell", // "pty-req" and "env". Here we handle only the // "exec" request. req := <-requests if req.Type != "exec" { req.Reply(false, nil) return } // RFC 4254 Section 6.5. var payload struct { Command string } if err := ssh.Unmarshal(req.Payload, &payload); err != nil { t.Logf("invalid payload on channel %v: %v", channel, err) req.Reply(false, nil) return } args, err := shlex.Split(payload.Command) if err != nil { t.Logf("invalid command on channel %v: %v", channel, err) req.Reply(false, nil) return } if len(args) < 2 || (args[0] != "git-upload-pack" && args[0] != "git-receive-pack") { t.Logf("invalid command (%v) on channel %v: %v", args, channel, err) req.Reply(false, nil) return } req.Reply(true, nil) go func(in <-chan *ssh.Request) { for req := range in { t.Logf("draining request %v", req) } }(requests) // The first parameter is the (absolute) path of the repository. args[1] = "./testdata" + args[1] cmd := exec.Command(args[0], args[1:]...) cmd.Stdin = channel var wg sync.WaitGroup stdoutPipe, err := newChannelPipe(t, channel, &wg) if err != nil { t.Logf("Failed to create stdout pipe: %v", err) return } cmd.Stdout = stdoutPipe stderrPipe, err := newChannelPipe(t, channel.Stderr(), &wg) if err != nil { t.Logf("Failed to create stderr pipe: %v", err) return } cmd.Stderr = stderrPipe go func() { wg.Wait() channel.CloseWrite() }() err = cmd.Start() if err != nil { t.Logf("Failed to start %v: %v", args, err) return } // Once the process has started, we need to close the write end of the // pipes from this process so that we can know when the child has done // writing to it. stdoutPipe.Close() stderrPipe.Close() timer := time.AfterFunc(5*time.Second, func() { t.Log("process timed out, terminating") cmd.Process.Kill() }) defer timer.Stop() err = cmd.Wait() if err != nil { t.Logf("Failed to run %v: %v", args, err) return } }() return listener } func TestRemoteSSH(t *testing.T) { t.Parallel() pubKeyUsername := "testuser" hostPrivKey, err := rsa.GenerateKey(rand.Reader, 512) if err != nil { t.Fatalf("Failed to generate the host RSA private key: %v", err) } hostSigner, err := ssh.NewSignerFromKey(hostPrivKey) if err != nil { t.Fatalf("Failed to generate SSH hostSigner: %v", err) } privKey, err := rsa.GenerateKey(rand.Reader, 512) if err != nil { t.Fatalf("Failed to generate the user RSA private key: %v", err) } signer, err := ssh.NewSignerFromKey(privKey) if err != nil { t.Fatalf("Failed to generate SSH signer: %v", err) } // This is in the format "xx:xx:xx:...", so we remove the colons so that it // matches the fmt.Sprintf() below. // Note that not all libssh2 implementations support the SHA256 fingerprint, // so we use MD5 here for testing. publicKeyFingerprint := strings.Replace(ssh.FingerprintLegacyMD5(hostSigner.PublicKey()), ":", "", -1) listener := startSSHServer(t, hostSigner, []ssh.PublicKey{signer.PublicKey()}) defer listener.Close() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) certificateCheckCallbackCalled := false fetchOpts := FetchOptions{ RemoteCallbacks: RemoteCallbacks{ CertificateCheckCallback: func(cert *Certificate, valid bool, hostname string) error { hostkeyFingerprint := fmt.Sprintf("%x", cert.Hostkey.HashMD5[:]) if hostkeyFingerprint != publicKeyFingerprint { return fmt.Errorf("server hostkey %q, want %q", hostkeyFingerprint, publicKeyFingerprint) } certificateCheckCallbackCalled = true return nil }, CredentialsCallback: func(url, username string, allowedTypes CredentialType) (*Credential, error) { if allowedTypes&(CredentialTypeSSHKey|CredentialTypeSSHCustom|CredentialTypeSSHMemory) != 0 { return NewCredentialSSHKeyFromSigner(pubKeyUsername, signer) } if (allowedTypes & CredentialTypeUsername) != 0 { return NewCredentialUsername(pubKeyUsername) } return nil, fmt.Errorf("unknown credential type %+v", allowedTypes) }, }, } remote, err := repo.Remotes.Create( "origin", fmt.Sprintf("ssh://%s/TestGitRepository", listener.Addr().String()), ) checkFatal(t, err) defer remote.Free() err = remote.Fetch(nil, &fetchOpts, "") checkFatal(t, err) if !certificateCheckCallbackCalled { t.Fatalf("CertificateCheckCallback was not called") } heads, err := remote.Ls() checkFatal(t, err) if len(heads) == 0 { t.Error("Expected remote heads") } }
{ "content_hash": "58a2063e39d65aef0e06a9988338b534", "timestamp": "", "source": "github", "line_count": 521, "max_line_length": 103, "avg_line_length": 25.3320537428023, "alnum_prop": 0.6782845885740264, "repo_name": "libgit2/git2go", "id": "05395b3a774175f324b31a6a1596c3f067fd446e", "size": "13198", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "remote_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "17055" }, { "name": "Go", "bytes": "485952" }, { "name": "Makefile", "bytes": "1814" }, { "name": "Shell", "bytes": "2862" } ], "symlink_target": "" }
namespace ex = std::experimental::pmr; int main(int, char**) { typedef ex::resource_adaptor<std::allocator<void>> R; typedef ex::resource_adaptor<std::allocator<long>> R2; static_assert(std::is_same<R, R2>::value, ""); { static_assert(std::is_base_of<ex::memory_resource, R>::value, ""); static_assert(std::is_same<R::allocator_type, std::allocator<char>>::value, ""); } { static_assert(std::is_default_constructible<R>::value, ""); static_assert(std::is_copy_constructible<R>::value, ""); static_assert(std::is_move_constructible<R>::value, ""); static_assert(std::is_copy_assignable<R>::value, ""); static_assert(std::is_move_assignable<R>::value, ""); } return 0; }
{ "content_hash": "d5455faa928ccde8ff00bcb29f41861f", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 88, "avg_line_length": 36, "alnum_prop": 0.6084656084656085, "repo_name": "llvm-mirror/libcxx", "id": "1691025848c6c3e7b2e9e3ed07ef8c1cf316c80e", "size": "1373", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "test/std/experimental/memory/memory.resource.adaptor/memory.resource.adaptor.overview/overview.pass.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2035" }, { "name": "C", "bytes": "19789" }, { "name": "C++", "bytes": "25847968" }, { "name": "CMake", "bytes": "147482" }, { "name": "CSS", "bytes": "1237" }, { "name": "HTML", "bytes": "228687" }, { "name": "Objective-C++", "bytes": "2263" }, { "name": "Python", "bytes": "279305" }, { "name": "Shell", "bytes": "21350" } ], "symlink_target": "" }
namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Utility function to calculate the center of a circle of given radius which // passes through two given points. static ChVector2<> CalcCircleCenter(const ChVector2<>& A, const ChVector2<>& B, double r, double direction) { // midpoint ChVector2<> C = (A + B) / 2; // distance between A and B double l = (B - A).Length(); // distance between C and O double d = std::sqrt(r * r - l * l / 4); // slope of line AB double mAB = (B.y() - A.y()) / (B.x() - A.x()); // slope of line CO (perpendicular to AB) double mCO = -1 / mAB; // x offset from C double x_offset = d / std::sqrt(1 + mCO * mCO); // y offset from C double y_offset = mCO * x_offset; // circle center ChVector2<> O(C.x() + direction * x_offset, C.y() + direction * y_offset); ////std::cout << std::endl; ////std::cout << "radius: " << r << std::endl; ////std::cout << A.x() << " " << A.y() << std::endl; ////std::cout << B.x() << " " << B.y() << std::endl; ////std::cout << O.x() << " " << O.y() << std::endl; ////std::cout << "Check: " << (A - O).Length() - r << " " << (B - O).Length() - r << std::endl; ////std::cout << std::endl; return O; } class SprocketBandContactCB : public ChSystem::CustomCollisionCallback { public: //// TODO Add in a collision envelope to the contact algorithm for NSC SprocketBandContactCB(ChTrackAssembly* track, ///< containing track assembly double envelope, ///< collision detection envelope int gear_nteeth, ///< number of teeth of the sprocket gear double separation ///< separation between sprocket gears ) : m_track(track), m_envelope(envelope), m_gear_nteeth(gear_nteeth), m_separation(separation) { m_sprocket = std::dynamic_pointer_cast<ChSprocketBand>(m_track->GetSprocket()); auto shoe = std::dynamic_pointer_cast<ChTrackShoeBand>(track->GetTrackShoe(0)); // The angle between the centers of two sequential teeth on the sprocket m_beta = CH_C_2PI / m_sprocket->GetNumTeeth(); double OutRad = m_sprocket->GetOuterRadius(); // The angle measured from the center of the sprocket between the center of the tooth // and the outer line segment edge of the tooth's base width double HalfBaseWidthCordAng = std::asin((m_sprocket->GetBaseWidth() / 2) / OutRad); // The angle measured at the center of the sprocket between the end of one tooth profile // and the start of the next (angle where the profile runs along the outer radius // of the sprocket) double OuterRadArcAng = m_beta - 2 * HalfBaseWidthCordAng; m_gear_outer_radius_arc_angle_start = HalfBaseWidthCordAng; m_gear_outer_radius_arc_angle_end = HalfBaseWidthCordAng + OuterRadArcAng; // Vectors defining the current tooth's radial and perpendicular vectors ChVector2<> vec_Radial(1, 0); ChVector2<> vec_Perp(-vec_Radial.y(), vec_Radial.x()); // Points defining the sprocket tooth's base width ChVector2<> ToothBaseWidthUpperPnt(OutRad * (std::cos(HalfBaseWidthCordAng)), OutRad * (std::sin(HalfBaseWidthCordAng))); ChVector2<> ToothBaseWidthLowerPnt(OutRad * (std::cos(-HalfBaseWidthCordAng)), OutRad * (std::sin(-HalfBaseWidthCordAng))); ChVector2<> ToothBaseWidthCtrPnt = 0.5 * (ToothBaseWidthUpperPnt + ToothBaseWidthLowerPnt); // Points defining the sprocket tooth's tip width ChVector2<> ToothTipWidthCtrPnt = ToothBaseWidthCtrPnt - m_sprocket->GetToothDepth() * vec_Radial; ChVector2<> ToothTipWidthUpperPnt = ToothTipWidthCtrPnt + 0.5 * m_sprocket->GetTipWidth() * vec_Perp; ChVector2<> ToothTipWidthLowerPnt = ToothTipWidthCtrPnt - 0.5 * m_sprocket->GetTipWidth() * vec_Perp; // Cache the points for the first sprocket tooth profile for the tooth arc centers, positive arc is in the CCW // direction for the first tooth profile and the negative arc is in the CW direction for the first tooth profile m_gear_center_p = CalcCircleCenter(ToothBaseWidthUpperPnt, ToothTipWidthUpperPnt, m_sprocket->GetArcRadius(), 1); m_gear_center_m = CalcCircleCenter(ToothBaseWidthLowerPnt, ToothTipWidthLowerPnt, m_sprocket->GetArcRadius(), 1); // Cache the starting (smallest) and ending (largest) arc angles for the positive sprocket tooth arc (ensuring // that both angles are positive) m_gear_center_p_start_angle = std::atan2(ToothBaseWidthUpperPnt.y() - m_gear_center_p.y(), ToothBaseWidthUpperPnt.x() - m_gear_center_p.x()); m_gear_center_p_start_angle = m_gear_center_p_start_angle < 0 ? m_gear_center_p_start_angle + CH_C_2PI : m_gear_center_p_start_angle; m_gear_center_p_end_angle = std::atan2(ToothTipWidthUpperPnt.y() - m_gear_center_p.y(), ToothTipWidthUpperPnt.x() - m_gear_center_p.x()); m_gear_center_p_end_angle = m_gear_center_p_end_angle < 0 ? m_gear_center_p_end_angle + CH_C_2PI : m_gear_center_p_end_angle; if (m_gear_center_p_start_angle > m_gear_center_p_end_angle) { double temp = m_gear_center_p_start_angle; m_gear_center_p_start_angle = m_gear_center_p_end_angle; m_gear_center_p_end_angle = temp; } // Cache the starting (smallest) and ending (largest) arc angles for the negative sprocket tooth arc (ensuring // that both angles are positive) m_gear_center_m_start_angle = std::atan2(ToothBaseWidthLowerPnt.y() - m_gear_center_m.y(), ToothBaseWidthLowerPnt.x() - m_gear_center_m.x()); m_gear_center_m_start_angle = m_gear_center_m_start_angle < 0 ? m_gear_center_m_start_angle + CH_C_2PI : m_gear_center_m_start_angle; m_gear_center_m_end_angle = std::atan2(ToothTipWidthLowerPnt.y() - m_gear_center_m.y(), ToothTipWidthLowerPnt.x() - m_gear_center_m.x()); m_gear_center_m_end_angle = m_gear_center_m_end_angle < 0 ? m_gear_center_m_end_angle + CH_C_2PI : m_gear_center_m_end_angle; if (m_gear_center_m_start_angle > m_gear_center_m_end_angle) { double temp = m_gear_center_m_start_angle; m_gear_center_m_start_angle = m_gear_center_m_end_angle; m_gear_center_m_end_angle = temp; } // Since the shoe has not been initalized yet, set a flag to cache all of the parameters that depend on the shoe // being initalized m_update_tread = true; } virtual void OnCustomCollision(ChSystem* system) override; private: // Test collision between a tread segment body and the sprocket's gear profile void CheckTreadSegmentSprocket(std::shared_ptr<ChBody> treadsegment, // tread segment body const ChVector<>& locS_abs // center of sprocket (global frame) ); // Test for collision between an arc on a tread segment body and the matching arc on the sprocket's gear profile void CheckTreadArcSprocketArc( std::shared_ptr<ChBody> treadsegment, // tread segment body ChVector2<> sprocket_arc_center, // Center of the sprocket profile arc in the sprocket's X-Z plane double sprocket_arc_angle_start, // Starting (smallest & positive) angle for the sprocket arc double sprocket_arc_angle_end, // Ending (largest & positive) angle for the sprocket arc double sprocket_arc_radius, // Radius for the sprocket arc ChVector2<> tooth_arc_center, // Center of the belt tooth's profile arc in the sprocket's X-Z plane double tooth_arc_angle_start, // Starting (smallest & positive) angle for the belt tooth arc double tooth_arc_angle_end, // Ending (largest & positive) angle for the belt tooth arc double tooth_arc_radius // Radius for the tooth arc ); void CheckTreadTipSprocketTip(std::shared_ptr<ChBody> treadsegment); void CheckSegmentCircle(std::shared_ptr<ChBody> BeltSegment, // connector body double cr, // circle radius const ChVector<>& p1, // segment end point 1 const ChVector<>& p2 // segment end point 2 ); ChTrackAssembly* m_track; // pointer to containing track assembly std::shared_ptr<ChSprocketBand> m_sprocket; // handle to the sprocket double m_envelope; // collision detection envelope int m_gear_nteeth; // sprocket gear, number of teeth double m_separation; // separation distance between sprocket gears double m_gear_tread_broadphase_dist_squared; // Tread body to Sprocket quick Broadphase distance squared check ChVector2<> m_gear_center_p; // center of (+x) arc, in sprocket body x-z plane ChVector2<> m_gear_center_m; // center of (-x) arc, in sprocket body x-z plane double m_gear_center_p_start_angle; // starting positive angle of the first sprocket tooth (+z ) arc double m_gear_center_p_end_angle; // ending positive angle of the first sprocket tooth (+z ) arc double m_gear_center_m_start_angle; // starting positive angle of the first sprocket tooth (-z ) arc double m_gear_center_m_end_angle; // ending positive angle of the first sprocket tooth (-z ) arc double m_gear_outer_radius_arc_angle_start; // starting positive angle of the first sprocket outer radius arc double m_gear_outer_radius_arc_angle_end; // ending positive angle of the first sprocket outer radius arc ChVector2<> m_tread_center_p; // center of (+x) arc, in tread body x-z plane ChVector2<> m_tread_center_m; // center of (-x) arc, in tread body x-z plane double m_tread_center_p_start_angle; // starting positive angle of the first tooth (+x ) arc double m_tread_center_p_end_angle; // ending positive angle of the first tooth (+x ) arc double m_tread_center_m_start_angle; // starting positive angle of the first tooth (-x ) arc double m_tread_center_m_end_angle; // ending positive angle of the first tooth (-x ) arc double m_tread_arc_radius; // radius of the tooth arc profile double m_tread_tip_halfwidth; // half of the length (x direction) of the tread tooth tip double m_tread_tip_height; // the height (z direction) of the trad tooth from its base line to its tip bool m_update_tread; // flag to update the remaining cached contact properties on the first contact callback double m_beta; // angle between sprocket teeth }; // Add contacts between the sprocket and track shoes. void SprocketBandContactCB::OnCustomCollision(ChSystem* system) { // Temporary workaround since the shoe has not been intialized by the time the collision constructor is called. if (m_update_tread) { m_update_tread = false; auto shoe = std::dynamic_pointer_cast<ChTrackShoeBand>(m_track->GetTrackShoe(0)); // Broadphase collision distance squared check for tread tooth to sprocket contact m_gear_tread_broadphase_dist_squared = std::pow( m_sprocket->GetOuterRadius() + sqrt(std::pow(shoe->GetToothBaseLength() / 2, 2) + std::pow(shoe->GetToothHeight() + shoe->GetWebThickness() / 2, 2)), 2); m_tread_center_p = shoe->m_center_p; // center of (+x) arc, in tread body x-z plane m_tread_center_m = shoe->m_center_m; // center of (-x) arc, in tread body x-z plane m_tread_center_p_start_angle = shoe->m_center_p_arc_start; // starting positive angle of the tooth (+x ) arc m_tread_center_p_end_angle = shoe->m_center_p_arc_end; // ending positive angle of the tooth (+x ) arc m_tread_center_m_start_angle = shoe->m_center_m_arc_start; // starting positive angle of the tooth (-x ) arc m_tread_center_m_end_angle = shoe->m_center_m_arc_end; // ending positive angle of the tooth (-x ) arc m_tread_arc_radius = shoe->GetToothArcRadius(); // radius of the tooth arcs m_tread_tip_halfwidth = shoe->GetToothTipLength() / 2; // half of the tip length (s direction) of the belt tooth m_tread_tip_height = shoe->GetToothHeight() + shoe->GetTreadThickness() / 2; // height of the belt tooth profile from the tip to its base line } // Return now if collision disabled on sproket. if (!m_sprocket->GetGearBody()->GetCollide()) return; // Sprocket gear center location (expressed in global frame) ChVector<> locS_abs = m_sprocket->GetGearBody()->GetPos(); // Loop over all track shoes in the associated track for (size_t is = 0; is < m_track->GetNumTrackShoes(); ++is) { auto shoe = std::static_pointer_cast<ChTrackShoeBand>(m_track->GetTrackShoe(is)); CheckTreadSegmentSprocket(shoe->GetShoeBody(), locS_abs); } } void SprocketBandContactCB::CheckTreadSegmentSprocket( std::shared_ptr<ChBody> treadsegment, // tread segment body const ChVector<>& locS_abs // center of sprocket (global frame) ) { // (1) Express the center of the web segment body in the sprocket frame ChVector<> loc = m_sprocket->GetGearBody()->TransformPointParentToLocal(treadsegment->GetPos()); // (2) Broadphase collision test: no contact if the tread segments's center is too far from the // center of the gear (test performed in the sprocket's x-z plane). if (loc.x() * loc.x() + loc.z() * loc.z() > m_gear_tread_broadphase_dist_squared) return; // (3) Check the sprocket tooth tip to the belt tooth tip contact CheckTreadTipSprocketTip(treadsegment); // (4) Check for sprocket arc to tooth arc collisions // Working in the frame of the sprocket, find the candidate tooth space. // This is the closest tooth space to the tread center point. // Angle formed by 'loc' relative the sprocket center in the sprocket frame double angle = std::atan2(loc.z(), loc.x()); angle = angle < 0 ? angle + CH_C_2PI : angle; // Find angle of closest tooth space double alpha = m_beta * std::round(angle / m_beta); // Determine the tooth x and z axes in the sprocket frame ChVector<> tooth_x_axis_point = m_sprocket->GetGearBody()->TransformPointParentToLocal( treadsegment->GetPos() + treadsegment->GetRot().GetXaxis()); ChVector2<> tooth_x_axis(tooth_x_axis_point.x() - loc.x(), tooth_x_axis_point.z() - loc.z()); tooth_x_axis.Normalize(); ChVector2<> tooth_z_axis(-tooth_x_axis.y(), tooth_x_axis.x()); // Check the positive arcs (positive sprocket arc to positive tooth arc contact) // Calculate the sprocket positive arc center point for the closest tooth spacing angle ChVector2<> sprocket_center_p(m_gear_center_p.x() * std::cos(alpha) - m_gear_center_p.y() * std::sin(alpha), m_gear_center_p.x() * std::sin(alpha) + m_gear_center_p.y() * std::cos(alpha)); // Adjust start & end angle based on the selected sprocket tooth spacing angle double gear_center_p_start_angle = m_gear_center_p_start_angle + alpha; double gear_center_p_end_angle = m_gear_center_p_end_angle + alpha; // Ensure that the starting angle is between 0 & 2PI, adjusting ending angle to match while (gear_center_p_start_angle > CH_C_2PI) { gear_center_p_start_angle -= CH_C_2PI; gear_center_p_end_angle -= CH_C_2PI; } // Calculate the positive tooth arc center point in the sprocket frame ChVector<> tooth_center_p_3d = m_sprocket->GetGearBody()->TransformPointParentToLocal( treadsegment->GetPos() + m_tread_center_p.x() * treadsegment->GetRot().GetXaxis() + m_tread_center_p.y() * treadsegment->GetRot().GetZaxis()); ChVector2<> tooth_center_p(tooth_center_p_3d.x(), tooth_center_p_3d.z()); // Calculate the tooth arc starting point and end points in the sprocket frame // Don't add in the tooth_center_p point postion since it will get subtracted off to calculate the angle // This leads to the tooth arc angles in the sprocket frame ChVector2<> tooth_arc_start_point_p = m_tread_arc_radius * std::cos(m_tread_center_p_start_angle) * tooth_x_axis + m_tread_arc_radius * std::sin(m_tread_center_p_start_angle) * tooth_z_axis; ChVector2<> tooth_arc_end_point_p = m_tread_arc_radius * std::cos(m_tread_center_p_end_angle) * tooth_x_axis + m_tread_arc_radius * std::sin(m_tread_center_p_end_angle) * tooth_z_axis; double tooth_center_p_start_angle = std::atan2(tooth_arc_start_point_p.y(), tooth_arc_start_point_p.x()); tooth_center_p_start_angle = tooth_center_p_start_angle < 0 ? tooth_center_p_start_angle + CH_C_2PI : tooth_center_p_start_angle; double tooth_center_p_end_angle = std::atan2(tooth_arc_end_point_p.y(), tooth_arc_end_point_p.x()); tooth_center_p_end_angle = tooth_center_p_end_angle < 0 ? tooth_center_p_end_angle + CH_C_2PI : tooth_center_p_end_angle; if (tooth_center_p_end_angle < tooth_center_p_start_angle) { tooth_center_p_end_angle += CH_C_2PI; } double temp = m_sprocket->GetArcRadius(); CheckTreadArcSprocketArc(treadsegment, sprocket_center_p, gear_center_p_start_angle, gear_center_p_end_angle, m_sprocket->GetArcRadius(), tooth_center_p, tooth_center_p_start_angle, tooth_center_p_end_angle, m_tread_arc_radius); // Check the negative arcs (negative sprocket arc to negative tooth arc contact) // Calculate the sprocket negative arc center point for the closest tooth spacing angle ChVector2<> sprocket_center_m(m_gear_center_m.x() * std::cos(alpha) - m_gear_center_m.y() * std::sin(alpha), m_gear_center_m.x() * std::sin(alpha) + m_gear_center_m.y() * std::cos(alpha)); // Adjust start & end angle based on the selected sprocket tooth spacing angle double gear_center_m_start_angle = m_gear_center_m_start_angle + alpha; double gear_center_m_end_angle = m_gear_center_m_end_angle + alpha; // Ensure that the starting angle is between 0 & 2PI, adjusting ending angle to match while (gear_center_m_start_angle > CH_C_2PI) { gear_center_m_start_angle -= CH_C_2PI; gear_center_m_end_angle -= CH_C_2PI; } // Calculate the positive tooth arc center point in the sprocket frame ChVector<> tooth_center_m_3d = m_sprocket->GetGearBody()->TransformPointParentToLocal( treadsegment->GetPos() + m_tread_center_m.x() * treadsegment->GetRot().GetXaxis() + m_tread_center_m.y() * treadsegment->GetRot().GetZaxis()); ChVector2<> tooth_center_m(tooth_center_m_3d.x(), tooth_center_m_3d.z()); // Calculate the tooth arc starting point and end points in the sprocket frame // Don't add in the tooth_center_m point postion since it will get subtracted off to calculate the angle // This leads to the tooth arc angles in the sprocket frame ChVector2<> tooth_arc_start_point_m = m_tread_arc_radius * std::cos(m_tread_center_m_start_angle) * tooth_x_axis + m_tread_arc_radius * std::sin(m_tread_center_m_start_angle) * tooth_z_axis; ChVector2<> tooth_arc_end_point_m = m_tread_arc_radius * std::cos(m_tread_center_m_end_angle) * tooth_x_axis + m_tread_arc_radius * std::sin(m_tread_center_m_end_angle) * tooth_z_axis; double tooth_center_m_start_angle = std::atan2(tooth_arc_start_point_m.y(), tooth_arc_start_point_m.x()); tooth_center_m_start_angle = tooth_center_m_start_angle < 0 ? tooth_center_m_start_angle + CH_C_2PI : tooth_center_m_start_angle; double tooth_center_m_end_angle = std::atan2(tooth_arc_end_point_m.y(), tooth_arc_end_point_m.x()); tooth_center_m_end_angle = tooth_center_m_end_angle < 0 ? tooth_center_m_end_angle + CH_C_2PI : tooth_center_m_end_angle; if (tooth_center_m_end_angle < tooth_center_m_start_angle) { tooth_center_m_end_angle += CH_C_2PI; } CheckTreadArcSprocketArc(treadsegment, sprocket_center_m, gear_center_m_start_angle, gear_center_m_end_angle, m_sprocket->GetArcRadius(), tooth_center_m, tooth_center_m_start_angle, tooth_center_m_end_angle, m_tread_arc_radius); } void SprocketBandContactCB::CheckTreadTipSprocketTip(std::shared_ptr<ChBody> treadsegment) { // Check the tooth tip to outer sprocket arc // Check to see if any of the points are within the angle of an outer sprocket arc // If so, clip the part of the tip line segment that is out of the arc, if need and run a line segment to circle // check ChVector<> tooth_tip_p = m_sprocket->GetGearBody()->TransformPointParentToLocal( treadsegment->GetPos() + m_tread_tip_halfwidth * treadsegment->GetRot().GetXaxis() + m_tread_tip_height * treadsegment->GetRot().GetZaxis()); tooth_tip_p.y() = 0; ChVector<> tooth_tip_m = m_sprocket->GetGearBody()->TransformPointParentToLocal( treadsegment->GetPos() - m_tread_tip_halfwidth * treadsegment->GetRot().GetXaxis() + m_tread_tip_height * treadsegment->GetRot().GetZaxis()); tooth_tip_m.y() = 0; double tooth_tip_p_angle = std::atan2(tooth_tip_p.z(), tooth_tip_p.x()); tooth_tip_p_angle = tooth_tip_p_angle < 0 ? tooth_tip_p_angle + CH_C_2PI : tooth_tip_p_angle; double tooth_tip_m_angle = std::atan2(tooth_tip_m.z(), tooth_tip_m.x()); tooth_tip_m_angle = tooth_tip_m_angle < 0 ? tooth_tip_m_angle + CH_C_2PI : tooth_tip_m_angle; double tooth_tip_p_angle_adjust = m_beta * std::floor(tooth_tip_p_angle / m_beta); tooth_tip_p_angle -= tooth_tip_p_angle_adjust; // Adjust the angle so that it lies within 1 tooth spacing so it is // easier to check if it is on an outer sprocket arc double tooth_tip_m_angle_adjust = m_beta * std::floor(tooth_tip_m_angle / m_beta); tooth_tip_m_angle -= tooth_tip_m_angle_adjust; // Adjust the angle so that it lies within 1 tooth spacing so it is // easier to check if it is on an outer sprocket arc if (((tooth_tip_p_angle >= m_gear_outer_radius_arc_angle_start) && (tooth_tip_p_angle <= m_gear_outer_radius_arc_angle_end)) || ((tooth_tip_m_angle >= m_gear_outer_radius_arc_angle_start) && (tooth_tip_m_angle <= m_gear_outer_radius_arc_angle_end))) { // Check for possible collisions with outer sprocket radius // Clamp the tooth points within the sprocket outer radius arc to prevent false contacts from being generated if (!((tooth_tip_p_angle >= m_gear_outer_radius_arc_angle_start) && (tooth_tip_p_angle <= m_gear_outer_radius_arc_angle_end))) { // Clip tooth_tip_p so that it lies within the outer arc section of the sprocket profile since there is no // contact after this point double clip_angle_start = m_gear_outer_radius_arc_angle_start + tooth_tip_m_angle_adjust; // Use m tip point, since that is in the correct arc double clip_angle_end = m_gear_outer_radius_arc_angle_end + tooth_tip_m_angle_adjust; ChVector<> vec_tooth = tooth_tip_p - tooth_tip_m; double a = vec_tooth.x(); double b = -std::cos(clip_angle_end); double c = vec_tooth.z(); double d = -std::sin(clip_angle_end); double alpha = (1 / (a * d - b * c)) * (-d * tooth_tip_m.x() + b * tooth_tip_m.z()); ChClampValue(alpha, 0.0, 1.0); CheckSegmentCircle(treadsegment, m_sprocket->GetOuterRadius(), tooth_tip_m + alpha * vec_tooth, tooth_tip_m); } else if (!((tooth_tip_m_angle >= m_gear_outer_radius_arc_angle_start) && (tooth_tip_m_angle <= m_gear_outer_radius_arc_angle_end))) { // Clip tooth_tip_m so that it lies within the outer arc section of the sprocket profile since there is no // contact after this point double clip_angle_start = m_gear_outer_radius_arc_angle_start + tooth_tip_p_angle_adjust; // Use p tip point, since that is in the correct arc double clip_angle_end = m_gear_outer_radius_arc_angle_end + tooth_tip_p_angle_adjust; ChVector<> vec_tooth = tooth_tip_m - tooth_tip_p; double a = vec_tooth.x(); double b = -std::cos(clip_angle_start); double c = vec_tooth.z(); double d = -std::sin(clip_angle_start); double alpha = (1 / (a * d - b * c)) * (-d * tooth_tip_p.x() + b * tooth_tip_p.z()); ChClampValue(alpha, 0.0, 1.0); CheckSegmentCircle(treadsegment, m_sprocket->GetOuterRadius(), tooth_tip_p + alpha * vec_tooth, tooth_tip_p); } else { // No Tooth Clipping Needed CheckSegmentCircle(treadsegment, m_sprocket->GetOuterRadius(), tooth_tip_p, tooth_tip_m); } } } void SprocketBandContactCB::CheckTreadArcSprocketArc(std::shared_ptr<ChBody> treadsegment, ChVector2<> sprocket_arc_center, double sprocket_arc_angle_start, double sprocket_arc_angle_end, double sprocket_arc_radius, ChVector2<> tooth_arc_center, double tooth_arc_angle_start, double tooth_arc_angle_end, double tooth_arc_radius) { // Find the angle from the sprocket arc center through the tooth arc center. If the angle lies within // the sprocket arc, use the point on the sprocket arc at that angle as the sprocket collision point. // If it does not lie within the arc, determine which sprocket end point is closest to that angle and use // that point as the sprocket collision point. double sprocket_contact_angle = std::atan2(tooth_arc_center.y() - sprocket_arc_center.y(), tooth_arc_center.x() - sprocket_arc_center.x()); while (sprocket_contact_angle < sprocket_arc_angle_start) { sprocket_contact_angle += CH_C_2PI; } ChVector2<> sprocket_collision_point = sprocket_arc_center + sprocket_arc_radius * ChVector2<>(std::cos(sprocket_contact_angle), std::sin(sprocket_contact_angle)); if (sprocket_contact_angle >= sprocket_arc_angle_end) { // Lies outside of the sprocket arc, so find the sprocket end point that is closest to the the arc since the // sprocket_contact_angle has to be >= sprocket_arc_angle_start ChVector2<> arc_start_point = sprocket_arc_center + sprocket_arc_radius * ChVector2<>(std::cos(sprocket_arc_angle_start), std::sin(sprocket_arc_angle_start)); ChVector2<> arc_start_to_collision_point = sprocket_collision_point - arc_start_point; ChVector2<> arc_end_point = sprocket_arc_center + sprocket_arc_radius * ChVector2<>(std::cos(sprocket_arc_angle_end), std::sin(sprocket_arc_angle_end)); ChVector2<> arc_end_to_collision_point = sprocket_collision_point - arc_end_point; sprocket_collision_point = (arc_start_to_collision_point.Length2() <= arc_end_to_collision_point.Length2()) ? arc_start_point : arc_end_point; } // Find the angle from the tooth arc center through the sprocket collision point. If the angle lies // within the tooth arc, use the point on the tooth arc at that angle as the tooth collision point. If // the angle does not lie within the arc, then no contact exists. double tooth_contact_angle = std::atan2(sprocket_collision_point.y() - tooth_arc_center.y(), sprocket_collision_point.x() - tooth_arc_center.x()); tooth_contact_angle -= CH_C_2PI; // Ensure that tooth_contact_angle is negative and this less than tooth_arc_angle_start while (tooth_contact_angle < tooth_arc_angle_start) { tooth_contact_angle += CH_C_2PI; } if (tooth_contact_angle > tooth_arc_angle_end) { return; // Tooth collision point does not lie on the tooth arc } ChVector2<> tooth_collision_point = tooth_arc_center + tooth_arc_radius * ChVector2<>(std::cos(tooth_contact_angle), std::sin(tooth_contact_angle)); // Subtract the tooth arc radius from distance from tooth arc center to the sprocket collision point. // If this distance is positive, then no contact exists. Otherwise this is the collision distance. ChVector2<> sprocket_collision_point_to_tooth_arc_center = tooth_arc_center - sprocket_collision_point; double collision_distance = sprocket_collision_point_to_tooth_arc_center.Length() - tooth_arc_radius; if (collision_distance >= 0) { return; // tooth arc is inside the sprocket arc, so no collision } // Find the normalized vector from the tooth collision point through the sprocket collision point // as well as the tooth arc center. This is the collision normal vector. sprocket_collision_point_to_tooth_arc_center.Normalize(); ChVector<> normal(sprocket_collision_point_to_tooth_arc_center.x(), 0, sprocket_collision_point_to_tooth_arc_center.y()); ChVector<> pt_gear(sprocket_collision_point.x(), 0, sprocket_collision_point.y()); ChVector<> pt_tooth(tooth_collision_point.x(), 0, tooth_collision_point.y()); // Fill in contact information and add the contact to the system. // Express all vectors in the global frame collision::ChCollisionInfo contact; contact.modelA = m_sprocket->GetGearBody()->GetCollisionModel().get(); contact.modelB = treadsegment->GetCollisionModel().get(); contact.vN = m_sprocket->GetGearBody()->TransformDirectionLocalToParent(normal); contact.vpA = m_sprocket->GetGearBody()->TransformPointLocalToParent(pt_gear); contact.vpB = m_sprocket->GetGearBody()->TransformPointLocalToParent(pt_tooth); contact.distance = collision_distance; ////contact.eff_radius = sprocket_arc_radius; //// TODO: take into account tooth_arc_radius? m_sprocket->GetGearBody()->GetSystem()->GetContactContainer()->AddContact(contact); } // Working in the (x-z) plane, perform a 2D collision test between the circle of radius 'cr' // centered at the origin (on the sprocket body) and the line segment with endpoints 'p1' and 'p2' // (on the Belt Segement body). void SprocketBandContactCB::CheckSegmentCircle(std::shared_ptr<ChBody> BeltSegment, // connector body double cr, // circle radius const ChVector<>& p1, // segment end point 1 const ChVector<>& p2 // segment end point 2 ) { // Find closest point on segment to circle center: X = p1 + t * (p2-p1) ChVector<> s = p2 - p1; double t = Vdot(-p1, s) / Vdot(s, s); ChClampValue(t, 0.0, 1.0); ChVector<> pt_segement = p1 + t * s; // No contact if circle center is too far from segment. double dist2 = pt_segement.Length2(); if (dist2 >= cr * cr) return; // Generate contact information (still in sprocket frame) double dist = std::sqrt(dist2); ChVector<> normal = pt_segement / dist; ChVector<> pt_gear = cr * normal; // Fill in contact information and add the contact to the system. // Express all vectors in the global frame collision::ChCollisionInfo contact; contact.modelA = m_sprocket->GetGearBody()->GetCollisionModel().get(); contact.modelB = BeltSegment->GetCollisionModel().get(); contact.vN = m_sprocket->GetGearBody()->TransformDirectionLocalToParent(normal); contact.vpA = m_sprocket->GetGearBody()->TransformPointLocalToParent(pt_gear); contact.vpB = m_sprocket->GetGearBody()->TransformPointLocalToParent(pt_segement); contact.distance = dist - cr; ////contact.eff_radius = cr; m_sprocket->GetGearBody()->GetSystem()->GetContactContainer()->AddContact(contact); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- ChSprocketBand::ChSprocketBand(const std::string& name) : ChSprocket(name) {} // ----------------------------------------------------------------------------- // Initialize this sprocket subsystem. // ----------------------------------------------------------------------------- void ChSprocketBand::Initialize(std::shared_ptr<ChBodyAuxRef> chassis, const ChVector<>& location, ChTrackAssembly* track) { // Invoke the base class method ChSprocket::Initialize(chassis, location, track); double radius = GetOuterRadius(); double width = 0.5 * (GetGuideWheelWidth() - GetGuideWheelGap()); double offset = 0.25 * (GetGuideWheelWidth() + GetGuideWheelGap()); m_gear->GetCollisionModel()->ClearModel(); m_gear->GetCollisionModel()->SetFamily(TrackedCollisionFamily::WHEELS); m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(TrackedCollisionFamily::IDLERS); m_gear->GetCollisionModel()->AddCylinder(radius, radius, width / 2, ChVector<>(0, offset, 0)); m_gear->GetCollisionModel()->AddCylinder(radius, radius, width / 2, ChVector<>(0, -offset, 0)); m_gear->GetCollisionModel()->BuildModel(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChSprocketBand::AddVisualizationAssets(VisualizationType vis) { if (vis == VisualizationType::NONE) return; ChSprocket::AddVisualizationAssets(vis); double radius = GetOuterRadius(); double width = GetGuideWheelWidth(); double gap = GetGuideWheelGap(); auto cyl_1 = std::make_shared<ChCylinderShape>(); cyl_1->GetCylinderGeometry().p1 = ChVector<>(0, width / 2, 0); cyl_1->GetCylinderGeometry().p2 = ChVector<>(0, gap / 2, 0); cyl_1->GetCylinderGeometry().rad = radius; m_gear->AddAsset(cyl_1); auto cyl_2 = std::make_shared<ChCylinderShape>(); cyl_2->GetCylinderGeometry().p1 = ChVector<>(0, -width / 2, 0); cyl_2->GetCylinderGeometry().p2 = ChVector<>(0, -gap / 2, 0); cyl_2->GetCylinderGeometry().rad = radius; m_gear->AddAsset(cyl_2); auto tex = std::make_shared<ChTexture>(); tex->SetTextureFilename(chrono::GetChronoDataFile("greenwhite.png")); m_gear->AddAsset(tex); } void ChSprocketBand::RemoveVisualizationAssets() { m_gear->GetAssets().clear(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- ChSystem::CustomCollisionCallback* ChSprocketBand::GetCollisionCallback(ChTrackAssembly* track) { // Check compatibility between this type of sprocket and the track shoes. // We expect track shoes of type ChTrackShoeBand. auto shoe = std::dynamic_pointer_cast<ChTrackShoeBand>(track->GetTrackShoe(0)); assert(shoe); // Extract parameterization of sprocket profile int sprocket_nteeth = GetNumTeeth(); // Create and return the callback object. Note: this pointer will be freed by the base class. return new SprocketBandContactCB(track, 0.005, GetNumTeeth(), GetSeparation()); } // ----------------------------------------------------------------------------- // Create and return the sprocket gear profile. // ----------------------------------------------------------------------------- std::shared_ptr<geometry::ChLinePath> ChSprocketBand::GetProfile() { auto profile = std::make_shared<geometry::ChLinePath>(); int num_teeth = GetNumTeeth(); double OutRad = GetOuterRadius(); double BaseLen = GetBaseWidth(); double TipLen = GetTipWidth(); double Depth = GetToothDepth(); double ArcRad = GetArcRadius(); ChVector<> SprocketCtr(0.0, 0.0, 0.0); // The angle between the centers of two sequential teeth on the sprocket double EntireToothArcAng = CH_C_2PI / num_teeth; // The angle measured from the center of the sprocket between the center of the tooth // and the outer line segment edge of the tooth's base width double HalfBaseWidthCordAng = std::asin((BaseLen / 2) / OutRad); // The angle measured at the center of the sprocket bewteen the end of one tooth profile // and the start of the next (angle where the profile runs along the outer radius // of the sprocket) double OuterRadArcAng = EntireToothArcAng - 2 * HalfBaseWidthCordAng; for (int i = 0; i < num_teeth; ++i) { double CtrAng = -i * EntireToothArcAng; // Vectors defining the current tooth's radial and perpendicular vectors ChVector<> vec_Radial(std::cos(CtrAng), std::sin(CtrAng), 0); ChVector<> vec_Perp(-vec_Radial.y(), vec_Radial.x(), 0); // Points defining the sprocket tooth's base width ChVector<> ToothBaseWidthUpperPnt(OutRad * (std::cos(CtrAng + HalfBaseWidthCordAng)), OutRad * (std::sin(CtrAng + HalfBaseWidthCordAng)), 0); ChVector<> ToothBaseWidthLowerPnt(OutRad * (std::cos(CtrAng - HalfBaseWidthCordAng)), OutRad * (std::sin(CtrAng - HalfBaseWidthCordAng)), 0); ChVector<> ToothBaseWidthCtrPnt = 0.5 * (ToothBaseWidthUpperPnt + ToothBaseWidthLowerPnt); // Points defining the sprocket tooth's tip width ChVector<> ToothTipWidthCtrPnt = ToothBaseWidthCtrPnt - Depth * vec_Radial; ChVector<> ToothTipWidthUpperPnt = ToothTipWidthCtrPnt + 0.5 * TipLen * vec_Perp; ChVector<> ToothTipWidthLowerPnt = ToothTipWidthCtrPnt - 0.5 * TipLen * vec_Perp; // Points defining the tip to tooth base chord midpoint for the concave tooth profile double ToothArcChordLen = std::sqrt(Depth * Depth + std::pow((BaseLen - TipLen) / 2, 2)); ChVector<> ToothUpperChordMidPnt = 0.5 * (ToothBaseWidthUpperPnt + ToothTipWidthUpperPnt); ChVector<> ToothLowerChordMidPnt = 0.5 * (ToothBaseWidthLowerPnt + ToothTipWidthLowerPnt); // Define the distance to project perpendicular to the tooth arc chord at the chord's center // to reach the center of the tooth arc circles double ToothArcChordRadiusSegmentLen = sqrt(ArcRad * ArcRad - std::pow(ToothArcChordLen / 2, 2)); // Define the arc centers for the tooth concave profiles ChVector<> vec_Chord1 = ToothBaseWidthUpperPnt - ToothTipWidthUpperPnt; vec_Chord1.Normalize(); ChVector<> vec_Chord1Perp(-vec_Chord1.y(), vec_Chord1.x(), 0); ChVector<> vec_Chord2 = ToothBaseWidthLowerPnt - ToothTipWidthLowerPnt; vec_Chord2.Normalize(); ChVector<> vec_Chord2Perp(-vec_Chord2.y(), vec_Chord2.x(), 0); ChVector<> ToothUpperArcCtrPnt = ToothUpperChordMidPnt - vec_Chord1Perp * ToothArcChordRadiusSegmentLen; ChVector<> ToothLowerArcCtrPnt = ToothLowerChordMidPnt + vec_Chord2Perp * ToothArcChordRadiusSegmentLen; // Calculate the starting and ending arc angles for each concave tooth profile double UpperArc_Angle1 = std::atan2(ToothBaseWidthUpperPnt.y() - ToothUpperArcCtrPnt.y(), ToothBaseWidthUpperPnt.x() - ToothUpperArcCtrPnt.x()); double UpperArc_Angle2 = std::atan2(ToothTipWidthUpperPnt.y() - ToothUpperArcCtrPnt.y(), ToothTipWidthUpperPnt.x() - ToothUpperArcCtrPnt.x()); // Ensure that Angle1 is positive UpperArc_Angle1 = UpperArc_Angle1 < 0 ? UpperArc_Angle1 + CH_C_2PI : UpperArc_Angle1; // Ensure that Angle2 is greater than Angle1 while (UpperArc_Angle2 < UpperArc_Angle1) { UpperArc_Angle2 += CH_C_2PI; } double LowerArc_Angle1 = std::atan2(ToothTipWidthLowerPnt.y() - ToothLowerArcCtrPnt.y(), ToothTipWidthLowerPnt.x() - ToothLowerArcCtrPnt.x()); double LowerArc_Angle2 = std::atan2(ToothBaseWidthLowerPnt.y() - ToothLowerArcCtrPnt.y(), ToothBaseWidthLowerPnt.x() - ToothLowerArcCtrPnt.x()); // Ensure that Angle1 is positive LowerArc_Angle1 = LowerArc_Angle1 < 0 ? LowerArc_Angle1 + CH_C_2PI : LowerArc_Angle1; // Ensure that Angle2 is greater than Angle1 while (LowerArc_Angle2 < LowerArc_Angle1) { LowerArc_Angle2 += CH_C_2PI; } // Calculate the starting and ending arc angles for profile along the sprocket's outer radius double OuterArc_Angle1 = CtrAng - HalfBaseWidthCordAng; double OuterArc_Angle2 = OuterArc_Angle1 - OuterRadArcAng; // Start the profile geometry with the upper concave tooth arc geometry::ChLineArc arc1(ChCoordsys<>(ToothUpperArcCtrPnt), ArcRad, UpperArc_Angle1, UpperArc_Angle2, true); // Next is the straight segment for the tooth tip geometry::ChLineSegment seg2(ToothTipWidthUpperPnt, ToothTipWidthLowerPnt); // Next is the lower concave tooth arc geometry::ChLineArc arc3(ChCoordsys<>(ToothLowerArcCtrPnt), ArcRad, LowerArc_Angle1, LowerArc_Angle2, true); // Finally is the arc segment that runs along the sprocket's outer radius to the start of the next tooth profile geometry::ChLineArc arc4(ChCoordsys<>(SprocketCtr), OutRad, OuterArc_Angle1, OuterArc_Angle2); // Add this tooth segments profile to the sprocket profile profile->AddSubLine(arc1); profile->AddSubLine(seg2); profile->AddSubLine(arc3); profile->AddSubLine(arc4); } return profile; } } // end namespace vehicle } // end namespace chrono
{ "content_hash": "dbcb99f18ea15c1a6d1cd1ff54adb578", "timestamp": "", "source": "github", "line_count": 758, "max_line_length": 120, "avg_line_length": 57.16490765171504, "alnum_prop": 0.6216334725716, "repo_name": "armanpazouki/chrono", "id": "f2b38499eb2fdb9f913c24518c9437e0daa24adb", "size": "44472", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/chrono_vehicle/tracked_vehicle/sprocket/ChSprocketBand.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3754" }, { "name": "C", "bytes": "2094018" }, { "name": "C++", "bytes": "18310783" }, { "name": "CMake", "bytes": "456720" }, { "name": "CSS", "bytes": "170229" }, { "name": "Cuda", "bytes": "702762" }, { "name": "GLSL", "bytes": "4731" }, { "name": "HTML", "bytes": "7903" }, { "name": "Inno Setup", "bytes": "24125" }, { "name": "JavaScript", "bytes": "4731" }, { "name": "Lex", "bytes": "3433" }, { "name": "Objective-C", "bytes": "2096" }, { "name": "POV-Ray SDL", "bytes": "23109" }, { "name": "Python", "bytes": "186160" }, { "name": "Shell", "bytes": "1459" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Device_Vestel</title> <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css"> <link rel="stylesheet" href="../assets/css/main.css" id="site_styles"> <link rel="shortcut icon" type="image/png" href="../assets/favicon.png"> <script src="../assets/vendor/yui-min.js"></script> </head> <body> <div id="doc"> <header class="main-header"> <div class="content"> <div class="project-title"> </div> <ul class="jump-links"> <li><a href="#index" class="index-jump-link">index</a></li> <li><a href="#top" class="top-jump-link">top</a></li> </ul> </div> </header> <div id="bd" class="main-body"> <div id="docs-sidebar" class="sidebar apidocs"> <div id="api-list"> <div id="api-tabview" class="tabview"> <ul class="tabs"> <li><a href="#api-classes">Classes</a></li> <li><a href="#api-modules">Modules</a></li> </ul> <div id="api-tabview-filter"> <input type="search" id="api-filter" placeholder="Type to filter APIs"> </div> <div id="api-tabview-panel"> <ul id="api-classes" class="apis classes"> <li><a class="type" href="../classes/Audio.html">Audio</a></li> <li><a class="type" href="../classes/Device.html">Device</a></li> <li><a class="type" href="../classes/Device_Arcelik.html">Device_Arcelik</a></li> <li><a class="type" href="../classes/Device_LG.html">Device_LG</a></li> <li><a class="type" href="../classes/Device_Philips.html">Device_Philips</a></li> <li><a class="type" href="../classes/Device_Samsung.html">Device_Samsung</a></li> <li><a class="type" href="../classes/Device_Tizen.html">Device_Tizen</a></li> <li><a class="type" href="../classes/Device_Vestel.html">Device_Vestel</a></li> <li><a class="type" href="../classes/Device_Web.html">Device_Web</a></li> <li><a class="type" href="../classes/Device_WebOs.html">Device_WebOs</a></li> <li><a class="type" href="../classes/Events.html">Events</a></li> <li><a class="type" href="../classes/Logger.html">Logger</a></li> <li><a class="type" href="../classes/Player.html">Player</a></li> <li><a class="type" href="../classes/Subtitle.html">Subtitle</a></li> <li><a class="type" href="../classes/Xhr.html">Xhr</a></li> </ul> <ul id="api-modules" class="apis modules"> </ul> </div> </div> </div> </div> <div id="docs-main" class="apidocs"> <div class="content container"> <h1>Device_Vestel Class</h1> <div class="box meta"> <div class="extends"> Extends <a href="../classes/Device.html" class="crosslink">Device</a> </div> <div class="foundat"> Defined in: <a href="../files/src_core_devices_vestel.js.html#l6"><code>src\core\devices\vestel.js:6</code></a> </div> </div> <div class="box intro"> <p>This is extendable class for Vestel group devices</p> </div> <!-- Class member index --> <a name="index" class="anchor-link"></a> <div class="index"> <h2>Index</h2> <div id="api-options"> Show: <label for="api-show-inherited"> <input type="checkbox" id="api-show-inherited"> Inherited </label> <label for="api-show-protected"> <input type="checkbox" id="api-show-protected"> Protected </label> <label for="api-show-private"> <input type="checkbox" id="api-show-private"> Private </label> <label for="api-show-deprecated"> <input type="checkbox" id="api-show-deprecated"> Deprecated </label> </div> <div class="index-section methods"> <h3>Methods</h3> <ul class="index-list methods extends"> <li class="index-item method constructor"> <a href="#method_Device_Vestel">Device_Vestel</a> <span class="flag constructor">constructor</span> </li> <li class="index-item method"> <a href="#method_createVideoElement">createVideoElement</a> </li> <li class="index-item method inherited"> <a href="#method_initEvents">initEvents</a> </li> <li class="index-item method inherited"> <a href="#method_initPlayerClass">initPlayerClass</a> </li> </ul> </div> </div> <div class="class-detail"> <div class="constructor"> <h2>Constructor</h2> <a name="method_Device_Vestel" class="anchor-link"></a> <div class="method item"> <h3 class="name"><code>Device_Vestel</code> <span class="paren">()</span> </h3> <div class="meta"> <p> Defined in <a href="../files/src_core_devices_vestel.js.html#l6"><code>src\core\devices\vestel.js:6</code></a> </p> </div> <div class="extended-detail"> <div class="description"> </div> </div> </div> </div> <div class="methods-detail"> <h2>Methods</h2> <a name="method_createVideoElement" class="anchor-link"></a> <div class="method item"> <h3 class="name"><code>createVideoElement</code> <span class="paren">()</span> <span class="returns-inline"> <span class="type">Boolean</span> </span> </h3> <div class="meta"> <p> Defined in <a href="../files/src_core_devices_vestel.js.html#l25"><code>src\core\devices\vestel.js:25</code></a> </p> </div> <div class="extended-detail"> <div class="description"> <p>Abstract Player createVideoElement function.</p> </div> <div class="returns"> <h4>Returns:</h4> <div class="returns-description"> <span class="type">Boolean</span>: <p>true</p> </div> </div> </div> </div> <a name="method_initEvents" class="anchor-link"></a> <div class="method item inherited"> <h3 class="name"><code>initEvents</code> <span class="paren">()</span> <span class="returns-inline"> <span class="type">Object</span> </span> </h3> <div class="meta"> <p>Inherited from <a href="../classes/Device.html#method_initEvents" class="type">Device</a>: <a href="../files/src_core_device.js.html#l29"><code>src\core\device.js:29</code></a> </p> </div> <div class="extended-detail"> <div class="description"> Events are based on class. So it have to be constructed. </div> <div class="returns"> <h4>Returns:</h4> <div class="returns-description"> <span class="type">Object</span>: It returns Events class </div> </div> </div> </div> <a name="method_initPlayerClass" class="anchor-link"></a> <div class="method item inherited"> <h3 class="name"><code>initPlayerClass</code> <span class="paren">()</span> <span class="returns-inline"> <span class="type">Object</span> </span> </h3> <div class="meta"> <p>Inherited from <a href="../classes/Device.html#method_initPlayerClass" class="type">Device</a>: <a href="../files/src_core_device.js.html#l42"><code>src\core\device.js:42</code></a> </p> </div> <div class="extended-detail"> <div class="description"> This function stands for initializing Player class It uses currentDevice and config info (extended during device extending) It pass Events to Player class to use same initialized class </div> <div class="returns"> <h4>Returns:</h4> <div class="returns-description"> <span class="type">Object</span>: It returns Events class </div> </div> </div> </div> <div class="no-visible-items-message"> <p>There are no methods that match your current filter settings. You can change your filter settings in the index section on this page. <a href="#index" class="index-jump-link">index</a></p> </div> </div> </div> </div> </div> </div> </div> <script src="../assets/vendor/prettify/prettify-min.js"></script> <script>prettyPrint();</script> <script src="../assets/vendor/jquery.min.js"></script> <script src="../assets/js/jquery-offscreen-trigger.js"></script> <script src="../assets/js/yui-prettify.js"></script> <script src="../assets/../api.js"></script> <script src="../assets/js/api-filter.js"></script> <script src="../assets/js/api-list.js"></script> <script src="../assets/js/api-search.js"></script> <script src="../assets/js/apidocs.js"></script> </body> </html>
{ "content_hash": "f05f5b2430d900b66476dff18b33ec3c", "timestamp": "", "source": "github", "line_count": 363, "max_line_length": 218, "avg_line_length": 45.17906336088154, "alnum_prop": 0.30628048780487804, "repo_name": "dogantv/smarttv", "id": "e84c70934da0a565b6c576b88bb0ebbae8359393", "size": "16400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/generated/classes/Device_Vestel.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "414014" }, { "name": "HTML", "bytes": "697498" }, { "name": "JavaScript", "bytes": "171544" } ], "symlink_target": "" }
package org.switchyard.serial.graph.node; import javax.xml.namespace.QName; import org.switchyard.serial.graph.Graph; /** * A node representing a QName. * * @author David Ward &lt;<a href="mailto:dward@jboss.org">dward@jboss.org</a>&gt; &copy; 2012 Red Hat Inc. */ @SuppressWarnings("serial") public final class QNameNode implements Node { private String _namespaceURI; private String _localPart; private String _prefix; /** * Default constructor. */ public QNameNode() {} /** * Gets the namespace uri. * @return the namespace uri */ public String getNamespaceURI() { return _namespaceURI; } /** * Sets the namespace uri. * @param namespaceURI the namespace uri */ public void setNamespaceURI(String namespaceURI) { _namespaceURI = namespaceURI; } /** * Gets the local part. * @return the local part */ public String getLocalPart() { return _localPart; } /** * Sets the local part. * @param localPart the local part */ public void setLocalPart(String localPart) { _localPart = localPart; } /** * Gets the prefix. * @return the prefix */ public String getPrefix() { return _prefix; } /** * Sets the prefix. * @param prefix the prefix */ public void setPrefix(String prefix) { _prefix = prefix; } /** * {@inheritDoc} */ @Override public void compose(Object obj, Graph graph) { QName qname = (QName)obj; setNamespaceURI(qname.getNamespaceURI()); setLocalPart(qname.getLocalPart()); setPrefix(qname.getPrefix()); } /** * {@inheritDoc} */ @Override public Object decompose(Graph graph) { return new QName(getNamespaceURI(), getLocalPart(), getPrefix()); } }
{ "content_hash": "fd24c9d70778450f0d5a28cebb955af6", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 107, "avg_line_length": 20.695652173913043, "alnum_prop": 0.5898109243697479, "repo_name": "tadayosi/switchyard", "id": "a26e7dee5adc4b51ada8e25d8afa5449f18bf72f", "size": "2537", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "core/serial/base/src/main/java/org/switchyard/serial/graph/node/QNameNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1387" }, { "name": "CSS", "bytes": "1428" }, { "name": "Clojure", "bytes": "239" }, { "name": "HTML", "bytes": "12878" }, { "name": "Java", "bytes": "9850364" }, { "name": "Ruby", "bytes": "1772" }, { "name": "XSLT", "bytes": "84991" } ], "symlink_target": "" }
package java.security.interfaces; import java.security.InvalidParameterException; import java.security.SecureRandom; /** * This interface contains methods for intializing a Digital Signature * Algorithm key generation engine. The initialize methods may be called * any number of times. If no explicity initialization call is made, then * the engine defaults to generating 1024-bit keys using pre-calculated * base, prime, and subprime values. * * @version 0.0 * * @author Aaron M. Renn (arenn@urbanophile.com) */ public interface DSAKeyPairGenerator { /** * Initializes the key generator with the specified DSA parameters and * random bit source * * @param params The DSA parameters to use * @param random The random bit source to use * * @exception InvalidParameterException If the parameters passed are not valid */ void initialize (DSAParams params, SecureRandom random) throws InvalidParameterException; /** * Initializes the key generator to a give modulus. If the <code>genParams</code> * value is <code>true</code> then new base, prime, and subprime values * will be generated for the given modulus. If not, the pre-calculated * values will be used. If no pre-calculated values exist for the specified * modulus, an exception will be thrown. It is guaranteed that there will * always be pre-calculated values for all modulus values between 512 and * 1024 bits inclusives. * * @param modlen The modulus length * @param genParams <code>true</code> to generate new DSA parameters, <code>false</code> otherwise * @param random The random bit source to use * * @exception InvalidParameterException If a parameter is invalid */ void initialize (int modlen, boolean genParams, SecureRandom random) throws InvalidParameterException; }
{ "content_hash": "15d4d76cd8aa3753eef93c780e0ceb07", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 100, "avg_line_length": 36.74, "alnum_prop": 0.7408818726183996, "repo_name": "the-linix-project/linix-kernel-source", "id": "e657c54b4e6f973706eced7bdd7736274fca0d31", "size": "3613", "binary": false, "copies": "182", "ref": "refs/heads/master", "path": "gccsrc/gcc-4.7.2/libjava/classpath/java/security/interfaces/DSAKeyPairGenerator.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ada", "bytes": "38139979" }, { "name": "Assembly", "bytes": "3723477" }, { "name": "Awk", "bytes": "83739" }, { "name": "C", "bytes": "103607293" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "38577421" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "32588" }, { "name": "Emacs Lisp", "bytes": "13451" }, { "name": "FORTRAN", "bytes": "4294984" }, { "name": "GAP", "bytes": "13089" }, { "name": "Go", "bytes": "11277335" }, { "name": "Haskell", "bytes": "2415" }, { "name": "Java", "bytes": "45298678" }, { "name": "JavaScript", "bytes": "6265" }, { "name": "Matlab", "bytes": "56" }, { "name": "OCaml", "bytes": "148372" }, { "name": "Objective-C", "bytes": "995127" }, { "name": "Objective-C++", "bytes": "436045" }, { "name": "PHP", "bytes": "12361" }, { "name": "Pascal", "bytes": "40318" }, { "name": "Perl", "bytes": "358808" }, { "name": "Python", "bytes": "60178" }, { "name": "SAS", "bytes": "1711" }, { "name": "Scilab", "bytes": "258457" }, { "name": "Shell", "bytes": "2610907" }, { "name": "Tcl", "bytes": "17983" }, { "name": "TeX", "bytes": "1455571" }, { "name": "XSLT", "bytes": "156419" } ], "symlink_target": "" }
/***************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * */ #include "test.h" #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #include <curl/mprintf.h> #include "memdebug.h" /* build request url */ static char *suburl(const char *base, int i) { return curl_maprintf("%s%.4d", base, i); } /* * Test the Client->Server ANNOUNCE functionality (PUT style) */ int test(char *URL) { int res; CURL *curl; int sdp; FILE *sdpf = NULL; struct_stat file_info; char *stream_uri = NULL; int request=1; struct curl_slist *custom_headers=NULL; if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { fprintf(stderr, "curl_global_init() failed\n"); return TEST_ERR_MAJOR_BAD; } if ((curl = curl_easy_init()) == NULL) { fprintf(stderr, "curl_easy_init() failed\n"); curl_global_cleanup(); return TEST_ERR_MAJOR_BAD; } test_setopt(curl, CURLOPT_HEADERDATA, stdout); test_setopt(curl, CURLOPT_WRITEDATA, stdout); test_setopt(curl, CURLOPT_URL, URL); if((stream_uri = suburl(URL, request++)) == NULL) { res = TEST_ERR_MAJOR_BAD; goto test_cleanup; } test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); free(stream_uri); stream_uri = NULL; sdp = open("log/file568.txt", O_RDONLY); fstat(sdp, &file_info); close(sdp); sdpf = fopen("log/file568.txt", "rb"); if(sdpf == NULL) { fprintf(stderr, "can't open log/file568.txt\n"); res = TEST_ERR_MAJOR_BAD; goto test_cleanup; } test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_ANNOUNCE); test_setopt(curl, CURLOPT_READDATA, sdpf); test_setopt(curl, CURLOPT_UPLOAD, 1L); test_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t) file_info.st_size); /* Do the ANNOUNCE */ res = curl_easy_perform(curl); if(res) goto test_cleanup; test_setopt(curl, CURLOPT_UPLOAD, 0L); fclose(sdpf); sdpf = NULL; /* Make sure we can do a normal request now */ if((stream_uri = suburl(URL, request++)) == NULL) { res = TEST_ERR_MAJOR_BAD; goto test_cleanup; } test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); free(stream_uri); stream_uri = NULL; test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_DESCRIBE); res = curl_easy_perform(curl); if(res) goto test_cleanup; /* Now do a POST style one */ if((stream_uri = suburl(URL, request++)) == NULL) { res = TEST_ERR_MAJOR_BAD; goto test_cleanup; } test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); free(stream_uri); stream_uri = NULL; custom_headers = curl_slist_append(custom_headers, "Content-Type: posty goodness"); if(!custom_headers) { res = TEST_ERR_MAJOR_BAD; goto test_cleanup; } test_setopt(curl, CURLOPT_RTSPHEADER, custom_headers); test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_ANNOUNCE); test_setopt(curl, CURLOPT_POSTFIELDS, "postyfield=postystuff&project=curl\n"); res = curl_easy_perform(curl); if(res) goto test_cleanup; test_setopt(curl, CURLOPT_POSTFIELDS, NULL); test_setopt(curl, CURLOPT_RTSPHEADER, NULL); curl_slist_free_all(custom_headers); custom_headers = NULL; /* Make sure we can do a normal request now */ if((stream_uri = suburl(URL, request++)) == NULL) { res = TEST_ERR_MAJOR_BAD; goto test_cleanup; } test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); free(stream_uri); stream_uri = NULL; test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); res = curl_easy_perform(curl); test_cleanup: if(sdpf) fclose(sdpf); if(stream_uri) free(stream_uri); if(custom_headers) curl_slist_free_all(custom_headers); curl_easy_cleanup(curl); curl_global_cleanup(); return res; }
{ "content_hash": "27b93fc4bc9a5cab4377c09244ba9081", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 80, "avg_line_length": 24.803680981595093, "alnum_prop": 0.6002968093000247, "repo_name": "racker/omnibus", "id": "1f16664cb8d73e2c5ebe1613d0d77ec15cf9e457", "size": "4043", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "source/curl-7.21.2/tests/libtest/lib568.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "21896" }, { "name": "ActionScript", "bytes": "7811" }, { "name": "Ada", "bytes": "913692" }, { "name": "Assembly", "bytes": "546596" }, { "name": "Awk", "bytes": "147229" }, { "name": "C", "bytes": "118056858" }, { "name": "C#", "bytes": "1871806" }, { "name": "C++", "bytes": "28581121" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "162089" }, { "name": "Clojure", "bytes": "79070" }, { "name": "D", "bytes": "4925" }, { "name": "DOT", "bytes": "1898" }, { "name": "Emacs Lisp", "bytes": "625560" }, { "name": "Erlang", "bytes": "79712366" }, { "name": "FORTRAN", "bytes": "3755" }, { "name": "Java", "bytes": "5632652" }, { "name": "JavaScript", "bytes": "1240931" }, { "name": "Logos", "bytes": "119270" }, { "name": "Objective-C", "bytes": "1088478" }, { "name": "PHP", "bytes": "39064" }, { "name": "Pascal", "bytes": "66389" }, { "name": "Perl", "bytes": "4971637" }, { "name": "PowerShell", "bytes": "1885" }, { "name": "Prolog", "bytes": "5214" }, { "name": "Python", "bytes": "912999" }, { "name": "R", "bytes": "4009" }, { "name": "Racket", "bytes": "2713" }, { "name": "Ragel in Ruby Host", "bytes": "24585" }, { "name": "Rebol", "bytes": "106436" }, { "name": "Ruby", "bytes": "27360215" }, { "name": "Scala", "bytes": "5487" }, { "name": "Scheme", "bytes": "5036" }, { "name": "Scilab", "bytes": "771" }, { "name": "Shell", "bytes": "8793006" }, { "name": "Tcl", "bytes": "3330919" }, { "name": "Visual Basic", "bytes": "10926" }, { "name": "XQuery", "bytes": "4276" }, { "name": "XSLT", "bytes": "2003063" }, { "name": "eC", "bytes": "4568" } ], "symlink_target": "" }
import { ResetHybridCloud } from "../../"; export = ResetHybridCloud;
{ "content_hash": "e80d0854809969c7115388ca7e40919b", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 42, "avg_line_length": 23.666666666666668, "alnum_prop": 0.676056338028169, "repo_name": "markogresak/DefinitelyTyped", "id": "a342e95a7999b6349b432dbd62a8dca3dcfda1d5", "size": "71", "binary": false, "copies": "30", "ref": "refs/heads/master", "path": "types/carbon__pictograms-react/lib/reset--hybrid--cloud/index.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "17426898" } ], "symlink_target": "" }
"use strict"; var assert = require("assert"); var blessed = require("blessed"); var contrib = require("blessed-contrib"); exports.tryCatch = function (done, func) { try { func(); done(); } catch (err) { done(err); } }; exports.getTestContainer = function (sandbox) { assert(sandbox, "getTestContainer requires sandbox"); var mockScreen = { on: sandbox.stub(), append: sandbox.stub(), remove: sandbox.stub(), type: "screen", setEffects: sandbox.stub(), _events: {}, clickable: [], keyable: [], rewindFocus: sandbox.stub(), _listenKeys: sandbox.stub(), _listenMouse: sandbox.stub() }; // prevent "Error: no active screen" blessed.Screen.total = 1; blessed.Screen.global = mockScreen; var container = blessed.box({ parent: mockScreen }); sandbox.stub(container, "render"); return container; }; // stub functions that require an active screen exports.stubWidgets = function (sandbox) { assert(sandbox, "stubWidgets requires sandbox"); sandbox.stub(blessed.element.prototype, "setContent"); sandbox.stub(blessed.element.prototype, "setLabel"); sandbox.stub(contrib.line.prototype, "setData"); sandbox.stub(contrib.gauge.prototype, "setData"); sandbox.stub(blessed.scrollablebox.prototype, "getScrollHeight"); sandbox.stub(blessed.element.prototype, "_getHeight"); };
{ "content_hash": "1d0d0446b8e5997a98e0cf2f585fb318", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 67, "avg_line_length": 26.725490196078432, "alnum_prop": 0.6801173881144534, "repo_name": "alexkuz/nodejs-dashboard", "id": "f225e817b081958cc636c36851151954770d8950", "size": "1363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/utils.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "69595" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using Gallio.Common.Collections; using Gallio.Framework.Pattern; using Gallio.Common.Reflection; namespace MbUnit.Framework { /// <summary> /// Specifies a method that is to be invoked after a fixture instance has been /// created to complete its initialization before test fixture setup runs. /// </summary> /// <remarks> /// <para> /// This attribute provides a mechanism for completing the initialization /// of a fixture if the work cannot be completed entirely within the /// constructor. For example, data binding might be used to set fields /// and property values of the fixture instance. Consequently post-construction /// initialization may be required. /// </para> /// <para> /// <see cref="FixtureInitializerAttribute" /> allows initialization to occur /// earlier in the test lifecycle than <see cref="FixtureSetUpAttribute" />. /// </para> /// <para> /// The attribute may be applied to multiple methods within a fixture, however /// the order in which they are processed is undefined. /// </para> /// <para> /// The method to which this attribute is applied must be declared by the /// fixture class and must not have any parameters. The method may be static. /// </para> /// </remarks> [AttributeUsage(PatternAttributeTargets.ContributionMethod, AllowMultiple = false, Inherited = true)] public class FixtureInitializerAttribute : ContributionMethodPatternAttribute { /// <inheritdoc /> protected override void Validate(IPatternScope containingScope, IMethodInfo method) { base.Validate(containingScope, method); if (method.Parameters.Count != 0) ThrowUsageErrorException("A fixture initializer method must not have any parameters."); } /// <inheritdoc /> protected override void DecorateContainingScope(IPatternScope containingScope, IMethodInfo method) { containingScope.TestBuilder.TestInstanceActions.InitializeTestInstanceChain.After( delegate(PatternTestInstanceState testInstanceState) { testInstanceState.InvokeFixtureMethod(method, EmptyArray<KeyValuePair<ISlotInfo, object>>.Instance); }); } } }
{ "content_hash": "de181402449f98ed4698c9ad94b345b1", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 120, "avg_line_length": 42.410714285714285, "alnum_prop": 0.6774736842105263, "repo_name": "citizenmatt/gallio", "id": "bcf27ac0c983ee681bcdd64f59d51f873f90e74b", "size": "3052", "binary": false, "copies": "1", "ref": "refs/heads/resharper_support", "path": "src/MbUnit/MbUnit/Framework/FixtureInitializerAttribute.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "8498" }, { "name": "C", "bytes": "19623" }, { "name": "C#", "bytes": "13782394" }, { "name": "C++", "bytes": "111680" }, { "name": "JavaScript", "bytes": "6388" }, { "name": "Objective-C", "bytes": "2774" }, { "name": "PHP", "bytes": "107627" }, { "name": "PowerShell", "bytes": "11241" }, { "name": "Ruby", "bytes": "3595477" }, { "name": "Visual Basic", "bytes": "12323" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "58720a8b53ae02cc0dc4faede9bbc5a9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d7dd4374e519a0b526da3250d8b26c214375257d", "size": "180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Saprosma/Saprosma dispar/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.yakka.example"> <!-- Flutter needs it to communicate with the running application to allow setting breakpoints, to provide hot reload, etc. --> <uses-permission android:name="android.permission.INTERNET"/> </manifest>
{ "content_hash": "b019fe9bd5a47162515fd5021e545397", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 69, "avg_line_length": 46.42857142857143, "alnum_prop": 0.7138461538461538, "repo_name": "lukef/qr.flutter", "id": "654eca89dbaafe39235591dabd8c22639f022037", "size": "325", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "example/android/app/src/debug/AndroidManifest.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Dart", "bytes": "47590" }, { "name": "Kotlin", "bytes": "122" }, { "name": "Objective-C", "bytes": "37" }, { "name": "Shell", "bytes": "124" }, { "name": "Swift", "bytes": "404" } ], "symlink_target": "" }
package com.intellij.ide.hierarchy.type; import com.intellij.ide.hierarchy.*; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiAnonymousClass; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.presentation.java.ClassPresentationUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.text.MessageFormat; import java.util.Comparator; import java.util.Map; public class TypeHierarchyBrowser extends TypeHierarchyBrowserBase { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.hierarchy.type.TypeHierarchyBrowser"); public TypeHierarchyBrowser(final Project project, final PsiClass psiClass) { super(project, psiClass); } @Override protected boolean isInterface(@NotNull PsiElement psiElement) { return psiElement instanceof PsiClass && ((PsiClass)psiElement).isInterface(); } @Override protected void createTrees(@NotNull Map<String, JTree> trees) { createTreeAndSetupCommonActions(trees, IdeActions.GROUP_TYPE_HIERARCHY_POPUP); } @Override protected void prependActions(@NotNull DefaultActionGroup actionGroup) { super.prependActions(actionGroup); actionGroup.add(new ChangeScopeAction() { @Override protected boolean isEnabled() { return !Comparing.strEqual(getCurrentViewType(), SUPERTYPES_HIERARCHY_TYPE); } }); } @Override protected String getContentDisplayName(@NotNull String typeName, @NotNull PsiElement element) { return MessageFormat.format(typeName, ClassPresentationUtil.getNameForClass((PsiClass)element, false)); } @Override protected PsiElement getElementFromDescriptor(@NotNull HierarchyNodeDescriptor descriptor) { if (!(descriptor instanceof TypeHierarchyNodeDescriptor)) return null; return ((TypeHierarchyNodeDescriptor)descriptor).getPsiClass(); } @Override @Nullable protected JPanel createLegendPanel() { return null; } @Override protected boolean isApplicableElement(@NotNull final PsiElement element) { return element instanceof PsiClass; } @Override protected Comparator<NodeDescriptor> getComparator() { return JavaHierarchyUtil.getComparator(myProject); } @Override protected HierarchyTreeStructure createHierarchyTreeStructure(@NotNull final String typeName, @NotNull final PsiElement psiElement) { if (SUPERTYPES_HIERARCHY_TYPE.equals(typeName)) { return new SupertypesHierarchyTreeStructure(myProject, (PsiClass)psiElement); } else if (SUBTYPES_HIERARCHY_TYPE.equals(typeName)) { return new SubtypesHierarchyTreeStructure(myProject, (PsiClass)psiElement, getCurrentScopeType()); } else if (TYPE_HIERARCHY_TYPE.equals(typeName)) { return new TypeHierarchyTreeStructure(myProject, (PsiClass)psiElement, getCurrentScopeType()); } else { LOG.error("unexpected type: " + typeName); return null; } } @Override protected boolean canBeDeleted(final PsiElement psiElement) { return psiElement instanceof PsiClass && !(psiElement instanceof PsiAnonymousClass); } @Override protected String getQualifiedName(final PsiElement psiElement) { if (psiElement instanceof PsiClass) { return ((PsiClass)psiElement).getQualifiedName(); } return ""; } public static class BaseOnThisTypeAction extends TypeHierarchyBrowserBase.BaseOnThisTypeAction { @Override protected boolean isEnabled(@NotNull final HierarchyBrowserBaseEx browser, @NotNull final PsiElement psiElement) { return super.isEnabled(browser, psiElement) && !CommonClassNames.JAVA_LANG_OBJECT.equals(((PsiClass)psiElement).getQualifiedName()); } } @NotNull @Override protected TypeHierarchyBrowserBase.BaseOnThisTypeAction createBaseOnThisAction() { return new BaseOnThisTypeAction(); } }
{ "content_hash": "2700c7ba168dcefeceb553088f28cc8f", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 138, "avg_line_length": 35.016666666666666, "alnum_prop": 0.7724892908138982, "repo_name": "goodwinnk/intellij-community", "id": "c2028b57eb1c47bc35f3c51da976ef3f41496c48", "size": "4343", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "java/java-impl/src/com/intellij/ide/hierarchy/type/TypeHierarchyBrowser.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="login_toolbar_height">60dp</dimen> <dimen name="login_prompt_margin_bottom">12dp</dimen> </resources>
{ "content_hash": "fcce406fa845e6b9357869133bd4b2eb", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 55, "avg_line_length": 24.571428571428573, "alnum_prop": 0.6918604651162791, "repo_name": "tomaszrykala/yahnac", "id": "406c8434f52f95de5fb1d5342238133df4270a76", "size": "172", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/res/values-land/dimens-login.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "153161" }, { "name": "Java", "bytes": "371475" } ], "symlink_target": "" }
import '../amp-story-subscriptions'; import * as Preact from '#core/dom/jsx'; import {Services} from '#service'; import {afterRenderPromise} from '#testing/helpers'; import { Action, AmpStoryStoreService, } from '../../../amp-story/1.0/amp-story-store-service'; import {AmpStorySubscriptions} from '../amp-story-subscriptions'; describes.realWin( 'amp-story-subscriptions-v0.1', { amp: { runtimeOn: true, extensions: ['amp-story:1.0', 'amp-story-subscriptions:0.1'], }, }, (env) => { let win; let doc; let subscriptionsEl; let storeService; let storySubscriptions; const nextTick = () => new Promise((resolve) => win.setTimeout(resolve, 0)); beforeEach(() => { win = env.win; doc = win.document; storeService = new AmpStoryStoreService(win); env.sandbox .stub(Services, 'storyStoreServiceForOrNull') .returns(Promise.resolve(storeService)); subscriptionsEl = ( <amp-story-subscriptions layout="container"> </amp-story-subscriptions> ); const storyEl = doc.createElement('amp-story'); storyEl.appendChild(subscriptionsEl); doc.body.appendChild(storyEl); storySubscriptions = new AmpStorySubscriptions(subscriptionsEl); }); it('should contain amp-subscriptions attributes', async () => { await subscriptionsEl.whenBuilt(); expect( subscriptionsEl .querySelector('div') .hasAttribute('subscriptions-dialog') ).to.equal(true); expect( subscriptionsEl .querySelector('div') .getAttribute('subscriptions-display') ).to.equal('NOT granted'); }); it('should display the blocking paywall on state update', async () => { await storySubscriptions.buildCallback(); await nextTick(); storeService.dispatch(Action.TOGGLE_SUBSCRIPTIONS_DIALOG, true); await afterRenderPromise(win); expect(storySubscriptions.element).to.have.class( 'i-amphtml-story-subscriptions-visible' ); }); } );
{ "content_hash": "cf58199e148551719b0a9eb24284b302", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 80, "avg_line_length": 27.342105263157894, "alnum_prop": 0.6400384985563041, "repo_name": "alanorozco/amphtml", "id": "ca1cb386232588a21f616dc8d4aa8026fe51e669", "size": "2078", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "extensions/amp-story-subscriptions/0.1/test/test-amp-story-subscriptions.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "256" }, { "name": "C++", "bytes": "1602173" }, { "name": "CSS", "bytes": "478866" }, { "name": "Go", "bytes": "6528" }, { "name": "HTML", "bytes": "2077804" }, { "name": "JavaScript", "bytes": "18908816" }, { "name": "Python", "bytes": "64486" }, { "name": "Shell", "bytes": "20757" }, { "name": "Starlark", "bytes": "33981" }, { "name": "TypeScript", "bytes": "23157" }, { "name": "Yacc", "bytes": "28669" } ], "symlink_target": "" }
using System.Collections; using UnityEngine; using System; using System.Collections.Generic; namespace tk { public class TcpPrivateAPIHandler : MonoBehaviour { private tk.JsonTcpClient client; public PathManager pathManager; private bool isVerified; void Awake() { pathManager = GameObject.FindObjectOfType<PathManager>(); } public void Init(tk.JsonTcpClient _client) { client = _client; _client.dispatchInMainThread = false; //too slow to wait. _client.dispatcher.Register("verify", new tk.Delegates.OnMsgRecv(OnVerify)); _client.dispatcher.Register("set_random_seed", new tk.Delegates.OnMsgRecv(OnSetRandomSeed)); _client.dispatcher.Register("reset_challenges", new tk.Delegates.OnMsgRecv(OnResetChallenges)); } public tk.JsonTcpClient GetClients() { return client; } bool isPrivateKeyCorrect(string privateKey) { if (privateKey == GlobalState.privateKey) { return true; } else { return false; } } void OnVerify(JSONObject json) { if (isPrivateKeyCorrect(json.GetField("private_key").str)) { isVerified = true; UnityMainThreadDispatcher.Instance().Enqueue(SendIsVerified()); } else { UnityMainThreadDispatcher.Instance().Enqueue(sendErrorMessage("private_key_error", "private_key doesn't correspond, please ensure you entered the right one")); } } void OnSetRandomSeed(JSONObject json) { if (isVerified) { if (pathManager == null) { pathManager = GameObject.FindObjectOfType<PathManager>(); } int new_seed; int.TryParse(json.GetField("seed").str, out new_seed); GlobalState.seed = new_seed; UnityMainThreadDispatcher.Instance().Enqueue(savePlayerPrefsInt("seed", GlobalState.seed)); if (pathManager != null) { UnityMainThreadDispatcher.Instance().Enqueue(pathManager.InitAfterCarPathLoaded(pathManager.challenges)); } } else { UnityMainThreadDispatcher.Instance().Enqueue(sendErrorMessage("private_key_error", "private_key doesn't correspond, please ensure you entered the right one")); } } void OnResetChallenges(JSONObject json) { if (isVerified) { UnityMainThreadDispatcher.Instance().Enqueue(pathManager.InitAfterCarPathLoaded(pathManager.challenges)); } else { UnityMainThreadDispatcher.Instance().Enqueue(sendErrorMessage("private_key_error", "private_key doesn't correspond, please ensure you entered the right one")); } } public IEnumerator SendIsVerified() { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("msg_type", "verified"); client.SendMsg(json); yield return null; } public IEnumerator SendCollisionWithStartingLine(string name, int startingLineIndex, float timeStamp) { if (isVerified) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("msg_type", "collision_with_starting_line"); json.AddField("car_name", name); json.AddField("starting_line_index", startingLineIndex); json.AddField("timeStamp", timeStamp); client.SendMsg(json); } yield return null; } public IEnumerator SendCollisionWithChallenge(string name, int coneIndex, float timeStamp) { if (isVerified) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("msg_type", "collision_with_cone"); json.AddField("car_name", name); json.AddField("cone_index", coneIndex); json.AddField("timeStamp", timeStamp); client.SendMsg(json); } yield return null; } IEnumerator sendErrorMessage(string msgType, string errorMessage) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("msg_type", msgType); json.AddField("error_message", errorMessage); client.SendMsg(json); yield return null; } IEnumerator savePlayerPrefsInt(string key, int value) { PlayerPrefs.SetInt(key, value); PlayerPrefs.Save(); yield return null; } IEnumerator savePlayerPrefsFloat(string key, float value) { PlayerPrefs.SetFloat(key, value); PlayerPrefs.Save(); yield return null; } IEnumerator savePlayerPrefsString(string key, string value) { PlayerPrefs.SetString(key, value); PlayerPrefs.Save(); yield return null; } } }
{ "content_hash": "6c3e043d5d512a1f685e8d501b02f355", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 180, "avg_line_length": 37.268115942028984, "alnum_prop": 0.5897336185105969, "repo_name": "tawnkramer/sdsandbox", "id": "173e53f2196363ca6f80f35499d2888c8e0bfe29", "size": "5143", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdsim/Assets/Scripts/tcp/TcpPrivateAPIHandler.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "1117254" }, { "name": "HLSL", "bytes": "216130" }, { "name": "OpenSCAD", "bytes": "357" }, { "name": "Python", "bytes": "33800" }, { "name": "ShaderLab", "bytes": "182929" } ], "symlink_target": "" }
/*************************************************************************************************/ /*! * \file wsf_sec.h * * \brief AES and random number security service API. * * $Date: 2015-10-15 14:57:57 -0400 (Thu, 15 Oct 2015) $ * $Revision: 4218 $ * * Copyright (c) 2009-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: LicenseRef-PBL * * This file and the related binary are licensed under the * Permissive Binary License, Version 1.0 (the "License"); * you may not use these files except in compliance with the License. * * You may obtain a copy of the License here: * LICENSE-permissive-binary-license-1.0.txt and at * https://www.mbed.com/licenses/PBL-1.0 * * See the License for the specific language governing permissions and * limitations under the License. */ /*************************************************************************************************/ #ifndef WSF_SEC_H #define WSF_SEC_H #include "wsf_types.h" #ifdef __cplusplus extern "C" { #endif /************************************************************************************************** Macros **************************************************************************************************/ /*! CMAC algorithm key length */ #define WSF_CMAC_KEY_LEN 16 /*! CMAC algorithm result length */ #define WSF_CMAC_HASH_LEN 16 /*! ECC algorithm key length */ #define WSF_ECC_KEY_LEN 32 /*! Invalid AES Token */ #define WSF_TOKEN_INVALID 0xFF /************************************************************************************************** Data Types **************************************************************************************************/ /*! AES Security callback parameters structure */ typedef struct { wsfMsgHdr_t hdr; /*! header */ uint8_t *pCiphertext; /*! pointer to 16 bytes of ciphertext data */ } wsfSecMsg_t; /*! AES Security callback are the same as wsfSecMsg_t */ typedef wsfSecMsg_t wsfSecAes_t; /*! CMAC Security callback are the same as wsfSecMsg_t */ typedef wsfSecMsg_t wsfSecCmacMsg_t; /*! ECC Security public/private key pair */ typedef struct { uint8_t pubKey_x[WSF_ECC_KEY_LEN]; /*! x component of ecc public key */ uint8_t pubKey_y[WSF_ECC_KEY_LEN]; /*! y component of ecc public key */ uint8_t privKey[WSF_ECC_KEY_LEN]; /*! ecc private key */ } wsfSecEccKey_t; /*! ECC security DH Key shared secret */ typedef struct { uint8_t secret[WSF_ECC_KEY_LEN]; /*! DH Key Shared secret */ } wsfSecEccSharedSec_t; /*! ECC Security callback parameters structure */ typedef struct { wsfMsgHdr_t hdr; /*! header */ union { wsfSecEccSharedSec_t sharedSecret; /*! shared secret */ wsfSecEccKey_t key; /*! ecc public/private key pair */ } data; } wsfSecEccMsg_t; /************************************************************************************************** Function Declarations **************************************************************************************************/ /*************************************************************************************************/ /*! * \fn WsfSecInit * * \brief Initialize the security service. This function should only be called once * upon system initialization. * * \return None. */ /*************************************************************************************************/ void WsfSecInit(void); /*************************************************************************************************/ /*! * \fn WsfSecRandInit * * \brief Initialize the random number service. This function should only be called once * upon system initialization. * * \return None. */ /*************************************************************************************************/ void WsfSecRandInit(void); /*************************************************************************************************/ /*! * \fn WsfSecAesInit * * \brief Initialize the AES service. This function should only be called once * upon system initialization. * * \return None. */ /*************************************************************************************************/ void WsfSecAesInit(void); /*************************************************************************************************/ /*! * \fn WsfSecCmacInit * * \brief Called to initialize CMAC security. This function should only be called once * upon system initialization. * * \return None. */ /*************************************************************************************************/ void WsfSecCmacInit(void); /*************************************************************************************************/ /*! * \fn WsfSecEccInit * * \brief Called to initialize ECC security. This function should only be called once * upon system initialization. * * \return None. */ /*************************************************************************************************/ void WsfSecEccInit(void); /*************************************************************************************************/ /*! * \fn WsfSecAes * * \brief Execute an AES calculation. When the calculation completes, a WSF message will be * sent to the specified handler. This function returns a token value that * the client can use to match calls to this function with messages. * * \param pKey Pointer to 16 byte key. * \param pPlaintext Pointer to 16 byte plaintext. * \param handlerId WSF handler ID. * \param param Client-defined parameter returned in message. * \param event Event for client's WSF handler. * * \return Token value. */ /*************************************************************************************************/ uint8_t WsfSecAes(uint8_t *pKey, uint8_t *pPlaintext, wsfHandlerId_t handlerId, uint16_t param, uint8_t event); /*************************************************************************************************/ /*! * \fn WsfSecAesCmac * * \brief Execute the CMAC algorithm. * * \param pKey Key used in CMAC operation. * \param pPlaintext Data to perform CMAC operation over * \param len Size of pPlaintext in bytes. * \param handlerId WSF handler ID for client. * \param param Optional parameter sent to client's WSF handler. * \param event Event for client's WSF handler. * * \return TRUE if successful, else FALSE. */ /*************************************************************************************************/ bool_t WsfSecCmac(const uint8_t *pKey, uint8_t *pPlaintext, uint8_t textLen, wsfHandlerId_t handlerId, uint16_t param, uint8_t event); /*************************************************************************************************/ /*! * \fn WsfSecEccGenKey * * \brief Generate an ECC key. * * \param handlerId WSF handler ID for client. * \param param Optional parameter sent to client's WSF handler. * \param event Event for client's WSF handler. * * \return TRUE if successful, else FALSE. */ /*************************************************************************************************/ bool_t WsfSecEccGenKey(wsfHandlerId_t handlerId, uint16_t param, uint8_t event); /*************************************************************************************************/ /*! * \fn WsfSecEccGenSharedSecret * * \brief Generate an ECC key. * * \param pKey ECC Key structure. * \param handlerId WSF handler ID for client. * \param param Optional parameter sent to client's WSF handler. * \param event Event for client's WSF handler. * * \return TRUE if successful, else FALSE. */ /*************************************************************************************************/ bool_t WsfSecEccGenSharedSecret(wsfSecEccKey_t *pKey, wsfHandlerId_t handlerId, uint16_t param, uint8_t event); /*************************************************************************************************/ /*! * \fn WsfSecRand * * \brief This function returns up to 16 bytes of random data to a buffer provided by the * client. * * \param pRand Pointer to returned random data. * \param randLen Length of random data. * * \return None. */ /*************************************************************************************************/ void WsfSecRand(uint8_t *pRand, uint8_t randLen); #ifdef __cplusplus }; #endif #endif /* WSF_SEC_H */
{ "content_hash": "91117f9ccfe3c8cf5fe851935ecb6f54", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 111, "avg_line_length": 35.922764227642276, "alnum_prop": 0.4389498698653389, "repo_name": "tung7970/mbed-os-1", "id": "eda1b9234c151d5c6231319683b5958cbbb5b193", "size": "8837", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "hal/targets/hal/TARGET_ARM_SSG/TARGET_BEETLE/cordio/include/wsf/include/wsf_sec.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "5739225" }, { "name": "C", "bytes": "163905387" }, { "name": "C++", "bytes": "8132346" }, { "name": "CMake", "bytes": "27635" }, { "name": "HTML", "bytes": "1543876" }, { "name": "Makefile", "bytes": "131050" }, { "name": "Objective-C", "bytes": "357234" }, { "name": "Python", "bytes": "18259" }, { "name": "Shell", "bytes": "24790" }, { "name": "XSLT", "bytes": "11192" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebAPIUpload { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
{ "content_hash": "013d8c0e7050cf32fd139881763124cb", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 70, "avg_line_length": 28.82608695652174, "alnum_prop": 0.7119155354449472, "repo_name": "stefer/WebAPIUpload", "id": "59aed4c695e85de3687ca8f319b08877859836d3", "size": "665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/WebAPIUpload/Global.asax.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "C#", "bytes": "170683" }, { "name": "CSS", "bytes": "2626" }, { "name": "HTML", "bytes": "5069" }, { "name": "JavaScript", "bytes": "10918" } ], "symlink_target": "" }
#include <assert.h> #include <stdint.h> #ifdef _MSC_VER #define INLINE #else #define INLINE inline #endif typedef union _pkvBranch_t_* pkvBranch_t; /** * Prefix key tree leaf. */ typedef struct pkvLeaf_t { pkvPair_t* data; // array of key-value pairs (32-bit) size_t dlen; // size of key-value pairs array (32-bit) uint16_t level; // level in tree (zero for leaves) (16-bit) uint16_t split; // number of active bits in center (16-bit) // of key-value pairs array } pkvLeaf_t; // (96-bits) /** * Prefix tree splitting branch. */ typedef struct pkvSplit_t { pkvBranch_t child[2]; // two pointer to branches (64-bit) uint16_t level; // level in tree (non-zero) (16-bit) uint16_t split; // number of active bits in center (16-bit) // of key-value pairs array } pkvSplit_t; // (96-bits) /** * Prefix tree branch super-class. */ union _pkvBranch_t_ { pkvLeaf_t leaf; // can be leaf pkvSplit_t splt; // or can be split }; /** * Prefix tree root. */ struct _pkvTree_t_ { pkvBranch_t root; ///< Tree root pkvPair_t* data; ///< Pointer to key-value array. size_t keylen; ///< Tree full key length }; // This algorithm uses total set bit count of each // byte/short of key to sort kv-array // // Functions to count set bits are heavily used, // so I tested several ways to do this. //#define INTRSIC_WAY #ifdef INTRSIC_WAY // This approach uses standard(?) function "population count" // // __builtin_popcount - gcc specific // __popcnt - vs specific // // Processor with SSE4 built-in support (popcnt instruction). // static INLINE uint16_t bkbits16(uint16_t value) { return __builtin_popcount(value); } static INLINE uint8_t bkbits8(uint8_t value) { return __builtin_popcount(value); } #else #ifdef BK_WAY // // Basic algorithm from Brian Kernighan book. // static INLINE uint16_t bkbits(uint16_t value) { uint16_t c; for (c = 0; value; c++) { value &= value - 1; } return c; } static INLINE uint8_t bkbits(uint8_t value) { uint8_t c; for (c = 0; value; c++) { value &= value - 1; } return c; } #else // // Table based algorithm. // static const unsigned char BitsSetTable256[256] = { # define B2(n) n, n+1, n+1, n+2 # define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2) # define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2) B6(0), B6(1), B6(1), B6(2) }; static INLINE uint16_t bkbits16(uint16_t value) { return BitsSetTable256[value & 0xFF] + BitsSetTable256[(value >> 8)&0xFF]; } static INLINE uint8_t bkbits8(uint8_t value) { return BitsSetTable256[value & 0xFF]; } #endif #endif
{ "content_hash": "bd5dbf6091a5370344700f23c54bff00", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 76, "avg_line_length": 24.541284403669724, "alnum_prop": 0.6250467289719626, "repo_name": "masscry/alpha0", "id": "300c79aa82beafe639e7170166f89e97e171c2a9", "size": "2675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/prefixkv/prfpriv.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "105736" }, { "name": "CMake", "bytes": "1653" } ], "symlink_target": "" }
/*global window document navigator setTimeout clearTimeout alert XMLHttpRequest */ /** * @namespace The global container for Eclipse APIs. */ var eclipse = eclipse || {}; window.editorDivStyleApplied = 0; window.scrollDivStyleApplied = 0; /** * Constructs a new key binding with the given key code and modifiers. * * @param {String|Number} keyCode the key code. * @param {Boolean} mod1 the primary modifier (usually Command on Mac and Control on other platforms). * @param {Boolean} mod2 the secondary modifier (usually Shift). * @param {Boolean} mod3 the third modifier (usually Alt). * @param {Boolean} mod4 the fourth modifier (usually Control on the Mac). * * @class A KeyBinding represents of a key code and a modifier state that can be triggered by the user using the keyboard. * @name eclipse.KeyBinding * * @property {String|Number} keyCode The key code. * @property {Boolean} mod1 The primary modifier (usually Command on Mac and Control on other platforms). * @property {Boolean} mod2 The secondary modifier (usually Shift). * @property {Boolean} mod3 The third modifier (usually Alt). * @property {Boolean} mod4 The fourth modifier (usually Control on the Mac). * * @see eclipse.Editor#setKeyBinding */ eclipse.KeyBinding = (function() { var isMac = navigator.platform.indexOf("Mac") !== -1; /** @private */ function KeyBinding (keyCode, mod1, mod2, mod3, mod4) { if (typeof(keyCode) === "string") { this.keyCode = keyCode.toUpperCase().charCodeAt(0); } else { this.keyCode = keyCode; } this.mod1 = mod1 !== undefined && mod1 !== null ? mod1 : false; this.mod2 = mod2 !== undefined && mod2 !== null ? mod2 : false; this.mod3 = mod3 !== undefined && mod3 !== null ? mod3 : false; this.mod4 = mod4 !== undefined && mod4 !== null ? mod4 : false; } KeyBinding.prototype = /** @lends eclipse.KeyBinding.prototype */ { /** * Returns whether this key binding matches the given key event. * * @param e the key event. * @returns {Boolean} <code>true</code> whether the key binding matches the key event. */ match: function (e) { if (this.keyCode === e.keyCode) { var mod1 = isMac ? e.metaKey : e.ctrlKey; if (this.mod1 !== mod1) { return false; } if (this.mod2 !== e.shiftKey) { return false; } if (this.mod3 !== e.altKey) { return false; } if (isMac && this.mod4 !== e.ctrlKey) { return false; } return true; } return false; }, /** * Returns whether this key binding is the same as the given parameter. * * @param {eclipse.KeyBinding} kb the key binding to compare with. * @returns {Boolean} whether or not the parameter and the receiver describe the same key binding. */ equals: function(kb) { if (!kb) { return false; } if (this.keyCode !== kb.keyCode) { return false; } if (this.mod1 !== kb.mod1) { return false; } if (this.mod2 !== kb.mod2) { return false; } if (this.mod3 !== kb.mod3) { return false; } if (this.mod4 !== kb.mod4) { return false; } return true; } }; return KeyBinding; }()); /** * Constructs a new editor. * * @param options the editor options. * @param {String|DOMElement} options.parent the parent element for the editor, it can be either a DOM element or an ID for a DOM element. * @param {eclipse.TextModel} [options.model] the text model for the editor. If this options is not set the editor creates an empty {@link eclipse.TextModel}. * @param {Boolean} [options.readonly=false] whether or not the editor is read-only. * @param {String|String[]} [options.stylesheet] one or more stylesheet URIs for the editor. * @param {Number} [options.tabSize] The number of spaces in a tab. * * @class A Editor is a user interface for editing text. * @name eclipse.Editor */ eclipse.Editor = (function() { /** @private */ function addHandler(node, type, handler, capture) { if (typeof node.addEventListener === "function") { node.addEventListener(type, handler, capture === true); } else { node.attachEvent("on" + type, handler); } } /** @private */ function removeHandler(node, type, handler, capture) { if (typeof node.removeEventListener === "function") { node.removeEventListener(type, handler, capture === true); } else { node.detachEvent("on" + type, handler); } } var isIE = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); var isFirefox = parseFloat(navigator.userAgent.split("Firefox/")[1] || navigator.userAgent.split("Minefield/")[1]) || 0; var isOpera = navigator.userAgent.indexOf("Opera") !== -1; var isChrome = navigator.userAgent.indexOf("Chrome") !== -1; var isSafari = navigator.userAgent.indexOf("Safari") !== -1; var isWebkit = navigator.userAgent.indexOf("WebKit") !== -1; var isMac = navigator.platform.indexOf("Mac") !== -1; var isWindows = navigator.platform.indexOf("Win") !== -1; var isW3CEvents = typeof window.document.documentElement.addEventListener === "function"; var isRangeRects = !isIE && typeof window.document.createRange().getBoundingClientRect === "function"; /** * Constructs a new Selection object. * * @class A Selection represents a range of selected text in the editor. * @name eclipse.Selection */ var Selection = (function() { /** @private */ function Selection (start, end, caret) { /** * The selection start offset. * * @name eclipse.Selection#start */ this.start = start; /** * The selection end offset. * * @name eclipse.Selection#end */ this.end = end; /** @private */ this.caret = caret; //true if the start, false if the caret is at end } Selection.prototype = /** @lends eclipse.Selection.prototype */ { /** @private */ clone: function() { return new Selection(this.start, this.end, this.caret); }, /** @private */ collapse: function() { if (this.caret) { this.end = this.start; } else { this.start = this.end; } }, /** @private */ extend: function (offset) { if (this.caret) { this.start = offset; } else { this.end = offset; } if (this.start > this.end) { var tmp = this.start; this.start = this.end; this.end = tmp; this.caret = !this.caret; } }, /** @private */ setCaret: function(offset) { this.start = offset; this.end = offset; this.caret = false; }, /** @private */ getCaret: function() { return this.caret ? this.start : this.end; }, /** @private */ toString: function() { return "start=" + this.start + " end=" + this.end + (this.caret ? " caret is at start" : " caret is at end"); }, /** @private */ isEmpty: function() { return this.start === this.end; }, /** @private */ equals: function(object) { return this.caret === object.caret && this.start === object.start && this.end === object.end; } }; return Selection; }()); /** * Constructs a new EventTable object. * * @class * @name eclipse.EventTable * @private */ var EventTable = (function() { /** @private */ function EventTable(){ this._listeners = {}; } EventTable.prototype = /** @lends EventTable.prototype */ { /** @private */ addEventListener: function(type, context, func, data) { if (!this._listeners[type]) { this._listeners[type] = []; } var listener = { context: context, func: func, data: data }; this._listeners[type].push(listener); }, /** @private */ sendEvent: function(type, event) { var listeners = this._listeners[type]; if (listeners) { for (var i=0, len=listeners.length; i < len; i++){ var l = listeners[i]; if (l && l.context && l.func) { l.func.call(l.context, event, l.data); } } } }, /** @private */ removeEventListener: function(type, context, func, data){ var listeners = this._listeners[type]; if (listeners) { for (var i=0, len=listeners.length; i < len; i++){ var l = listeners[i]; if (l.context === context && l.func === func && l.data === data) { listeners.splice(i, 1); break; } } } } }; return EventTable; }()); /** @private */ function Editor (options) { this._init(options); } Editor.prototype = /** @lends eclipse.Editor.prototype */ { /** * Adds an event listener to the editor. * * @param {String} type the event type. The supported events are: * <ul> * <li>"Modify" See {@link #onModify} </li> * <li>"Selection" See {@link #onSelection} </li> * <li>"Scroll" See {@link #onScroll} </li> * <li>"Verify" See {@link #onVerify} </li> * <li>"Destroy" See {@link #onDestroy} </li> * <li>"LineStyle" See {@link #onLineStyle} </li> * <li>"ModelChanging" See {@link #onModelChanging} </li> * <li>"ModelChanged" See {@link #onModelChanged} </li> * </ul> * @param {Object} context the context of the function. * @param {Function} func the function that will be executed when the event happens. * The function should take an event as the first parameter and optional data as the second parameter. * @param {Object} [data] optional data passed to the function. * * @see #removeEventListener */ addEventListener: function(type, context, func, data) { this._eventTable.addEventListener(type, context, func, data); }, /** * @class This interface represents a ruler for the editor. * <p> * A Ruler is a graphical element that is placed either on the left or on the right side of * the editor. It can be used to provide the editor with per line decoration such as line numbering, * bookmarks, breakpoints, folding disclosures, etc. * </p><p> * There are two types of rulers: page and document. A page ruler only shows the content for the lines that are * visible, while a document ruler always shows the whole content. * </p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#addRuler} * </p> * @name eclipse.Ruler * */ /** * Returns the ruler overview type. * * @name getOverview * @methodOf eclipse.Ruler# * @returns {String} the overview type, which is either "page" or "document". * * @see #getLocation */ /** * Returns the ruler location. * * @name getLocation * @methodOf eclipse.Ruler# * @returns {String} the ruler location, which is either "left" or "right". */ /** * Returns the HTML content for the decoration of a given line. * <p> * If the line index is <code>-1</code>, the HTML content for the decoration * that determines the width of the ruler should be returned. * </p> * * @name getHTML * @methodOf eclipse.Ruler# * @param {Number} lineIndex * @returns {String} the HTML content for a given line, or generic line. * * @see #getStyle */ /** * Returns the CSS styling information for the decoration of a given line. * <p> * If the line index is <code>-1</code>, the CSS styling information for the decoration * that determines the width of the ruler should be returned. If the line is * <code>undefined</code>, the ruler styling information should be returned. * </p> * * @name getStyle * @methodOf eclipse.Ruler# * @param {Number} lineIndex * @returns {eclipse.Style} the CSS styling for ruler, given line, or generic line. * * @see #getHTML */ /** * Returns the indices of the lines that have decoration. * <p> * This function is only called for rulers with "document" overview type. * </p> * @name getAnnotations * @methodOf eclipse.Ruler# * @returns {Number[]} an array of line indices. */ /** * This event is sent when the user clicks a line decoration. * * @name onClick * @event * @methodOf eclipse.Ruler# * @param {Number} lineIndex the line index of the clicked decoration * @param {DOMEvent} e the click event */ /** * This event is sent when the user double clicks a line decoration. * * @name onDblClick * @event * @methodOf eclipse.Ruler# * @param {Number} lineIndex the line index of the double clicked decoration * @param {DOMEvent} e the double click event */ /** * Adds a ruler to the editor. * * @param {eclipse.Ruler} ruler the ruler. */ addRuler: function (ruler) { var document = this._frameDocument; var body = document.body; var side = ruler.getLocation(); var rulerParent = side === "left" ? this._leftDiv : this._rightDiv; if (!rulerParent) { rulerParent = document.createElement("DIV"); rulerParent.style.overflow = "hidden"; rulerParent.style.MozUserSelect = "none"; rulerParent.style.WebkitUserSelect = "none"; if (isIE) { rulerParent.attachEvent("onselectstart", function() {return false;}); } rulerParent.style.position = "absolute"; rulerParent.style.top = "0px"; rulerParent.style.cursor = "default"; body.appendChild(rulerParent); if (side === "left") { this._leftDiv = rulerParent; rulerParent.className = "editorLeftRuler"; } else { this._rightDiv = rulerParent; rulerParent.className = "editorRightRuler"; } var table = document.createElement("TABLE"); rulerParent.appendChild(table); table.cellPadding = "0px"; table.cellSpacing = "0px"; table.border = "0px"; table.insertRow(0); var self = this; addHandler(rulerParent, "click", function(e) { self._handleRulerEvent(e); }); addHandler(rulerParent, "dblclick", function(e) { self._handleRulerEvent(e); }); } var div = document.createElement("DIV"); div._ruler = ruler; div.rulerChanged = true; div.style.position = "relative"; var row = rulerParent.firstChild.rows[0]; var index = row.cells.length; var cell = row.insertCell(index); cell.vAlign = "top"; cell.appendChild(div); ruler.setEditor(this); this._updatePage(); }, /** * Converts the given rectangle from one coordinate spaces to another. * <p>The supported coordinate spaces are: * <ul> * <li>"document" - relative to document, the origin is the top-left corner of first line</li> * <li>"page" - relative to html page that contains the editor</li> * <li>"editor" - relative to editor, the origin is the top-left corner of the editor container</li> * </ul> * </p> * <p>All methods in the editor that take or return a position are in the document coordinate space.</p> * * @param rect the rectangle to convert. * @param rect.x the x of the rectangle. * @param rect.y the y of the rectangle. * @param rect.width the width of the rectangle. * @param rect.height the height of the rectangle. * @param {String} from the source coordinate space. * @param {String} to the destination coordinate space. * * @see #getLocationAtOffset * @see #getOffsetAtLocation * @see #getTopPixel * @see #setTopPixel */ convert: function(rect, from, to) { var scroll = this._getScroll(); var editorPad = this._getEditorPadding(); var frame = this._frame.getBoundingClientRect(); var editorRect = this._editorDiv.getBoundingClientRect(); switch(from) { case "document": if (rect.x !== undefined) { rect.x += - scroll.x + editorRect.left + editorPad.left; } if (rect.y !== undefined) { rect.y += - scroll.y + editorRect.top + editorPad.top; } break; case "page": if (rect.x !== undefined) { rect.x += - frame.left; } if (rect.y !== undefined) { rect.y += - frame.top; } break; } //At this point rect is in the widget coordinate space switch (to) { case "document": if (rect.x !== undefined) { rect.x += scroll.x - editorRect.left - editorPad.left; } if (rect.y !== undefined) { rect.y += scroll.y - editorRect.top - editorPad.top; } break; case "page": if (rect.x !== undefined) { rect.x += frame.left; } if (rect.y !== undefined) { rect.y += frame.top; } break; } }, /** * Destroys the editor. * <p> * Removes the editor from the page and frees all resources created by the editor. * Calling this function causes the "Destroy" event to be fire so that all components * attached to editor can release their references. * </p> * * @see #onDestroy */ destroy: function() { this._setGrab(null); this._unhookEvents(); /* Destroy rulers*/ var destroyRulers = function(rulerDiv) { if (!rulerDiv) { return; } var cells = rulerDiv.firstChild.rows[0].cells; for (var i = 0; i < cells.length; i++) { var div = cells[i].firstChild; div._ruler.setEditor(null); } }; destroyRulers (this._leftDiv); destroyRulers (this._rightDiv); /* Destroy timers */ if (this._autoScrollTimerID) { clearTimeout(this._autoScrollTimerID); this._autoScrollTimerID = null; } if (this._updateTimer) { clearTimeout(this._updateTimer); this._updateTimer = null; } /* Destroy DOM */ var parent = this._parent; var frame = this._frame; parent.removeChild(frame); var e = {}; this.onDestroy(e); this._parent = null; this._parentDocument = null; this._model = null; this._selection = null; this._doubleClickSelection = null; this._eventTable = null; this._frame = null; this._frameDocument = null; this._frameWindow = null; this._scrollDiv = null; this._editorDiv = null; this._clientDiv = null; this._overlayDiv = null; this._textArea = null; this._keyBindings = null; this._actions = null; }, /** * Gives focus to the editor. */ focus: function() { /* * Feature in Chrome. When focus is called in the clientDiv without * setting selection the browser will set the selection to the first dom * element, which can be above the client area. When this happen the * browser also scrolls the window to show that element. * The fix is to call _updateDOMSelection() before calling focus(). */ this._updateDOMSelection(); if (isOpera) { this._clientDiv.blur(); } this._clientDiv.focus(); /* * Feature in Safari. When focus is called the browser selects the clientDiv * itself. The fix is to call _updateDOMSelection() after calling focus(). */ this._updateDOMSelection(); }, /** * Returns all action names defined in the editor. * <p> * There are two types of actions, the predefined actions of the editor * and the actions added by application code. * </p> * <p> * The predefined actions are: * <ul> * <li>Navigation actions. These actions move the caret collapsing the selection.</li> * <ul> * <li>"lineUp" - moves the caret up by one line</li> * <li>"lineDown" - moves the caret down by one line</li> * <li>"lineStart" - moves the caret to beginning of the current line</li> * <li>"lineEnd" - moves the caret to end of the current line </li> * <li>"charPrevious" - moves the caret to the previous character</li> * <li>"charNext" - moves the caret to the next character</li> * <li>"pageUp" - moves the caret up by one page</li> * <li>"pageDown" - moves the caret down by one page</li> * <li>"wordPrevious" - moves the caret to the previous word</li> * <li>"wordNext" - moves the caret to the next word</li> * <li>"textStart" - moves the caret to the beginning of the document</li> * <li>"textEnd" - moves the caret to the end of the document</li> * </ul> * <li>Selection actions. These actions move the caret extending the selection.</li> * <ul> * <li>"selectLineUp" - moves the caret up by one line</li> * <li>"selectLineDown" - moves the caret down by one line</li> * <li>"selectLineStart" - moves the caret to beginning of the current line</li> * <li>"selectLineEnd" - moves the caret to end of the current line </li> * <li>"selectCharPrevious" - moves the caret to the previous character</li> * <li>"selectCharNext" - moves the caret to the next character</li> * <li>"selectPageUp" - moves the caret up by one page</li> * <li>"selectPageDown" - moves the caret down by one page</li> * <li>"selectWordPrevious" - moves the caret to the previous word</li> * <li>"selectWordNext" - moves the caret to the next word</li> * <li>"selectTextStart" - moves the caret to the beginning of the document</li> * <li>"selectTextEnd" - moves the caret to the end of the document</li> * <li>"selectAll" - selects the entire document</li> * </ul> * <li>Edit actions. These actions modify the editor text</li> * <ul> * <li>"deletePrevious" - deletes the character preceding the caret</li> * <li>"deleteNext" - deletes the charecter following the caret</li> * <li>"deleteWordPrevious" - deletes the word preceding the caret</li> * <li>"deleteWordNext" - deletes the word following the caret</li> * <li>"tab" - inserts a tab character at the caret</li> * <li>"enter" - inserts a line delimiter at the caret</li> * </ul> * <li>Clipboard actions.</li> * <ul> * <li>"copy" - copies the selected text to the clipboard</li> * <li>"cut" - copies the selected text to the clipboard and deletes the selection</li> * <li>"paste" - replaces the selected text with the clipboard contents</li> * </ul> * </ul> * </p> * * @param {Boolean} [defaultAction=false] whether or not the predefined actions are included. * @returns {String[]} an array of action names defined in the editor. * * @see #invokeAction * @see #setAction * @see #setKeyBinding * @see #getKeyBindings */ getActions: function (defaultAction) { var result = []; var actions = this._actions; for (var i = 0; i < actions.length; i++) { if (!defaultAction && actions[i].defaultHandler) { continue; } result.push(actions[i].name); } return result; }, /** * Returns the bottom index. * <p> * The bottom index is the line that is currently at the bottom of the editor. This * line may be partially visible depending on the vertical scroll of the editor. The parameter * <code>fullyVisible</code> determines whether to return only fully visible lines. * </p> * * @param {Boolean} [fullyVisible=false] if <code>true</code>, returns the index of the last fully visible line. This * parameter is ignored if the editor is not big enough to show one line. * @returns {Number} the index of the bottom line. * * @see #getTopIndex * @see #setTopIndex */ getBottomIndex: function(fullyVisible) { return this._getBottomIndex(fullyVisible); }, /** * Returns the bottom pixel. * <p> * The bottom pixel is the pixel position that is currently at * the bottom edge of the editor. This position is relative to the * beginning of the document. * </p> * * @returns {Number} the bottom pixel. * * @see #getTopPixel * @see #setTopPixel * @see #convert */ getBottomPixel: function() { return this._getScroll().y + this._getClientHeight(); }, /** * Returns the caret offset relative to the start of the document. * * @returns the caret offset relative to the start of the document. * * @see #setCaretOffset * @see #setSelection * @see #getSelection */ getCaretOffset: function () { var s = this._getSelection(); return s.getCaret(); }, /** * Returns the client area. * <p> * The client area is the portion in pixels of the document that is visible. The * client area position is relative to the beginning of the document. * </p> * * @returns the client area rectangle {x, y, width, height}. * * @see #getTopPixel * @see #getBottomPixel * @see #getHorizontalPixel * @see #convert */ getClientArea: function() { var scroll = this._getScroll(); return {x: scroll.x, y: scroll.y, width: this._getClientWidth(), height: this._getClientHeight()}; }, /** * Returns the horizontal pixel. * <p> * The horizontal pixel is the pixel position that is currently at * the left edge of the editor. This position is relative to the * beginning of the document. * </p> * * @returns {Number} the horizontal pixel. * * @see #setHorizontalPixel * @see #convert */ getHorizontalPixel: function() { return this._getScroll().x; }, /** * Returns all the key bindings associated to the given action name. * * @param {String} name the action name. * @returns {eclipse.KeyBinding[]} the array of key bindings associated to the given action name. * * @see #setKeyBinding * @see #setAction */ getKeyBindings: function (name) { var result = []; var keyBindings = this._keyBindings; for (var i = 0; i < keyBindings.length; i++) { if (keyBindings[i].name === name) { result.push(keyBindings[i].keyBinding); } } return result; }, /** * Returns the line height for a given line index. Returns the default line * height if the line index is not specified. * * @param {Number} [lineIndex] the line index. * @returns {Number} the height of the line in pixels. * * @see #getLinePixel */ getLineHeight: function(lineIndex) { return this._getLineHeight(); }, /** * Returns the top pixel position of a given line index relative to the beginning * of the document. * <p> * Clamps out of range indices. * </p> * * @param {Number} lineIndex the line index. * @returns {Number} the pixel position of the line. * * @see #setTopPixel * @see #convert */ getLinePixel: function(lineIndex) { lineIndex = Math.min(Math.max(0, lineIndex), this._model.getLineCount()); var lineHeight = this._getLineHeight(); return lineHeight * lineIndex; }, /** * Returns the {x, y} pixel location of the top-left corner of the character * bounding box at the specified offset in the document. The pixel location * is relative to the document. * <p> * Clamps out of range offsets. * </p> * * @param {Number} offset the character offset * @returns the {x, y} pixel location of the given offset. * * @see #getOffsetAtLocation * @see #convert */ getLocationAtOffset: function(offset) { var model = this._model; offset = Math.min(Math.max(0, offset), model.getCharCount()); var lineIndex = model.getLineAtOffset(offset); var scroll = this._getScroll(); var editorRect = this._editorDiv.getBoundingClientRect(); var editorPad = this._getEditorPadding(); var x = this._getOffsetToX(offset) + scroll.x - editorRect.left - editorPad.left; var y = this.getLinePixel(lineIndex); return {x: x, y: y}; }, /** * Returns the text model of the editor. * * @returns {eclipse.TextModel} the text model of the editor. */ getModel: function() { return this._model; }, /** * Returns the character offset nearest to the given pixel location. The * pixel location is relative to the document. * * @param x the x of the location * @param y the y of the location * @returns the character offset at the given location. * * @see #getLocationAtOffset */ getOffsetAtLocation: function(x, y) { var model = this._model; var scroll = this._getScroll(); var editorRect = this._editorDiv.getBoundingClientRect(); var editorPad = this._getEditorPadding(); var lineIndex = this._getYToLine(y - scroll.y); x += -scroll.x + editorRect.left + editorPad.left; var offset = this._getXToOffset(lineIndex, x); return offset; }, /** * Returns the editor selection. * <p> * The selection is defined by a start and end character offset relative to the * document. The character at end offset is not included in the selection. * </p> * * @returns {eclipse.Selection} the editor selection * * @see #setSelection */ getSelection: function () { var s = this._getSelection(); return {start: s.start, end: s.end}; }, /** * Returns the text for the given range. * <p> * The text does not include the character at the end offset. * </p> * * @param {Number} [start=0] the start offset of text range. * @param {Number} [end=char count] the end offset of text range. * * @see #setText */ getText: function(start, end) { var model = this._model; return model.getText(start, end); }, /** * Returns the top index. * <p> * The top index is the line that is currently at the top of the editor. This * line may be partially visible depending on the vertical scroll of the editor. The parameter * <code>fullyVisible</code> determines whether to return only fully visible lines. * </p> * * @param {Boolean} [fullyVisible=false] if <code>true</code>, returns the index of the first fully visible line. This * parameter is ignored if the editor is not big enough to show one line. * @returns {Number} the index of the top line. * * @see #getBottomIndex * @see #setTopIndex */ getTopIndex: function(fullyVisible) { return this._getTopIndex(fullyVisible); }, /** * Returns the top pixel. * <p> * The top pixel is the pixel position that is currently at * the top edge of the editor. This position is relative to the * beginning of the document. * </p> * * @returns {Number} the top pixel. * * @see #getBottomPixel * @see #setTopPixel * @see #convert */ getTopPixel: function() { return this._getScroll().y; }, /** * Executes the action handler associated with the given name. * <p> * The application defined action takes precedence over predefined actions unless * the <code>defaultAction</code> paramater is <code>true</code>. * </p> * <p> * If the application defined action returns <code>false</code>, the editor predefined * action is executed if present. * </p> * * @param {String} name the action name. * @param {Boolean} [defaultAction] whether to always execute the predefined action. * @returns {Boolean} <code>true</code> if the action was executed. * * @see #setAction * @see #getActions */ invokeAction: function (name, defaultAction) { var actions = this._actions; for (var i = 0; i < actions.length; i++) { var a = actions[i]; if (a.name && a.name === name) { if (!defaultAction && a.userHandler) { if (a.userHandler()) { return; } } if (a.defaultHandler) { return a.defaultHandler(); } return false; } } return false; }, /** * @class This is the event sent when the editor is destroyed. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onDestroy} * </p> * @name eclipse.DestroyEvent */ /** * This event is sent when the editor has been destroyed. * * @event * @param {eclipse.DestroyEvent} destroyEvent the event * * @see #destroy */ onDestroy: function(destroyEvent) { this._eventTable.sendEvent("Destroy", destroyEvent); }, /** * @class This object is used to define style information for the editor. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onLineStyle} * </p> * @name eclipse.Style * * @property {String} styleClass A CSS class name. * @property {Object} style An object with CSS properties. */ /** * @class This object is used to style range. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onLineStyle} * </p> * @name eclipse.StyleRange * * @property {Number} start The start character offset, relative to the document, where the style should be applied. * @property {Number} end The end character offset (exclusive), relative to the document, where the style should be applied. * @property {eclipse.Style} style The style for the range. */ /** * @class This is the event sent when the editor needs the style information for a line. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onLineStyle} * </p> * @name eclipse.LineStyleEvent * * @property {Number} lineIndex The line index. * @property {String} lineText The line text. * @property {Number} lineStart The character offset, relative to document, of the first character in the line. * @property {eclipse.Style} style The style for the entire line (output argument). * @property {eclipse.StyleRange[]} ranges An array of style ranges for the line (output argument). */ /** * This event is sent when the editor needs the style information for a line. * * @event * @param {eclipse.LineStyleEvent} lineStyleEvent the event */ onLineStyle: function(lineStyleEvent) { this._eventTable.sendEvent("LineStyle", lineStyleEvent); }, /** * @class This is the event sent when the text in the model has changed. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onModelChanged}<br> * {@link eclipse.TextModel#onChanged} * </p> * @name eclipse.ModelChangedEvent * * @property {Number} start The character offset in the model where the change has occurred. * @property {Number} removedCharCount The number of characters removed from the model. * @property {Number} addedCharCount The number of characters added to the model. * @property {Number} removedLineCount The number of lines removed from the model. * @property {Number} addedLineCount The number of lines added to the model. */ /** * This event is sent when the text in the model has changed. * * @event * @param {eclipse.ModelChangingEvent} modelChangingEvent the event */ onModelChanged: function(modelChangedEvent) { this._eventTable.sendEvent("ModelChanged", modelChangedEvent); }, /** * @class This is the event sent when the text in the model is about to change. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onModelChanging}<br> * {@link eclipse.TextModel#onChanging} * </p> * @name eclipse.ModelChangingEvent * * @property {String} text The text that is about to be inserted in the model. * @property {Number} start The character offset in the model where the change will occur. * @property {Number} removedCharCount The number of characters being removed from the model. * @property {Number} addedCharCount The number of characters being added to the model. * @property {Number} removedLineCount The number of lines being removed from the model. * @property {Number} addedLineCount The number of lines being added to the model. */ /** * This event is sent when the text in the model is about to change. * * @event * @param {eclipse.ModelChangingEvent} modelChangingEvent the event */ onModelChanging: function(modelChangingEvent) { this._eventTable.sendEvent("ModelChanging", modelChangingEvent); }, /** * @class This is the event sent when the text is modified by the editor. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onModify} * </p> * @name eclipse.ModifyEvent */ /** * This event is sent when the editor has changed text in the model. * <p> * If the text is changed directly through the model API, this event * is not sent. * </p> * * @event * @param {eclipse.ModifyEvent} modifyEvent the event */ onModify: function(modifyEvent) { this._eventTable.sendEvent("Modify", modifyEvent); }, /** * @class This is the event sent when the selection changes in the editor. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onSelection} * </p> * @name eclipse.SelectionEvent * * @property {eclipse.Selection} oldValue The old selection. * @property {eclipse.Selection} newValue The new selection. */ /** * This event is sent when the editor selection has changed. * * @event * @param {eclipse.SelectionEvent} selectionEvent the event */ onSelection: function(selectionEvent) { this._eventTable.sendEvent("Selection", selectionEvent); }, /** * @class This is the event sent when the editor scrolls. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onScroll} * </p> * @name eclipse.ScrollEvent * * @property oldValue The old scroll {x,y}. * @property newValue The new scroll {x,y}. */ /** * This event is sent when the editor scrolls vertically or horizontally. * * @event * @param {eclipse.ScrollEvent} scrollEvent the event */ onScroll: function(scrollEvent) { this._eventTable.sendEvent("Scroll", scrollEvent); }, /** * @class This is the event sent when the text is about to be modified by the editor. * <p> * <b>See:</b><br> * {@link eclipse.Editor}<br> * {@link eclipse.Editor#event:onVerify} * </p> * @name eclipse.VerifyEvent * * @property {String} text The text being inserted. * @property {Number} start The start offset of the text range to be replaced. * @property {Number} end The end offset (exclusive) of the text range to be replaced. */ /** * This event is sent when the editor is about to change text in the model. * <p> * If the text is changed directly through the model API, this event * is not sent. * </p> * <p> * Listeners are allowed to change these parameters. Setting text to null * or undefined stops the change. * </p> * * @event * @param {eclipse.VerifyEvent} verifyEvent the event */ onVerify: function(verifyEvent) { this._eventTable.sendEvent("Verify", verifyEvent); }, /** * Redraws the text in the given line range. * <p> * The line at the end index is not redrawn. * </p> * * @param {Number} [startLine=0] the start line * @param {Number} [endLine=line count] the end line */ redrawLines: function(startLine, endLine, ruler) { if (startLine === undefined) { startLine = 0; } if (endLine === undefined) { endLine = this._model.getLineCount(); } if (startLine === endLine) { return; } var div = this._clientDiv; if (ruler) { var location = ruler.getLocation();//"left" or "right" var divRuler = location === "left" ? this._leftDiv : this._rightDiv; var cells = divRuler.firstChild.rows[0].cells; for (var i = 0; i < cells.length; i++) { if (cells[i].firstChild._ruler === ruler) { div = cells[i].firstChild; break; } } } if (ruler) { div.rulerChanged = true; } if (!ruler || ruler.getOverview() === "page") { var child = div.firstChild; while (child) { var lineIndex = child.lineIndex; if (startLine <= lineIndex && lineIndex < endLine) { child.lineChanged = true; } child = child.nextSibling; } } if (!ruler) { if (startLine <= this._maxLineIndex && this._maxLineIndex < endLine) { this._maxLineIndex = -1; this._maxLineWidth = 0; } } this._queueUpdatePage(); }, /** * Redraws the text in the given range. * <p> * The character at the end offset is not redrawn. * </p> * * @param {Number} [start=0] the start offset of text range * @param {Number} [end=char count] the end offset of text range */ redrawRange: function(start, end) { var model = this._model; if (start === undefined) { start = 0; } if (end === undefined) { end = model.getCharCount(); } if (start === end) { return; } var startLine = model.getLineAtOffset(start); var endLine = model.getLineAtOffset(Math.max(0, end - 1)) + 1; this.redrawLines(startLine, endLine); }, /** * Removes an event listener from the editor. * <p> * All the parameters must be the same ones used to add the listener. * </p> * * @param {String} type the event type. * @param {Object} context the context of the function. * @param {Function} func the function that will be executed when the event happens. * @param {Object} [data] optional data passed to the function. * * @see #addEventListener */ removeEventListener: function(type, context, func, data) { this._eventTable.removeEventListener(type, context, func, data); }, /** * Removes a ruler from the editor. * * @param {eclipse.Ruler} ruler the ruler. */ removeRuler: function (ruler) { ruler.setEditor(null); var side = ruler.getLocation(); var rulerParent = side === "left" ? this._leftDiv : this._rightDiv; var row = rulerParent.firstChild.rows[0]; var cells = row.cells; for (var index = 0; index < cells.length; index++) { var cell = cells[index]; if (cell.firstChild._ruler === ruler) { break; } } if (index === cells.length) { return; } row.cells[index]._ruler = undefined; row.deleteCell(index); this._updatePage(); }, /** * Associates an application defined handler to an action name. * <p> * If the action name is a predefined action, the given handler executes before * the default action handler. If the given handler returns <code>true</code>, the * default action handler is not called. * </p> * * @param {String} name the action name. * @param {Function} handler the action handler. * * @see #getActions * @see #invokeAction */ setAction: function(name, handler) { if (!name) { return; } var actions = this._actions; for (var i = 0; i < actions.length; i++) { var a = actions[i]; if (a.name === name) { a.userHandler = handler; return; } } actions.push({name: name, userHandler: handler}); }, /** * Associates a key binding with the given action name. Any previous * association with the specified key binding is overwriten. If the * action name is <code>null</code>, the association is removed. * * @param {eclipse.KeyBinding} keyBinding the key binding * @param {String} name the action */ setKeyBinding: function(keyBinding, name) { var keyBindings = this._keyBindings; for (var i = 0; i < keyBindings.length; i++) { var kb = keyBindings[i]; if (kb.keyBinding.equals(keyBinding)) { if (name) { kb.name = name; } else { if (kb.predefined) { kb.name = null; } else { var oldName = kb.name; keyBindings.splice(i, 1); var index = 0; while (index < keyBindings.length && oldName !== keyBindings[index].name) { index++; } if (index === keyBindings.length) { /* <p> * Removing all the key bindings associated to an user action will cause * the user action to be removed. Editor predefined actions are never * removed (so they can be reinstalled in the future). * </p> */ var actions = this._actions; for (var j = 0; j < actions.length; j++) { if (actions[j].name === oldName) { if (!actions[j].defaultHandler) { actions.splice(j, 1); } } } } } } return; } } if (name) { keyBindings.push({keyBinding: keyBinding, name: name}); } }, /** * Sets the caret offset relative to the start of the document. * * @param {Number} caret the caret offset relative to the start of the document. * @param {Boolean} [show=true] if <code>true</coce>, the editor will scroll if needed to show the caret location. * * @see #getCaretOffset * @see #setSelection * @see #getSelection */ setCaretOffset: function(offset, show) { var charCount = this._model.getCharCount(); offset = Math.max(0, Math.min (offset, charCount)); var selection = new Selection(offset, offset, false); this._setSelection (selection, show === undefined || show); }, /** * Sets the horizontal pixel. * <p> * The horizontal pixel is the pixel position that is currently at * the left edge of the editor. This position is relative to the * beginning of the document. * </p> * * @param {Number} pixel the horizontal pixel. * * @see #getHorizontalPixel * @see #convert */ setHorizontalPixel: function(pixel) { pixel = Math.max(0, pixel); this._scrollView(pixel - this._getScroll().x, 0); }, /** * Sets the text model of the editor. * * @param {eclipse.TextModel} model the text model of the editor. */ setModel: function(model) { if (!model) { return; } this._model.removeListener(this._modelListener); var oldLineCount = this._model.getLineCount(); var oldCharCount = this._model.getCharCount(); var newLineCount = model.getLineCount(); var newCharCount = model.getCharCount(); var newText = model.getText(); var e = { text: newText, start: 0, removedCharCount: oldCharCount, addedCharCount: newCharCount, removedLineCount: oldLineCount, addedLineCount: newLineCount }; this.onModelChanging(e); this.redrawRange(); this._model = model; e = { start: 0, removedCharCount: oldCharCount, addedCharCount: newCharCount, removedLineCount: oldLineCount, addedLineCount: newLineCount }; this.onModelChanged(e); this._model.addListener(this._modelListener); this.redrawRange(); }, /** * Sets the editor selection. * <p> * The selection is defined by a start and end character offset relative to the * document. The character at end offset is not included in the selection. * </p> * <p> * The caret is always placed at the end offset. The start offset can be * greater than the end offset to place the caret at the beginning of the * selection. * </p> * <p> * Clamps out of range offsets. * </p> * * @param {Number} start the start offset of the selection * @param {Number} end the end offset of the selection * @param {Boolean} [show=true] if <code>true</coce>, the editor will scroll if needed to show the caret location. * * @see #getSelection */ setSelection: function (start, end, show) { var caret = start > end; if (caret) { var tmp = start; start = end; end = tmp; } var charCount = this._model.getCharCount(); start = Math.max(0, Math.min (start, charCount)); end = Math.max(0, Math.min (end, charCount)); var selection = new Selection(start, end, caret); this._setSelection(selection, show === undefined || show); }, /** * Replaces the text in the given range with the given text. * <p> * The character at the end offset is not replaced. * </p> * <p> * When both <code>start</code> and <code>end</code> parameters * are not specified, the editor places the caret at the beginning * of the document and scrolls to make it visible. * </p> * * @param {String} text the new text. * @param {Number} [start=0] the start offset of text range. * @param {Number} [end=char count] the end offset of text range. * * @see #getText */ setText: function (text, start, end) { var reset = start === undefined && end === undefined; if (start === undefined) { start = 0; } if (end === undefined) { end = this._model.getCharCount(); } this._modifyContent({text: text, start: start, end: end, _code: true}, !reset); if (reset) { this._columnX = -1; this._setSelection(new Selection (0, 0, false), true); this._showCaret(); /* * Bug in Firefox 4. For some reason, the caret does not show after the * editor is refreshed. The fix is to toggle the contentEditable state and * force the clientDiv to loose and receive focus. */ if (isFirefox >= 4) { var clientDiv = this._clientDiv; clientDiv.contentEditable = false; clientDiv.contentEditable = true; clientDiv.blur(); clientDiv.focus(); } } }, /** * Sets the top index. * <p> * The top index is the line that is currently at the top of the editor. This * line may be partially visible depending on the vertical scroll of the editor. * </p> * * @param {Number} topIndex the index of the top line. * * @see #getBottomIndex * @see #getTopIndex */ setTopIndex: function(topIndex) { var model = this._model; if (model.getCharCount() === 0) { return; } var lineCount = model.getLineCount(); var lineHeight = this._getLineHeight(); var pageSize = Math.max(1, Math.min(lineCount, Math.floor(this._getClientHeight () / lineHeight))); if (topIndex < 0) { topIndex = 0; } else if (topIndex > lineCount - pageSize) { topIndex = lineCount - pageSize; } var pixel = topIndex * lineHeight - this._getScroll().y; this._scrollView(0, pixel); }, /** * Sets the top pixel. * <p> * The top pixel is the pixel position that is currently at * the top edge of the editor. This position is relative to the * beginning of the document. * </p> * * @param {Number} pixel the top pixel. * * @see #getBottomPixel * @see #getTopPixel * @see #convert */ setTopPixel: function(pixel) { var lineHeight = this._getLineHeight(); var clientHeight = this._getClientHeight(); var lineCount = this._model.getLineCount(); pixel = Math.min(Math.max(0, pixel), lineHeight * lineCount - clientHeight); this._scrollView(0, pixel - this._getScroll().y); }, /** * Scrolls the selection into view if needed. * * @see #getSelection * @see #setSelection */ showSelection: function() { return this._showCaret(); }, /**************************************** Event handlers *********************************/ _handleBodyMouseDown: function (e) { if (!e) { e = window.event; } /* * Prevent clicks outside of the editor from taking focus * away the editor. Note that in Firefox and Opera clicking on the * scrollbar also take focus from the editor. Other browsers * do not have this problem and stopping the click over the * scrollbar for them causes mouse capture problems. */ var topNode = isOpera ? this._clientDiv : this._overlayDiv || this._editorDiv; var temp = e.target ? e.target : e.srcElement; while (temp) { if (topNode === temp) { return; } temp = temp.parentNode; } if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation){ e.stopPropagation(); } if (!isW3CEvents) { /* In IE 8 is not possible to prevent the default handler from running * during mouse down event using usual API. The workaround is to use * setCapture/releaseCapture. */ topNode.setCapture(); setTimeout(function() { topNode.releaseCapture(); }, 0); } }, _handleBlur: function (e) { if (!e) { e = window.event; } this._hasFocus = false; if (isIE) { /* * Bug in IE. For some reason when text is deselected the overflow * selection at the end of some lines does not get redrawn. The * fix is to create a DOM element in the body to force a redraw. */ if (!this._getSelection().isEmpty()) { var document = this._frameDocument; var child = document.createElement("DIV"); var body = document.body; body.appendChild(child); body.removeChild(child); } } }, _handleContextMenu: function (e) { if (!e) { e = window.event; } if (e.preventDefault) { e.preventDefault(); } return false; }, _handleCopy: function (e) { if (this._ignoreCopy) { return; } if (!e) { e = window.event; } if (this._doCopy(e)) { if (e.preventDefault) { e.preventDefault(); } return false; } }, _handleCut: function (e) { if (!e) { e = window.event; } if (this._doCut(e)) { if (e.preventDefault) { e.preventDefault(); } return false; } }, _handleDataModified: function(e) { this._startIME(); }, _handleDblclick: function (e) { if (!e) { e = window.event; } var time = e.timeStamp ? e.timeStamp : new Date().getTime(); this._lastMouseTime = time; if (this._clickCount !== 2) { this._clickCount = 2; this._handleMouse(e); } }, _handleDragStart: function (e) { if (!e) { e = window.event; } if (e.preventDefault) { e.preventDefault(); } return false; }, _handleDocFocus: function (e) { if (!e) { e = window.event; } this._clientDiv.focus(); }, _handleFocus: function (e) { if (!e) { e = window.event; } this._hasFocus = true; if (isIE) { this._updateDOMSelection(); } }, _handleKeyDown: function (e) { if (!e) { e = window.event; } if (e.keyCode === 229) { if (this.readonly) { if (e.preventDefault) { e.preventDefault(); } return false; } this._startIME(); } else { this._commitIME(); } /* * Feature in Firefox. When a key is held down the browser sends * right number of keypress events but only one keydown. This is * unexpected and causes the editor to only execute an action * just one time. The fix is to ignore the keydown event and * execute the actions from the keypress handler. * Note: This only happens on the Mac (Firefox). * * Feature in Opera. Opera sends keypress events even for non-printable * keys. The fix is to handle actions in keypress instead of keydown. */ if ((isMac && isFirefox) || isOpera) { this._keyDownEvent = e; return true; } if (this._doAction(e)) { if (e.preventDefault) { e.preventDefault(); } else { e.cancelBubble = true; e.returnValue = false; e.keyCode = 0; } return false; } }, _handleKeyPress: function (e) { if (!e) { e = window.event; } if ((isMac && isFirefox) || isOpera) { if (this._doAction(this._keyDownEvent)) { if (e.preventDefault) { e.preventDefault(); } return false; } } var ctrlKey = isMac ? e.metaKey : e.ctrlKey; if (e.charCode !== undefined) { if (ctrlKey) { switch (e.charCode) { /* * In Firefox and Safari if ctrl+v, ctrl+c ctrl+x is canceled * the clipboard events are not sent. The fix to allow * the browser to handles these key events. */ case 99://c case 118://v case 120://x return true; } } } var ignore = false; if (isMac) { if (e.ctrlKey || e.metaKey) { ignore = true; } } else { if (isFirefox) { //Firefox clears the state mask when ALT GR generates input if (e.ctrlKey || e.altKey) { ignore = true; } } else { //IE and Chrome only send ALT GR when input is generated if (e.ctrlKey ^ e.altKey) { ignore = true; } } } if (!ignore) { var key = isOpera ? e.which : (e.charCode !== undefined ? e.charCode : e.keyCode); if (key !== 0) { this._doContent(String.fromCharCode (key)); if (e.preventDefault) { e.preventDefault(); } return false; } } }, _handleKeyUp: function (e) { if (!e) { e = window.event; } // don't commit for space (it happens during JP composition) if (e.keyCode === 13) { this._commitIME(); } }, _handleMouse: function (e) { var target = this._frameWindow; if (isIE) { target = this._clientDiv; } if (this._overlayDiv) { var self = this; setTimeout(function () { self.focus(); }, 0); } if (this._clickCount === 1) { this._setGrab(target); this._setSelectionTo(e.clientX, e.clientY, e.shiftKey); } else { /* * Feature in IE8 and older, the sequence of events in the IE8 event model * for a doule-click is: * * down * up * up * dblclick * * Given that the mouse down/up events are not balanced, it is not possible to * grab on mouse down and ungrab on mouse up. The fix is to grab on the first * mouse down and ungrab on mouse move when the button 1 is not set. */ if (isW3CEvents) { this._setGrab(target); } this._doubleClickSelection = null; this._setSelectionTo(e.clientX, e.clientY, e.shiftKey); this._doubleClickSelection = this._getSelection(); } }, _handleMouseDown: function (e) { if (!e) { e = window.event; } var left = e.which ? e.button === 0 : e.button === 1; this._commitIME(); if (left) { this._isMouseDown = true; var deltaX = Math.abs(this._lastMouseX - e.clientX); var deltaY = Math.abs(this._lastMouseY - e.clientY); var time = e.timeStamp ? e.timeStamp : new Date().getTime(); if ((time - this._lastMouseTime) <= this._clickTime && deltaX <= this._clickDist && deltaY <= this._clickDist) { this._clickCount++; } else { this._clickCount = 1; } this._lastMouseX = e.clientX; this._lastMouseY = e.clientY; this._lastMouseTime = time; this._handleMouse(e); if (isOpera) { if (!this._hasFocus) { this.focus(); } e.preventDefault(); } } }, _handleMouseMove: function (e) { if (!e) { e = window.event; } /* * Feature in IE8 and older, the sequence of events in the IE8 event model * for a doule-click is: * * down * up * up * dblclick * * Given that the mouse down/up events are not balanced, it is not possible to * grab on mouse down and ungrab on mouse up. The fix is to grab on the first * mouse down and ungrab on mouse move when the button 1 is not set. * * In order to detect double-click and drag gestures, it is necessary to send * a mouse down event from mouse move when the button is still down and isMouseDown * flag is not set. */ if (!isW3CEvents) { if (e.button === 0) { this._setGrab(null); return true; } if (!this._isMouseDown && e.button === 1 && (this._clickCount & 1) !== 0) { this._clickCount = 2; return this._handleMouse(e, this._clickCount); } } var x = e.clientX; var y = e.clientY; var editorPad = this._getEditorPadding(); var editorRect = this._editorDiv.getBoundingClientRect(); var width = this._getClientWidth (), height = this._getClientHeight(); var leftEdge = editorRect.left + editorPad.left; var topEdge = editorRect.top + editorPad.top; var rightEdge = editorRect.left + editorPad.left + width; var bottomEdge = editorRect.top + editorPad.top + height; var model = this._model; var caretLine = model.getLineAtOffset(this._getSelection().getCaret()); if (y < topEdge && caretLine !== 0) { this._doAutoScroll("up", x, y - topEdge); } else if (y > bottomEdge && caretLine !== model.getLineCount() - 1) { this._doAutoScroll("down", x, y - bottomEdge); } else if (x < leftEdge) { this._doAutoScroll("left", x - leftEdge, y); } else if (x > rightEdge) { this._doAutoScroll("right", x - rightEdge, y); } else { this._endAutoScroll(); this._setSelectionTo(x, y, true); // Feature in IE, IE does redraw the selection background right // away after the selection changes because of mouse move events. // The fix is to call getBoundingClientRect() on the // body element to force the selection to be redraw. Some how // calling this method forces a redraw. if (isIE) { var body = this._frameDocument.body; body.getBoundingClientRect(); } } }, _handleMouseUp: function (e) { if (!e) { e = window.event; } this._endAutoScroll(); var left = e.which ? e.button === 0 : e.button === 1; if (left) { this._isMouseDown=false; /* * Feature in IE8 and older, the sequence of events in the IE8 event model * for a doule-click is: * * down * up * up * dblclick * * Given that the mouse down/up events are not balanced, it is not possible to * grab on mouse down and ungrab on mouse up. The fix is to grab on the first * mouse down and ungrab on mouse move when the button 1 is not set. */ if (isW3CEvents) { this._setGrab(null); } } }, _handleMouseWheel: function (e) { if (!e) { e = window.event; } var lineHeight = this._getLineHeight(); var pixelX = 0, pixelY = 0; // Note: On the Mac the correct behaviour is to scroll by pixel. if (isFirefox) { var pixel; if (isMac) { pixel = e.detail * 3; } else { var limit = 256; pixel = Math.max(-limit, Math.min(limit, e.detail)) * lineHeight; } if (e.axis === e.HORIZONTAL_AXIS) { pixelX = pixel; } else { pixelY = pixel; } } else { //Webkit if (isMac) { /* * In Safari, the wheel delta is a multiple of 120. In order to * convert delta to pixel values, it is necessary to divide delta * by 40. * * In Chrome, the wheel delta depends on the type of the mouse. In * general, it is the pixel value for Mac mice and track pads, but * it is a multiple of 120 for other mice. There is no presise * way to determine if it is pixel value or a multiple of 120. * * Note that the current approach does not calculate the correct * pixel value for Mac mice when the delta is a multiple of 120. */ var denominatorX = 40, denominatorY = 40; if (isChrome) { if (e.wheelDeltaX % 120 !== 0) { denominatorX = 1; } if (e.wheelDeltaY % 120 !== 0) { denominatorY = 1; } } pixelX = -e.wheelDeltaX / denominatorX; if (-1 < pixelX && pixelX < 0) { pixelX = -1; } if (0 < pixelX && pixelX < 1) { pixelX = 1; } pixelY = -e.wheelDeltaY / denominatorY; if (-1 < pixelY && pixelY < 0) { pixelY = -1; } if (0 < pixelY && pixelY < 1) { pixelY = 1; } } else { pixelX = -e.wheelDeltaX; var linesToScroll = 8; pixelY = (-e.wheelDeltaY / 120 * linesToScroll) * lineHeight; } } /* * Feature in Safari. If the event target is removed from the DOM * safari stops smooth scrolling. The fix is keep the element target * in the DOM and remove it on a later time. * * Note: Using a timer is not a solution, because the timeout needs to * be at least as long as the gesture (which is too long). */ if (isSafari) { var lineDiv = e.target; while (lineDiv.lineIndex === undefined) { lineDiv = lineDiv.parentNode; } this._mouseWheelLine = lineDiv; } var oldScroll = this._getScroll(); this._scrollView(pixelX, pixelY); var newScroll = this._getScroll(); if (isSafari) { this._mouseWheelLine = null; } if (oldScroll.x !== newScroll.x || oldScroll.y !== newScroll.y) { if (e.preventDefault) { e.preventDefault(); } return false; } }, _handlePaste: function (e) { if (this._ignorePaste) { return; } if (!e) { e = window.event; } if (this._doPaste(e)) { if (isIE) { /* * Bug in IE, */ var self = this; setTimeout(function() {self._updateDOMSelection();}, 0); } if (e.preventDefault) { e.preventDefault(); } return false; } }, _handleResize: function (e) { if (!e) { e = window.event; } var document = this._frameDocument; var element = isIE ? document.documentElement : document.body; var newWidth = element.clientWidth; var newHeight = element.clientHeight; if (this._editorWidth !== newWidth || this._editorHeight !== newHeight) { this._editorWidth = newWidth; this._editorHeight = newHeight; // this._queueUpdatePage(); this._updatePage(); } }, _handleRulerEvent: function (e) { if (!e) { e = window.event; } var target = e.target ? e.target : e.srcElement; var lineIndex = target.lineIndex; var element = target; while (element && !element._ruler) { if (lineIndex === undefined && element.lineIndex !== undefined) { lineIndex = element.lineIndex; } element = element.parentNode; } var ruler = element ? element._ruler : null; if (ruler) { switch (e.type) { case "click": if (ruler.onClick) { ruler.onClick(lineIndex, e); } break; case "dblclick": if (ruler.onDblClick) { ruler.onDblClick(lineIndex, e); } break; } } }, _handleScroll: function () { this._doScroll(this._getScroll()); }, _handleSelectStart: function (e) { if (!e) { e = window.event; } if (this._ignoreSelect) { if (e && e.preventDefault) { e.preventDefault(); } return false; } }, /************************************ Actions ******************************************/ _doAction: function (e) { var keyBindings = this._keyBindings; for (var i = 0; i < keyBindings.length; i++) { var kb = keyBindings[i]; if (kb.keyBinding.match(e)) { if (kb.name) { var actions = this._actions; for (var j = 0; j < actions.length; j++) { var a = actions[j]; if (a.name === kb.name) { if (a.userHandler) { if (!a.userHandler()) { if (a.defaultHandler) { a.defaultHandler(); } } } else if (a.defaultHandler) { a.defaultHandler(); } break; } } } return true; } } return false; }, _doBackspace: function (args) { var selection = this._getSelection(); if (selection.isEmpty()) { var model = this._model; var caret = selection.getCaret(); var lineIndex = model.getLineAtOffset(caret); if (caret === model.getLineStart(lineIndex)) { if (lineIndex > 0) { selection.extend(model.getLineEnd(lineIndex - 1)); } } else { selection.extend(this._getOffset(caret, args.word, -1)); } } this._modifyContent({text: "", start: selection.start, end: selection.end}, true); return true; }, _doContent: function (text) { var selection = this._getSelection(); this._modifyContent({text: text, start: selection.start, end: selection.end, _ignoreDOMSelection: true}, true); }, _doCopy: function (e) { var selection = this._getSelection(); if (!selection.isEmpty()) { var text = this._model.getText(selection.start, selection.end); return this._setClipboardText(text, e); } return true; }, _doCursorNext: function (args) { if (!args.select) { if (this._clearSelection("next")) { return true; } } var model = this._model; var selection = this._getSelection(); var caret = selection.getCaret(); var lineIndex = model.getLineAtOffset(caret); if (caret === model.getLineEnd(lineIndex)) { if (lineIndex + 1 < model.getLineCount()) { selection.extend(model.getLineStart(lineIndex + 1)); } } else { selection.extend(this._getOffset(caret, args.word, 1)); } if (!args.select) { selection.collapse(); } this._setSelection(selection, true); return true; }, _doCursorPrevious: function (args) { if (!args.select) { if (this._clearSelection("previous")) { return true; } } var model = this._model; var selection = this._getSelection(); var caret = selection.getCaret(); var lineIndex = model.getLineAtOffset(caret); if (caret === model.getLineStart(lineIndex)) { if (lineIndex > 0) { selection.extend(model.getLineEnd(lineIndex - 1)); } } else { selection.extend(this._getOffset(caret, args.word, -1)); } if (!args.select) { selection.collapse(); } this._setSelection(selection, true); return true; }, _doCut: function (e) { var selection = this._getSelection(); if (!selection.isEmpty()) { var text = this._model.getText(selection.start, selection.end); this._doContent(""); return this._setClipboardText(text, e); } return true; }, _doDelete: function (args) { var selection = this._getSelection(); if (selection.isEmpty()) { var model = this._model; var caret = selection.getCaret(); var lineIndex = model.getLineAtOffset(caret); if (caret === model.getLineEnd (lineIndex)) { if (lineIndex + 1 < model.getLineCount()) { selection.extend(model.getLineStart(lineIndex + 1)); } } else { selection.extend(this._getOffset(caret, args.word, 1)); } } this._modifyContent({text: "", start: selection.start, end: selection.end}, true); return true; }, _doEnd: function (args) { var selection = this._getSelection(); var model = this._model; if (args.ctrl) { selection.extend(model.getCharCount()); } else { var lineIndex = model.getLineAtOffset(selection.getCaret()); selection.extend(model.getLineEnd(lineIndex)); } if (!args.select) { selection.collapse(); } this._setSelection(selection, true); return true; }, _doEnter: function (args) { var model = this._model; this._doContent(model.getLineDelimiter()); return true; }, _doHome: function (args) { var selection = this._getSelection(); var model = this._model; if (args.ctrl) { selection.extend(0); } else { var lineIndex = model.getLineAtOffset(selection.getCaret()); selection.extend(model.getLineStart(lineIndex)); } if (!args.select) { selection.collapse(); } this._setSelection(selection, true); return true; }, _doLineDown: function (args) { var model = this._model; var selection = this._getSelection(); var caret = selection.getCaret(); var lineIndex = model.getLineAtOffset(caret); if (lineIndex + 1 < model.getLineCount()) { var x = this._columnX; if (x === -1 || args.select) { x = this._getOffsetToX(caret); } selection.extend(this._getXToOffset(lineIndex + 1, x)); if (!args.select) { selection.collapse(); } this._setSelection(selection, true, true); this._columnX = x;//fix x by scrolling } return true; }, _doLineUp: function (args) { var model = this._model; var selection = this._getSelection(); var caret = selection.getCaret(); var lineIndex = model.getLineAtOffset(caret); if (lineIndex > 0) { var x = this._columnX; if (x === -1 || args.select) { x = this._getOffsetToX(caret); } selection.extend(this._getXToOffset(lineIndex - 1, x)); if (!args.select) { selection.collapse(); } this._setSelection(selection, true, true); this._columnX = x;//fix x by scrolling } return true; }, _doPageDown: function (args) { var model = this._model; var selection = this._getSelection(); var caret = selection.getCaret(); var caretLine = model.getLineAtOffset(caret); var lineCount = model.getLineCount(); if (caretLine < lineCount - 1) { var clientHeight = this._getClientHeight(); var lineHeight = this._getLineHeight(); var lines = Math.floor(clientHeight / lineHeight); var scrollLines = Math.min(lineCount - caretLine - 1, lines); scrollLines = Math.max(1, scrollLines); var x = this._columnX; if (x === -1 || args.select) { x = this._getOffsetToX(caret); } selection.extend(this._getXToOffset(caretLine + scrollLines, x)); if (!args.select) { selection.collapse(); } this._setSelection(selection, false, false); var verticalMaximum = lineCount * lineHeight; var verticalScrollOffset = this._getScroll().y; var scrollOffset = verticalScrollOffset + scrollLines * lineHeight; if (scrollOffset + clientHeight > verticalMaximum) { scrollOffset = verticalMaximum - clientHeight; } if (scrollOffset > verticalScrollOffset) { this._scrollView(0, scrollOffset - verticalScrollOffset); } else { this._updateDOMSelection(); } this._columnX = x;//fix x by scrolling } return true; }, _doPageUp: function (args) { var model = this._model; var selection = this._getSelection(); var caret = selection.getCaret(); var caretLine = model.getLineAtOffset(caret); if (caretLine > 0) { var clientHeight = this._getClientHeight(); var lineHeight = this._getLineHeight(); var lines = Math.floor(clientHeight / lineHeight); var scrollLines = Math.max(1, Math.min(caretLine, lines)); var x = this._columnX; if (x === -1 || args.select) { x = this._getOffsetToX(caret); } selection.extend(this._getXToOffset(caretLine - scrollLines, x)); if (!args.select) { selection.collapse(); } this._setSelection(selection, false, false); var verticalScrollOffset = this._getScroll().y; var scrollOffset = Math.max(0, verticalScrollOffset - scrollLines * lineHeight); if (scrollOffset < verticalScrollOffset) { this._scrollView(0, scrollOffset - verticalScrollOffset); } else { this._updateDOMSelection(); } this._columnX = x;//fix x by scrolling } return true; }, _doPaste: function(e) { var text = this._getClipboardText(e); if (text) { this._doContent(text); } return text !== null; }, _doScroll: function (scroll) { var oldX = this._hScroll; var oldY = this._vScroll; if (oldX !== scroll.x || (oldY !== scroll.y)) { this._hScroll = scroll.x; this._vScroll = scroll.y; this._commitIME(); this._updatePage(); var e = { oldValue: {x: oldX, y: oldY}, newValue: scroll }; this.onScroll(e); } }, _doSelectAll: function (args) { var model = this._model; var selection = this._getSelection(); selection.setCaret(0); selection.extend(model.getCharCount()); this._setSelection(selection, false); return true; }, _doTab: function (args) { this._doContent("\t"); return true; }, /************************************ Internals ******************************************/ _applyStyle: function(style, node) { if (!style) { return; } if (style.styleClass) { node.className = style.styleClass; } var properties = style.style; if (properties) { for (var s in properties) { if (properties.hasOwnProperty(s)) { node.style[s] = properties[s]; } } } }, _autoScroll: function () { var selection = this._getSelection(); var line; var x = this._autoScrollX; if (this._autoScrollDir === "up" || this._autoScrollDir === "down") { var scroll = this._autoScrollY / this._getLineHeight(); scroll = scroll < 0 ? Math.floor(scroll) : Math.ceil(scroll); line = this._model.getLineAtOffset(selection.getCaret()); line = Math.max(0, Math.min(this._model.getLineCount() - 1, line + scroll)); } else if (this._autoScrollDir === "left" || this._autoScrollDir === "right") { line = this._getYToLine(this._autoScrollY); x += this._getOffsetToX(selection.getCaret()); } selection.extend(this._getXToOffset(line, x)); this._setSelection(selection, true); }, _autoScrollTimer: function () { this._autoScroll(); var self = this; this._autoScrollTimerID = setTimeout(function () {self._autoScrollTimer();}, this._AUTO_SCROLL_RATE); }, _calculateLineHeight: function() { var document = this._frameDocument; var parent = this._clientDiv; var span1 = document.createElement("SPAN"); span1.appendChild(document.createTextNode("W")); parent.appendChild(span1); var br = document.createElement("BR"); parent.appendChild(br); var span2 = document.createElement("SPAN"); span2.appendChild(document.createTextNode("W")); parent.appendChild(span2); var rect1 = span1.getBoundingClientRect(); var rect2 = span2.getBoundingClientRect(); var lineHeight = rect2.top - rect1.top; parent.removeChild(span1); parent.removeChild(br); parent.removeChild(span2); return lineHeight; }, _clearSelection: function (direction) { var selection = this._getSelection(); if (selection.isEmpty()) { return false; } if (direction === "next") { selection.start = selection.end; } else { selection.end = selection.start; } this._setSelection(selection, true); return true; }, _commitIME: function () { if (this._imeOffset === -1) { return; } // make the state of the IME match the state the editor expects it be in // when the editor commits the text and IME also need to be committed // this can be accomplished by changing the focus around this._scrollDiv.focus(); this._clientDiv.focus(); var model = this._model; var lineIndex = model.getLineAtOffset(this._imeOffset); var lineStart = model.getLineStart(lineIndex); var newText = this._getDOMText(lineIndex); var oldText = model.getLine(lineIndex); var start = this._imeOffset - lineStart; var end = start + newText.length - oldText.length; if (start !== end) { var insertText = newText.substring(start, end); this._doContent(insertText); } this._imeOffset = -1; }, _createActions: function () { var KeyBinding = eclipse.KeyBinding; //no duplicate keybindings var bindings = this._keyBindings = []; // Cursor Navigation bindings.push({name: "lineUp", keyBinding: new KeyBinding(38), predefined: true}); bindings.push({name: "lineDown", keyBinding: new KeyBinding(40), predefined: true}); bindings.push({name: "charPrevious", keyBinding: new KeyBinding(37), predefined: true}); bindings.push({name: "charNext", keyBinding: new KeyBinding(39), predefined: true}); bindings.push({name: "pageUp", keyBinding: new KeyBinding(33), predefined: true}); bindings.push({name: "pageDown", keyBinding: new KeyBinding(34), predefined: true}); if (isMac) { bindings.push({name: "lineStart", keyBinding: new KeyBinding(37, true), predefined: true}); bindings.push({name: "lineEnd", keyBinding: new KeyBinding(39, true), predefined: true}); bindings.push({name: "wordPrevious", keyBinding: new KeyBinding(37, null, null, true), predefined: true}); bindings.push({name: "wordNext", keyBinding: new KeyBinding(39, null, null, true), predefined: true}); bindings.push({name: "textStart", keyBinding: new KeyBinding(36), predefined: true}); bindings.push({name: "textEnd", keyBinding: new KeyBinding(35), predefined: true}); bindings.push({name: "textStart", keyBinding: new KeyBinding(38, true), predefined: true}); bindings.push({name: "textEnd", keyBinding: new KeyBinding(40, true), predefined: true}); } else { bindings.push({name: "lineStart", keyBinding: new KeyBinding(36), predefined: true}); bindings.push({name: "lineEnd", keyBinding: new KeyBinding(35), predefined: true}); bindings.push({name: "wordPrevious", keyBinding: new KeyBinding(37, true), predefined: true}); bindings.push({name: "wordNext", keyBinding: new KeyBinding(39, true), predefined: true}); bindings.push({name: "textStart", keyBinding: new KeyBinding(36, true), predefined: true}); bindings.push({name: "textEnd", keyBinding: new KeyBinding(35, true), predefined: true}); } // Select Cursor Navigation bindings.push({name: "selectLineUp", keyBinding: new KeyBinding(38, null, true), predefined: true}); bindings.push({name: "selectLineDown", keyBinding: new KeyBinding(40, null, true), predefined: true}); bindings.push({name: "selectCharPrevious", keyBinding: new KeyBinding(37, null, true), predefined: true}); bindings.push({name: "selectCharNext", keyBinding: new KeyBinding(39, null, true), predefined: true}); bindings.push({name: "selectPageUp", keyBinding: new KeyBinding(33, null, true), predefined: true}); bindings.push({name: "selectPageDown", keyBinding: new KeyBinding(34, null, true), predefined: true}); if (isMac) { bindings.push({name: "selectLineStart", keyBinding: new KeyBinding(37, true, true), predefined: true}); bindings.push({name: "selectLineEnd", keyBinding: new KeyBinding(39, true, true), predefined: true}); bindings.push({name: "selectWordPrevious", keyBinding: new KeyBinding(37, null, true, true), predefined: true}); bindings.push({name: "selectWordNext", keyBinding: new KeyBinding(39, null, true, true), predefined: true}); bindings.push({name: "selectTextStart", keyBinding: new KeyBinding(36, null, true), predefined: true}); bindings.push({name: "selectTextEnd", keyBinding: new KeyBinding(35, null, true), predefined: true}); bindings.push({name: "selectTextStart", keyBinding: new KeyBinding(38, true, true), predefined: true}); bindings.push({name: "selectTextEnd", keyBinding: new KeyBinding(40, true, true), predefined: true}); } else { bindings.push({name: "selectLineStart", keyBinding: new KeyBinding(36, null, true), predefined: true}); bindings.push({name: "selectLineEnd", keyBinding: new KeyBinding(35, null, true), predefined: true}); bindings.push({name: "selectWordPrevious", keyBinding: new KeyBinding(37, true, true), predefined: true}); bindings.push({name: "selectWordNext", keyBinding: new KeyBinding(39, true, true), predefined: true}); bindings.push({name: "selectTextStart", keyBinding: new KeyBinding(36, true, true), predefined: true}); bindings.push({name: "selectTextEnd", keyBinding: new KeyBinding(35, true, true), predefined: true}); } //Misc bindings.push({name: "deletePrevious", keyBinding: new KeyBinding(8), predefined: true}); bindings.push({name: "deletePrevious", keyBinding: new KeyBinding(8, null, true), predefined: true}); bindings.push({name: "deleteNext", keyBinding: new KeyBinding(46), predefined: true}); bindings.push({name: "deleteWordPrevious", keyBinding: new KeyBinding(8, true), predefined: true}); bindings.push({name: "deleteWordPrevious", keyBinding: new KeyBinding(8, true, true), predefined: true}); bindings.push({name: "deleteWordNext", keyBinding: new KeyBinding(46, true), predefined: true}); bindings.push({name: "tab", keyBinding: new KeyBinding(9), predefined: true}); bindings.push({name: "enter", keyBinding: new KeyBinding(13), predefined: true}); bindings.push({name: "selectAll", keyBinding: new KeyBinding('a', true), predefined: true}); if (isMac) { bindings.push({name: "deleteNext", keyBinding: new KeyBinding(46, null, true), predefined: true}); bindings.push({name: "deleteWordPrevious", keyBinding: new KeyBinding(8, null, null, true), predefined: true}); bindings.push({name: "deleteWordNext", keyBinding: new KeyBinding(46, null, null, true), predefined: true}); } /* * Feature in IE/Chrome: prevent ctrl+'u' and ctrl+'i' from applying styles to the text. * * Note that Chrome applies the styles on the Mac with Ctrl instead of Cmd. */ var isMacChrome = isMac && isChrome; bindings.push({name: null, keyBinding: new KeyBinding('u', !isMacChrome, false, false, isMacChrome), predefined: true}); bindings.push({name: null, keyBinding: new KeyBinding('i', !isMacChrome, false, false, isMacChrome), predefined: true}); if (isFirefox) { bindings.push({name: "copy", keyBinding: new KeyBinding(45, true), predefined: true}); bindings.push({name: "paste", keyBinding: new KeyBinding(45, null, true), predefined: true}); bindings.push({name: "cut", keyBinding: new KeyBinding(46, null, true), predefined: true}); } //1 to 1, no duplicates var self = this; this._actions = [ {name: "lineUp", defaultHandler: function() {return self._doLineUp({select: false});}}, {name: "lineDown", defaultHandler: function() {return self._doLineDown({select: false});}}, {name: "lineStart", defaultHandler: function() {return self._doHome({select: false, ctrl:false});}}, {name: "lineEnd", defaultHandler: function() {return self._doEnd({select: false, ctrl:false});}}, {name: "charPrevious", defaultHandler: function() {return self._doCursorPrevious({select: false, word:false});}}, {name: "charNext", defaultHandler: function() {return self._doCursorNext({select: false, word:false});}}, {name: "pageUp", defaultHandler: function() {return self._doPageUp({select: false});}}, {name: "pageDown", defaultHandler: function() {return self._doPageDown({select: false});}}, {name: "wordPrevious", defaultHandler: function() {return self._doCursorPrevious({select: false, word:true});}}, {name: "wordNext", defaultHandler: function() {return self._doCursorNext({select: false, word:true});}}, {name: "textStart", defaultHandler: function() {return self._doHome({select: false, ctrl:true});}}, {name: "textEnd", defaultHandler: function() {return self._doEnd({select: false, ctrl:true});}}, {name: "selectLineUp", defaultHandler: function() {return self._doLineUp({select: true});}}, {name: "selectLineDown", defaultHandler: function() {return self._doLineDown({select: true});}}, {name: "selectLineStart", defaultHandler: function() {return self._doHome({select: true, ctrl:false});}}, {name: "selectLineEnd", defaultHandler: function() {return self._doEnd({select: true, ctrl:false});}}, {name: "selectCharPrevious", defaultHandler: function() {return self._doCursorPrevious({select: true, word:false});}}, {name: "selectCharNext", defaultHandler: function() {return self._doCursorNext({select: true, word:false});}}, {name: "selectPageUp", defaultHandler: function() {return self._doPageUp({select: true});}}, {name: "selectPageDown", defaultHandler: function() {return self._doPageDown({select: true});}}, {name: "selectWordPrevious", defaultHandler: function() {return self._doCursorPrevious({select: true, word:true});}}, {name: "selectWordNext", defaultHandler: function() {return self._doCursorNext({select: true, word:true});}}, {name: "selectTextStart", defaultHandler: function() {return self._doHome({select: true, ctrl:true});}}, {name: "selectTextEnd", defaultHandler: function() {return self._doEnd({select: true, ctrl:true});}}, {name: "deletePrevious", defaultHandler: function() {return self._doBackspace({word:false});}}, {name: "deleteNext", defaultHandler: function() {return self._doDelete({word:false});}}, {name: "deleteWordPrevious", defaultHandler: function() {return self._doBackspace({word:true});}}, {name: "deleteWordNext", defaultHandler: function() {return self._doDelete({word:true});}}, {name: "tab", defaultHandler: function() {return self._doTab();}}, {name: "enter", defaultHandler: function() {return self._doEnter();}}, {name: "selectAll", defaultHandler: function() {return self._doSelectAll();}}, {name: "copy", defaultHandler: function() {return self._doCopy();}}, {name: "cut", defaultHandler: function() {return self._doCut();}}, {name: "paste", defaultHandler: function() {return self._doPaste();}} ]; }, _createLine: function(parent, sibling, document, lineIndex, model) { var lineText = model.getLine(lineIndex); var lineStart = model.getLineStart(lineIndex); var e = {lineIndex: lineIndex, lineText: lineText, lineStart: lineStart}; this.onLineStyle(e); var child = document.createElement("DIV"); child.lineIndex = lineIndex; this._applyStyle(e.style, child); /* * Firefox does not extend the selection at the end of the line when the * line is fully selected. The fix is to add an extra space at the end of * the line. */ var extendSelection = isFirefox || isOpera; if (lineText.length === 0) { /* * When the span is empty the height of the line div becomes zero. * The fix is use a zero-width non-break space to preserve the default * height in the line div. Note that in Chrome this character shows * a glyph, for this reason the zero-width non-joiner character is * used instead. */ if (!extendSelection) { var span = document.createElement("SPAN"); span.ignoreChars = 1; span.appendChild(document.createTextNode(isWebkit ? "\u200C" : "\uFEFF")); child.appendChild(span); } } else { var start = 0; var tabSize = this._tabSize; if (tabSize && tabSize !== 8) { var tabIndex = lineText.indexOf("\t"), ignoreChars = 0; while (tabIndex !== -1) { this._createRange(child, document, e.ranges, start, tabIndex, lineText, lineStart); var spacesCount = tabSize - ((tabIndex + ignoreChars) % tabSize); var spaces = "\u00A0"; for (var i = 1; i < spacesCount; i++) { spaces += " "; } var tabSpan = document.createElement("SPAN"); tabSpan.appendChild(document.createTextNode(spaces)); tabSpan.ignoreChars = spacesCount - 1; ignoreChars += tabSpan.ignoreChars; if (e.ranges) { for (var j = 0; j < e.ranges.length; j++) { var range = e.ranges[j]; var styleStart = range.start - lineStart; var styleEnd = range.end - lineStart; if (styleStart > tabIndex) { break; } if (styleStart <= tabIndex && tabIndex < styleEnd) { this._applyStyle(range.style, tabSpan); break; } } } child.appendChild(tabSpan); start = tabIndex + 1; tabIndex = lineText.indexOf("\t", start); } } this._createRange(child, document, e.ranges, start, lineText.length, lineText, lineStart); } if (extendSelection) { var ext = document.createElement("SPAN"); ext.ignoreChars = 1; ext.appendChild(document.createTextNode(" ")); child.appendChild(ext); } parent.insertBefore(child, sibling); return child; }, _createRange: function(parent, document, ranges, start, end, text, lineStart) { if (start >= end) { return; } var span; if (ranges) { for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (range.end <= lineStart + start) { continue; } var styleStart = Math.max(lineStart + start, range.start) - lineStart; if (styleStart >= end) { break; } var styleEnd = Math.min(lineStart + end, range.end) - lineStart; if (styleStart < styleEnd) { styleStart = Math.max(start, styleStart); styleEnd = Math.min(end, styleEnd); if (start < styleStart) { span = document.createElement("SPAN"); span.appendChild(document.createTextNode(text.substring(start, styleStart))); parent.appendChild(span); } span = document.createElement("SPAN"); span.appendChild(document.createTextNode(text.substring(styleStart, styleEnd))); this._applyStyle(range.style, span); parent.appendChild(span); start = styleEnd; } } } if (start < end) { span = document.createElement("SPAN"); span.appendChild(document.createTextNode(text.substring(start, end))); parent.appendChild(span); } }, _doAutoScroll: function (direction, x, y) { this._autoScrollDir = direction; this._autoScrollX = x; this._autoScrollY = y; if (!this._autoScrollTimerID) { this._autoScrollTimer(); } }, _endAutoScroll: function () { if (this._autoScrollTimerID) { clearTimeout(this._autoScrollTimerID); } this._autoScrollDir = undefined; this._autoScrollTimerID = undefined; }, _getBoundsAtOffset: function (offset) { return isIE ? this._getBoundsAtOffset_IE(offset) : this._getBoundsAtOffset_FF(offset); }, _getBoundsAtOffset_FF: function (offset) { var model = this._model; var document = this._frameDocument; var clientDiv = this._clientDiv; var lineIndex = model.getLineAtOffset(offset); var dummy; var child = this._getLineNode(lineIndex); if (!child) { child = dummy = this._createLine(clientDiv, null, document, lineIndex, model); } var result = null; if (offset < model.getLineEnd(lineIndex)) { var lineOffset = model.getLineStart(lineIndex); var lineChild = child.firstChild; while (lineChild) { var textNode = lineChild.firstChild; var nodeLength = textNode.length; if (lineChild.ignoreChars) { nodeLength -= lineChild.ignoreChars; } if (lineOffset + nodeLength > offset) { var index = offset - lineOffset; if (isRangeRects) { var range = document.createRange(); range.setStart(textNode, index); range.setEnd(textNode, index + 1); result = range.getBoundingClientRect(); } else { var text = textNode.data; lineChild.removeChild(textNode); lineChild.appendChild(document.createTextNode(text.substring(0, index))); var span = document.createElement("SPAN"); span.appendChild(document.createTextNode(text.substring(index, index + 1))); lineChild.appendChild(span); lineChild.appendChild(document.createTextNode(text.substring(index + 1))); result = span.getBoundingClientRect(); lineChild.innerHTML = ""; lineChild.appendChild(textNode); if (!dummy) { /* * Removing the element node that holds the selection start or end * causes the selection to be lost. The fix is to detect this case * and restore the selection. */ var s = this._getSelection(); if ((lineOffset <= s.start && s.start < lineOffset + nodeLength) || (lineOffset <= s.end && s.end < lineOffset + nodeLength)) { this._updateDOMSelection(); } } } break; } lineOffset += nodeLength; lineChild = lineChild.nextSibling; } } if (!result) { var rect = this._getLineBoundingClientRect(child); result = {left: rect.right, right: rect.right}; } if (dummy) { clientDiv.removeChild(dummy); } return result; }, _getBoundsAtOffset_IE: function (offset) { var document = this._frameDocument; var clientDiv = this._clientDiv; var model = this._model; var lineIndex = model.getLineAtOffset(offset); var dummy; var child = this._getLineNode(lineIndex); if (!child) { child = dummy = this._createLine(clientDiv, null, document, lineIndex, model); } var result = {left: 0, right: 0}; if (offset === model.getLineEnd(lineIndex)) { var rect = this._getLineBoundingClientRect(child); result = {left: rect.right, right: rect.right}; } else { var lineOffset = model.getLineStart(lineIndex); var lineChild = child.firstChild; while (lineChild) { var textNode = lineChild.firstChild; var nodeLength = textNode.length; if (lineChild.ignoreChars) { nodeLength -= lineChild.ignoreChars; } if (lineOffset + nodeLength > offset) { var range = document.body.createTextRange(); range.moveToElementText(lineChild); range.collapse(); range.moveEnd("character", offset - lineOffset + 1); range.moveStart("character", offset - lineOffset); result = range.getBoundingClientRect(); var logicalXDPI = window.screen.logicalXDPI; var deviceXDPI = window.screen.deviceXDPI; result.left = result.left * logicalXDPI / deviceXDPI; result.right = result.right * logicalXDPI / deviceXDPI; break; } lineOffset += nodeLength; lineChild = lineChild.nextSibling; } } if (dummy) { clientDiv.removeChild(dummy); } return result; }, _getBottomIndex: function (fullyVisible) { var child = this._bottomChild; if (fullyVisible && this._getClientHeight() > this._getLineHeight()) { var rect = child.getBoundingClientRect(); var clientRect = this._clientDiv.getBoundingClientRect(); if (rect.bottom > clientRect.bottom) { child = this._getLinePrevious(child) || child; } } return child.lineIndex; }, _getFrameHeight: function() { return this._frameDocument.documentElement.clientHeight; }, _getFrameWidth: function() { return this._frameDocument.documentElement.clientWidth; }, _getClientHeight: function() { var editorPad = this._getEditorPadding(); return Math.max(0, this._editorDiv.clientHeight - editorPad.top - editorPad.bottom); }, _getClientWidth: function() { var editorPad = this._getEditorPadding(); return Math.max(0, this._editorDiv.clientWidth - editorPad.left - editorPad.right); }, _getClipboardText: function (event) { if (this._frameWindow.clipboardData) { //IE return this._frameWindow.clipboardData.getData("Text"); } if (isFirefox) { var textArea = this._textArea; textArea.innerHTML = ""; textArea.focus(); var delimiter = this._model.getLineDelimiter(); var _getText = function() { var text; if (textArea.firstChild) { text = ""; var child = textArea.firstChild; while (child) { if (child.nodeType === child.TEXT_NODE) { text += child.data; } else if (child.tagName === "BR") { text += delimiter; } child = child.nextSibling; } } else { text = textArea.value; } return text; }; //Try execCommand first. Works on firefox with clipboard permission, var result = false; this._ignorePaste = true; try { var document = this._frameDocument; result = document.execCommand("paste", false, null); } catch (ex) { } this._ignorePaste = false; if (!result) { //Try native paste in the text area, works for firefox (asynchronously) //only works during the paste event if (event) { var self = this; setTimeout(function() { self.focus(); var text = _getText(); if (text) { self._doContent(text); } }, 0); return null; } else { //no event and no clipboard permission, paste can't be performed //suggest allow clipboard helper to the user this.focus(); return ""; } } this.focus(); return _getText(); } //webkit if (event && event.clipboardData) { // Webkit (Chrome/Safari) allows getData during the paste event // Note: setData is not allowed, not even during copy/cut event return event.clipboardData.getData("text/plain"); } else { //TODO try paste using extension (Chrome only) } return ""; }, _getDOMText: function(lineIndex) { var child = this._getLineNode(lineIndex); var lineChild = child.firstChild; var text = ""; while (lineChild) { var textNode = lineChild.firstChild; while (textNode) { if (lineChild.ignoreChars) { for (var i = 0; i < textNode.length; i++) { var ch = textNode.data.substring(i, i + 1); if (ch !== " ") { text += ch; } } } else { text += textNode.data; } textNode = textNode.nextSibling; } lineChild = lineChild.nextSibling; } return text; }, _getEditorPadding: function() { if (!this._editorPadding) { this._editorPadding = this._getPadding(this._editorDiv); } return this._editorPadding; }, _getLineBoundingClientRect: function (child) { var rect = child.getBoundingClientRect(); var lastChild = child.lastChild; //Remove any artificial trailing whitespace in the line if (lastChild && lastChild.ignoreChars === 1) { var textNode = lastChild.firstChild; if (textNode.data === " ") { lastChild = lastChild.previousSibling; } } if (!lastChild) { return {left: rect.left, top: rect.top, right: rect.left, bottom: rect.bottom}; } var lastRect = lastChild.getBoundingClientRect(); return {left: rect.left, top: rect.top, right: lastRect.right, bottom: rect.bottom}; }, _getLineHeight: function() { var document = this._frameDocument; var body = document.body; return parseInt(body.style.lineHeight, 10); }, _getLineNode: function (lineIndex) { var clientDiv = this._clientDiv; var child = clientDiv.firstChild; while (child) { if (lineIndex === child.lineIndex) { return child; } child = child.nextSibling; } return undefined; }, _getLineNext: function (lineNode) { var node = lineNode ? lineNode.nextSibling : this._clientDiv.firstChild; while (node && node.lineIndex === -1) { node = node.nextSibling; } return node; }, _getLinePrevious: function (lineNode) { var node = lineNode ? lineNode.previousSibling : this._clientDiv.lastChild; while (node && node.lineIndex === -1) { node = node.previousSibling; } return node; }, _getOffset: function (offset, word, direction) { return isIE ? this._getOffset_IE(offset, word, direction) : this._getOffset_FF(offset, word, direction); }, _getOffset_FF: function (offset, word, direction) { function _isPunctuation(c) { return (33 <= c && c <= 47) || (58 <= c && c <= 64) || (91 <= c && c <= 94) || c === 96 || (123 <= c && c <= 126); } function _isWhitespace(c) { return c === 32 || c === 9; } if (word) { var model = this._model; var lineIndex = model.getLineAtOffset(offset); var lineText = model.getLine(lineIndex); var lineStart = model.getLineStart(lineIndex); var lineEnd = model.getLineEnd(lineIndex); var lineLength = lineText.length; var offsetInLine = offset - lineStart; var c, previousPunctuation, previousLetterOrDigit, punctuation, letterOrDigit; if (direction > 0) { if (offsetInLine === lineLength) { return lineEnd; } c = lineText.charCodeAt(offsetInLine); previousPunctuation = _isPunctuation(c); previousLetterOrDigit = !previousPunctuation && !_isWhitespace(c); offsetInLine++; while (offsetInLine < lineLength) { c = lineText.charCodeAt(offsetInLine); punctuation = _isPunctuation(c); if (punctuation && !previousPunctuation) { break; } letterOrDigit = !punctuation && !_isWhitespace(c); if (letterOrDigit && !previousLetterOrDigit) { break; } previousLetterOrDigit = letterOrDigit; previousPunctuation = punctuation; offsetInLine++; } } else { if (offsetInLine === 0) { return lineStart; } offsetInLine--; c = lineText.charCodeAt(offsetInLine); previousPunctuation = _isPunctuation(c); previousLetterOrDigit = !previousPunctuation && !_isWhitespace(c); while (0 < offsetInLine) { c = lineText.charCodeAt(offsetInLine - 1); punctuation = _isPunctuation(c); if (!punctuation && previousPunctuation) { break; } letterOrDigit = !punctuation && !_isWhitespace(c); if (!letterOrDigit && previousLetterOrDigit) { break; } previousLetterOrDigit = letterOrDigit; previousPunctuation = punctuation; offsetInLine--; } } return lineStart + offsetInLine; } return offset + direction; }, _getOffset_IE: function (offset, word, direction) { var document = this._frameDocument; var model = this._model; var lineIndex = model.getLineAtOffset(offset); var clientDiv = this._clientDiv; var dummy; var child = this._getLineNode(lineIndex); if (!child) { child = dummy = this._createLine(clientDiv, null, document, lineIndex, model); } var result = 0, range, length; var lineOffset = model.getLineStart(lineIndex); if (offset === model.getLineEnd(lineIndex)) { range = document.body.createTextRange(); range.moveToElementText(child.lastChild); length = range.text.length; range.moveEnd(word ? "word" : "character", direction); result = offset + range.text.length - length; } else if (offset === lineOffset && direction < 0) { result = lineOffset; } else { var lineChild = child.firstChild; while (lineChild) { var textNode = lineChild.firstChild; var nodeLength = textNode.length; if (lineChild.ignoreChars) { nodeLength -= lineChild.ignoreChars; } if (lineOffset + nodeLength > offset) { range = document.body.createTextRange(); if (offset === lineOffset && direction < 0) { range.moveToElementText(lineChild.previousSibling); } else { range.moveToElementText(lineChild); range.collapse(); range.moveEnd("character", offset - lineOffset); } length = range.text.length; range.moveEnd(word ? "word" : "character", direction); result = offset + range.text.length - length; break; } lineOffset = nodeLength + lineOffset; lineChild = lineChild.nextSibling; } } if (dummy) { clientDiv.removeChild(dummy); } return result; }, _getOffsetToX: function (offset) { return this._getBoundsAtOffset(offset).left; }, _getPadding: function (node) { var left,top,right,bottom; if (node.currentStyle) { left = node.currentStyle.paddingLeft; top = node.currentStyle.paddingTop; right = node.currentStyle.paddingRight; bottom = node.currentStyle.paddingBottom; } else if (this._frameWindow.getComputedStyle) { var style = this._frameWindow.getComputedStyle(node, null); left = style.getPropertyValue("padding-left"); top = style.getPropertyValue("padding-top"); right = style.getPropertyValue("padding-right"); bottom = style.getPropertyValue("padding-bottom"); } return { left: parseInt(left, 10), top: parseInt(top, 10), right: parseInt(right, 10), bottom: parseInt(bottom, 10) }; }, _getScroll: function() { var editorDiv = this._editorDiv; return {x: editorDiv.scrollLeft, y: editorDiv.scrollTop}; }, _getSelection: function () { return this._selection.clone(); }, _getTopIndex: function (fullyVisible) { var child = this._topChild; if (fullyVisible && this._getClientHeight() > this._getLineHeight()) { var rect = child.getBoundingClientRect(); var editorPad = this._getEditorPadding(); var editorRect = this._editorDiv.getBoundingClientRect(); if (rect.top < editorRect.top + editorPad.top) { child = this._getLineNext(child) || child; } } return child.lineIndex; }, _getXToOffset: function (lineIndex, x) { return isIE ? this._getXToOffset_IE(lineIndex, x) : this._getXToOffset_FF(lineIndex, x); }, _getXToOffset_FF: function (lineIndex, x) { var model = this._model; var document = this._frameDocument; var clientDiv = this._clientDiv; var dummy; var child = this._getLineNode(lineIndex); if (!child) { child = dummy = this._createLine(clientDiv, null, document, lineIndex, model); } var lineRect = this._getLineBoundingClientRect(child); if (x < lineRect.left) { x = lineRect.left; } if (x > lineRect.right) { x = lineRect.right; } var offset = model.getLineStart(lineIndex); var lineChild = child.firstChild; done: while (lineChild) { var textNode = lineChild.firstChild; var nodeLength = textNode.length; if (lineChild.ignoreChars) { nodeLength -= lineChild.ignoreChars; } var rects = lineChild.getClientRects(); for (var i = 0; i < rects.length; i++) { var rect = rects[i]; if (rect.left <= x && x < rect.right) { if (isRangeRects) { var range = document.createRange(); var index = 0; while (index < nodeLength) { range.setStart(textNode, index); range.setEnd(textNode, index + 1); rect = range.getBoundingClientRect(); if (rect.left <= x && x < rect.right) { //TODO test for character trailing (wrong for bidi) if (x > rect.left + (rect.right - rect.left) / 2) { index++; } break; } index++; } offset += index; } else { var newText = []; for (var j = 0; j < nodeLength; j++) { newText.push("<span>"); if (j === nodeLength - 1) { newText.push(textNode.data.substring(j)); } else { newText.push(textNode.data.substring(j, j + 1)); } newText.push("</span>"); } lineChild.innerHTML = newText.join(""); var rangeChild = lineChild.firstChild; while (rangeChild) { rect = rangeChild.getBoundingClientRect(); if (rect.left <= x && x < rect.right) { //TODO test for character trailing (wrong for bidi) if (x > rect.left + (rect.right - rect.left) / 2) { offset++; } break; } offset++; rangeChild = rangeChild.nextSibling; } if (!dummy) { lineChild.innerHTML = ""; lineChild.appendChild(textNode); /* * Removing the element node that holds the selection start or end * causes the selection to be lost. The fix is to detect this case * and restore the selection. */ var s = this._getSelection(); if ((offset <= s.start && s.start < offset + nodeLength) || (offset <= s.end && s.end < offset + nodeLength)) { this._updateDOMSelection(); } } } break done; } } offset += nodeLength; lineChild = lineChild.nextSibling; } if (dummy) { clientDiv.removeChild(dummy); } return offset; }, _getXToOffset_IE: function (lineIndex, x) { var model = this._model; var document = this._frameDocument; var clientDiv = this._clientDiv; var dummy; var child = this._getLineNode(lineIndex); if (!child) { child = dummy = this._createLine(clientDiv, null, document, lineIndex, model); } var lineRect = this._getLineBoundingClientRect(child); if (x < lineRect.left) { x = lineRect.left; } if (x > lineRect.right) { x = lineRect.right; } /* * Bug in IE. The coordinates of getClientRects() are relative to * the browser window. The fix is to convert to the frame window * before using it. */ var rects = child.getClientRects(); var minLeft = rects[0].left; for (var i=1; i<rects.length; i++) { minLeft = Math.min(rects[i].left, minLeft); } var deltaX = minLeft - lineRect.left; var scrollX = this._getScroll().x; function _getClientRects(element) { var rects, newRects, i, r; if (!element._rectsCache) { rects = element.getClientRects(); newRects = [rects.length]; for (i = 0; i<rects.length; i++) { r = rects[i]; newRects[i] = {left: r.left - deltaX + scrollX, top: r.top, right: r.right - deltaX + scrollX, bottom: r.bottom}; } element._rectsCache = newRects; } rects = element._rectsCache; newRects = [rects.length]; for (i = 0; i<rects.length; i++) { r = rects[i]; newRects[i] = {left: r.left - scrollX, top: r.top, right: r.right - scrollX, bottom: r.bottom}; } return newRects; } var offset = model.getLineStart(lineIndex); var lineChild = child.firstChild; var logicalXDPI = window.screen.logicalXDPI; var deviceXDPI = window.screen.deviceXDPI; done: while (lineChild) { var textNode = lineChild.firstChild; var nodeLength = textNode.length; if (lineChild.ignoreChars) { nodeLength -= lineChild.ignoreChars; } rects = _getClientRects(lineChild); for (var j = 0; j < rects.length; j++) { var rect = rects[j]; if (rect.left <= x && x < rect.right) { var range = document.body.createTextRange(); var high = textNode.length; var low = -1; while ((high - low) > 1) { var mid = Math.floor((high + low) / 2); range.moveToElementText(lineChild); range.move("character", low + 1); range.moveEnd("character", mid - low); rects = range.getClientRects(); var found = false; for (var k = 0; k < rects.length; k++) { rect = rects[k]; var rangeLeft = rect.left * logicalXDPI / deviceXDPI - deltaX; var rangeRight = rect.right * logicalXDPI / deviceXDPI - deltaX; if (rangeLeft <= x && x < rangeRight) { found = true; break; } } if (found) { high = mid; } else { low = mid; } } if (lineChild.ignoreChars && high >= nodeLength) { high = nodeLength - 1; } offset += high; range.moveToElementText(lineChild); range.move("character", high); if (high === nodeLength - 1 && lineChild.ignoreChars) { range.moveEnd("character", 1 + lineChild.ignoreChars); } else { range.moveEnd("character", 1); } rect = range.getClientRects()[0]; //TODO test for character trailing (wrong for bidi) if (x > ((rect.left - deltaX) + ((rect.right - rect.left) / 2))) { offset++; } break done; } } offset += nodeLength; lineChild = lineChild.nextSibling; } if (dummy) { clientDiv.removeChild(dummy); } return offset; }, _getYToLine: function (y) { var editorPad = this._getEditorPadding(); var editorRect = this._editorDiv.getBoundingClientRect(); y -= editorRect.top + editorPad.top; var lineHeight = this._getLineHeight(); var lineIndex = Math.floor((y + this._getScroll().y) / lineHeight); var lineCount = this._model.getLineCount(); return Math.max(0, Math.min(lineCount - 1, lineIndex)); }, _hookEvents: function() { var self = this; this._modelListener = { /** @private */ onChanging: function(newText, start, removedCharCount, addedCharCount, removedLineCount, addedLineCount) { self._onModelChanging(newText, start, removedCharCount, addedCharCount, removedLineCount, addedLineCount); }, /** @private */ onChanged: function(start, removedCharCount, addedCharCount, removedLineCount, addedLineCount) { self._onModelChanged(start, removedCharCount, addedCharCount, removedLineCount, addedLineCount); } }; this._model.addListener(this._modelListener); this._mouseMoveClosure = function(e) { return self._handleMouseMove(e);}; this._mouseUpClosure = function(e) { return self._handleMouseUp(e);}; var clientDiv = this._clientDiv; var editorDiv = this._editorDiv; var topNode = this._overlayDiv || this._clientDiv; var body = this._frameDocument.body; var resizeNode = isIE ? this._frame : this._frameWindow; var focusNode = isIE ? this._clientDiv: this._frameWindow; this._handlers = [ {target: editorDiv, type: "scroll", handler: function(e) { return self._handleScroll(e);}}, {target: clientDiv, type: "keydown", handler: function(e) { return self._handleKeyDown(e);}}, {target: clientDiv, type: "keypress", handler: function(e) { return self._handleKeyPress(e);}}, {target: clientDiv, type: "keyup", handler: function(e) { return self._handleKeyUp(e);}}, {target: clientDiv, type: "selectstart", handler: function(e) { return self._handleSelectStart(e);}}, {target: clientDiv, type: "contextmenu", handler: function(e) { return self._handleContextMenu(e);}}, {target: clientDiv, type: "copy", handler: function(e) { return self._handleCopy(e);}}, {target: clientDiv, type: "cut", handler: function(e) { return self._handleCut(e);}}, {target: clientDiv, type: "paste", handler: function(e) { return self._handlePaste(e);}}, {target: focusNode, type: "blur", handler: function(e) { return self._handleBlur(e);}}, {target: focusNode, type: "focus", handler: function(e) { return self._handleFocus(e);}}, {target: topNode, type: "mousedown", handler: function(e) { return self._handleMouseDown(e);}}, {target: body, type: "mousedown", handler: function(e) { return self._handleBodyMouseDown(e);}}, {target: topNode, type: "dragstart", handler: function(e) { return self._handleDragStart(e);}}, {target: resizeNode, type: "resize", handler: function(e) { return self._handleResize(e);}} ]; if (isIE) { this._handlers.push({target: this._frameDocument, type: "activate", handler: function(e) { return self._handleDocFocus(e); }}); } if (isFirefox) { this._handlers.push({target: this._frameDocument, type: "focus", handler: function(e) { return self._handleDocFocus(e); }}); } if (!isIE && !isOpera) { var wheelEvent = isFirefox ? "DOMMouseScroll" : "mousewheel"; this._handlers.push({target: this._editorDiv, type: wheelEvent, handler: function(e) { return self._handleMouseWheel(e); }}); } if (isFirefox && !isWindows) { this._handlers.push({target: this._clientDiv, type: "DOMCharacterDataModified", handler: function (e) { return self._handleDataModified(e); }}); } if (this._overlayDiv) { this._handlers.push({target: this._overlayDiv, type: "contextmenu", handler: function(e) { return self._handleContextMenu(e); }}); } if (!isW3CEvents) { this._handlers.push({target: this._clientDiv, type: "dblclick", handler: function(e) { return self._handleDblclick(e); }}); } for (var i=0; i<this._handlers.length; i++) { var h = this._handlers[i]; addHandler(h.target, h.type, h.handler); } }, _init: function(options) { var parent = options.parent; if (typeof(parent) === "string") { parent = window.document.getElementById(parent); } if (!parent) { throw "no parent"; } this._parent = parent; this._model = options.model ? options.model : new eclipse.TextModel(); this.readonly = options.readonly === true; this._selection = new Selection (0, 0, false); this._eventTable = new EventTable(); this._maxLineWidth = 0; this._maxLineIndex = -1; this._ignoreSelect = true; this._columnX = -1; /* Auto scroll */ this._autoScrollX = null; this._autoScrollY = null; this._autoScrollTimerID = null; this._AUTO_SCROLL_RATE = 50; this._grabControl = null; this._moseMoveClosure = null; this._mouseUpClosure = null; /* Double click */ this._lastMouseX = 0; this._lastMouseY = 0; this._lastMouseTime = 0; this._clickCount = 0; this._clickTime = 250; this._clickDist = 5; this._isMouseDown = false; this._doubleClickSelection = null; /* Scroll */ this._hScroll = 0; this._vScroll = 0; /* IME */ this._imeOffset = -1; /* Create elements */ while (parent.hasChildNodes()) { parent.removeChild(parent.lastChild); } var parentDocument = parent.document || parent.ownerDocument; this._parentDocument = parentDocument; var frame = parentDocument.createElement("IFRAME"); this._frame = frame; frame.frameBorder = "0px";//for IE, needs to be set before the frame is added to the parent frame.style.width = "100%"; frame.style.height = "100%"; frame.scrolling = "no"; frame.style.border = "0px"; parent.appendChild(frame); var html = []; html.push("<!DOCTYPE html>"); html.push("<html>"); html.push("<head>"); html.push("<meta http-equiv='X-UA-Compatible' content='IE=EmulateIE7'/>"); html.push("<style>"); html.push(".editorContainer {font-family: monospace; font-size: 10pt;}"); html.push(".editor {padding: 1px 2px;}"); html.push(".editorContent {}"); html.push("</style>"); if (options.stylesheet) { var stylesheet = typeof(options.stylesheet) === "string" ? [options.stylesheet] : options.stylesheet; for (var i = 0; i < stylesheet.length; i++) { try { //Force CSS to be loaded synchronously so lineHeight can be calculated var objXml = new XMLHttpRequest(); objXml.open("GET", stylesheet[i], false); objXml.send(null); html.push("<style>"); html.push(objXml.responseText); html.push("</style>"); } catch (e) { html.push("<link rel='stylesheet' type='text/css' href='"); html.push(stylesheet[i]); html.push("'></link>"); } } } html.push("</head>"); html.push("<body spellcheck='false'></body>"); html.push("</html>"); var frameWindow = frame.contentWindow; this._frameWindow = frameWindow; var document = frameWindow.document; this._frameDocument = document; document.open(); document.write(html.join("")); document.close(); var body = document.body; body.className = "editorContainer"; body.style.margin = "0px"; body.style.borderWidth = "0px"; body.style.padding = "0px"; var textArea = document.createElement("TEXTAREA"); this._textArea = textArea; textArea.id = "textArea"; textArea.tabIndex = -1; textArea.style.position = "fixed"; textArea.style.whiteSpace = "pre"; textArea.style.top = "-1000px"; textArea.style.width = "100px"; textArea.style.height = "100px"; body.appendChild(textArea); var editorDiv = document.createElement("DIV"); editorDiv.className = "editor"; this._editorDiv = editorDiv; editorDiv.id = "editorDiv"; editorDiv.tabIndex = -1; editorDiv.style.overflow = "auto"; editorDiv.style.position = "absolute"; editorDiv.style.top = "0px"; editorDiv.style.borderWidth = "0px"; editorDiv.style.margin = "0px"; editorDiv.style.MozOutline = "none"; editorDiv.style.outline = "none"; body.appendChild(editorDiv); var scrollDiv = document.createElement("DIV"); this._scrollDiv = scrollDiv; scrollDiv.id = "scrollDiv"; scrollDiv.style.margin = "0px"; scrollDiv.style.borderWidth = "0px"; scrollDiv.style.padding = "0px"; editorDiv.appendChild(scrollDiv); var clientDiv = document.createElement("DIV"); clientDiv.className = "editorContent"; this._clientDiv = clientDiv; clientDiv.id = "clientDiv"; clientDiv.style.whiteSpace = "pre"; clientDiv.style.position = "fixed"; clientDiv.style.borderWidth = "0px"; clientDiv.style.margin = "0px"; clientDiv.style.padding = "0px"; clientDiv.style.MozOutline = "none"; clientDiv.style.outline = "none"; scrollDiv.appendChild(clientDiv); if (false && isFirefox) { var overlayDiv = document.createElement("DIV"); this._overlayDiv = overlayDiv; overlayDiv.id = "overlayDiv"; overlayDiv.style.position = clientDiv.style.position; overlayDiv.style.borderWidth = clientDiv.style.borderWidth; overlayDiv.style.margin = clientDiv.style.margin; overlayDiv.style.padding = clientDiv.style.padding; overlayDiv.style.cursor = "text"; overlayDiv.style.zIndex = "1"; scrollDiv.appendChild(overlayDiv); } clientDiv.contentEditable = "true"; body.style.lineHeight = this._calculateLineHeight() + "px"; if (options.tabSize) { if (isOpera) { clientDiv.style.OTabSize = options.tabSize+""; } else if (isFirefox >= 4) { clientDiv.style.MozTabSize = options.tabSize+""; } else if (options.tabSize !== 8) { this._tabSize = options.tabSize; } } this._createActions(); this._hookEvents(); }, _isDOMSelectionComplete: function() { var selection = this._getSelection(); var topIndex = this._getTopIndex(); var bottomIndex = this._getBottomIndex(); var model = this._model; var firstLine = model.getLineAtOffset(selection.start); var lastLine = model.getLineAtOffset(selection.start !== selection.end ? selection.end - 1 : selection.end); if (topIndex <= firstLine && firstLine <= bottomIndex && topIndex <= lastLine && lastLine <= bottomIndex) { var child = this._getLineNode(firstLine); while (child && child.lineIndex <= lastLine) { var lineChild = child.firstChild; while (lineChild) { if (lineChild.ignoreChars) { return false; } lineChild = lineChild.nextSibling; } child = this._getLineNext(child); } return true; } return false; }, _modifyContent: function(e, updateCaret) { if (this.readonly && !e._code) { return; } this.onVerify(e); if (e.text === null || e.text === undefined) { return; } var model = this._model; if (e._ignoreDOMSelection) { this._ignoreDOMSelection = true; } model.setText (e.text, e.start, e.end); if (e._ignoreDOMSelection) { this._ignoreDOMSelection = false; } if (updateCaret) { var selection = this._getSelection (); selection.setCaret(e.start + e.text.length); this._setSelection(selection, true); this._showCaret(); } this.onModify({}); }, _onModelChanged: function(start, removedCharCount, addedCharCount, removedLineCount, addedLineCount) { var e = { start: start, removedCharCount: removedCharCount, addedCharCount: addedCharCount, removedLineCount: removedLineCount, addedLineCount: addedLineCount }; this.onModelChanged(e); var selection = this._getSelection(); if (selection.end > start) { if (selection.end > start && selection.start < start + removedCharCount) { // selection intersects replaced text. set caret behind text change selection.setCaret(start + addedCharCount); } else { // move selection to keep same text selected selection.start += addedCharCount - removedCharCount; selection.end += addedCharCount - removedCharCount; } this._setSelection(selection, false, false); } var model = this._model; var startLine = model.getLineAtOffset(start); var child = this._getLineNext(); while (child) { var lineIndex = child.lineIndex; if (startLine <= lineIndex && lineIndex <= startLine + removedLineCount) { child.lineChanged = true; } if (lineIndex > startLine + removedLineCount) { child.lineIndex = lineIndex + addedLineCount - removedLineCount; } child = this._getLineNext(child); } if (startLine <= this._maxLineIndex && this._maxLineIndex <= startLine + removedLineCount) { this._maxLineIndex = -1; this._maxLineWidth = 0; } this._updatePage(); }, _onModelChanging: function(newText, start, removedCharCount, addedCharCount, removedLineCount, addedLineCount) { var e = { text: newText, start: start, removedCharCount: removedCharCount, addedCharCount: addedCharCount, removedLineCount: removedLineCount, addedLineCount: addedLineCount }; this.onModelChanging(e); }, _queueUpdatePage: function() { if (this._updateTimer) { return; } var self = this; this._updateTimer = setTimeout(function() { self._updateTimer = null; self._updatePage(); }, 0); }, _scrollView: function (pixelX, pixelY) { /* * IE redraws the page when scrollTop is changed. This redraw is not necessary * while scrolling since updatePage() will be called in _handleScroll(). In order * to improve performance, the page is hidden during scroll causing only on redraw * to happen. Note that this approach causes flashing on Firefox. * * This code is intentionally commented. It causes editor to loose focus. */ // if (isIE) { // this._frameDocument.body.style.visibility = "hidden"; // } var editorDiv = this._editorDiv; var newX = editorDiv.scrollLeft + pixelX; if (pixelX) { editorDiv.scrollLeft = newX; } var newY = editorDiv.scrollTop + pixelY; if (pixelY) { editorDiv.scrollTop = newY; } this._doScroll({x: newX, y: newY}); // this._handleScroll(); // if (isIE) { // this._frameDocument.body.style.visibility = "visible"; // this.focus(); // } }, _setClipboardText: function (text, event) { if (this._frameWindow.clipboardData) { //IE return this._frameWindow.clipboardData.setData("Text", text); } if (isChrome || isFirefox || !event) { /* Feature in Chrome, clipboardData.setData is no-op on chrome, the fix is to use execCommand */ var document = this._frameDocument; var textArea = this._textArea; textArea.value = text; textArea.select(); var result = false; //Try execCommand first, it works on firefox with clipboard permission, // chrome 5, safari 4. this._ignoreCopy = true; try { result = document.execCommand("copy", false, null); } catch (e) {} this._ignoreCopy = false; if (!result) { if (event) { if (event.type === "copy" && this._isDOMSelectionComplete()) { this.focus(); return false; } var self = this; setTimeout(function() { self.focus(); }, 0); return false; } else { //no event and no permission, give up this.focus(); return true; } } this.focus(); return result; } if (event && event.clipboardData) { //webkit return event.clipboardData.setData("text/plain", text); } }, _setDOMSelection: function (startNode, startOffset, endNode, endOffset) { var window = this._frameWindow; var document = this._frameDocument; var startLineNode, startLineOffset, endLineNode, endLineOffset; var offset = 0; var lineChild = startNode.firstChild; var node, nodeLength, lineEnd; lineEnd = this._model.getLine(startNode.lineIndex).length; while (lineChild) { node = lineChild.firstChild; nodeLength = node.length; if (lineChild.ignoreChars) { nodeLength -= lineChild.ignoreChars; } if (offset + nodeLength > startOffset || offset + nodeLength >= lineEnd) { startLineNode = node; startLineOffset = startOffset - offset; if (lineChild.ignoreChars && nodeLength > 0 && startLineOffset === nodeLength) { startLineOffset += lineChild.ignoreChars; } break; } offset += nodeLength; lineChild = lineChild.nextSibling; } offset = 0; lineEnd = this._model.getLine(endNode.lineIndex).length; lineChild = endNode.firstChild; while (lineChild) { node = lineChild.firstChild; nodeLength = node.length; if (lineChild.ignoreChars) { nodeLength -= lineChild.ignoreChars; } if (nodeLength + offset > endOffset || offset + nodeLength >= lineEnd) { endLineNode = node; endLineOffset = endOffset - offset; if (lineChild.ignoreChars && nodeLength > 0 && endLineOffset === nodeLength) { endLineOffset += lineChild.ignoreChars; } break; } offset += nodeLength; lineChild = lineChild.nextSibling; } var range; if (window.getSelection) { //FF range = document.createRange(); range.setStart(startLineNode, startLineOffset); range.setEnd(endLineNode, endLineOffset); var sel = window.getSelection(); this._ignoreSelect = false; if (sel.rangeCount > 0) { sel.removeAllRanges(); } sel.addRange(range); this._ignoreSelect = true; } else if (document.selection) { //IE var body = document.body; /* * Bug in IE. For some reason when text is deselected the overflow * selection at the end of some lines does not get redrawn. The * fix is to create a DOM element in the body to force a redraw. */ var child = document.createElement("DIV"); body.appendChild(child); body.removeChild(child); range = body.createTextRange(); range.moveToElementText(startLineNode.parentNode); range.moveStart("character", startLineOffset); var endRange = body.createTextRange(); endRange.moveToElementText(endLineNode.parentNode); endRange.moveStart("character", endLineOffset); range.setEndPoint("EndToStart", endRange); this._ignoreSelect = false; range.select(); this._ignoreSelect = true; } }, _setGrab: function (target) { if (target === this._grabControl) { return; } if (target) { addHandler(target, "mousemove", this._mouseMoveClosure); addHandler(target, "mouseup", this._mouseUpClosure); if (target.setCapture) { target.setCapture(); } this._grabControl = target; } else { removeHandler(this._grabControl, "mousemove", this._mouseMoveClosure); removeHandler(this._grabControl, "mouseup", this._mouseUpClosure); if (this._grabControl.releaseCapture) { this._grabControl.releaseCapture(); } this._grabControl = null; } }, _setSelection: function (selection, scroll, update) { if (selection) { this._columnX = -1; if (update === undefined) { update = true; } var oldSelection = this._selection; if (!oldSelection.equals(selection)) { this._selection = selection; var e = { oldValue: {start:oldSelection.start, end:oldSelection.end}, newValue: {start:selection.start, end:selection.end} }; this.onSelection(e); if (scroll) { update = !this._showCaret(); } } /* Sometimes the browser changes the selection * as result of method calls or "leaked" events. * The fix is to set the visual selection even * when the logical selection is not changed. */ if (update) { this._updateDOMSelection(); } } }, _setSelectionTo: function (x,y,extent) { var model = this._model, offset; var selection = this._getSelection(); var lineIndex = this._getYToLine(y); if (this._clickCount === 1) { offset = this._getXToOffset(lineIndex, x); selection.extend(offset); if (!extent) { selection.collapse(); } } else { var word = (this._clickCount & 1) === 0; var start, end; if (word) { offset = this._getXToOffset(lineIndex, x); if (this._doubleClickSelection) { if (offset >= this._doubleClickSelection.start) { start = this._doubleClickSelection.start; end = this._getOffset(offset, true, +1); } else { start = this._getOffset(offset, true, -1); end = this._doubleClickSelection.end; } } else { start = this._getOffset(offset, true, -1); end = this._getOffset(start, true, +1); } } else { if (this._doubleClickSelection) { var doubleClickLine = model.getLineAtOffset(this._doubleClickSelection.start); if (lineIndex >= doubleClickLine) { start = model.getLineStart(doubleClickLine); end = model.getLineEnd(lineIndex); } else { start = model.getLineStart(lineIndex); end = model.getLineEnd(doubleClickLine); } } else { start = model.getLineStart(lineIndex); end = model.getLineEnd(lineIndex); } } selection.setCaret(start); selection.extend(end); } this._setSelection(selection, true, true); }, _showCaret: function () { var model = this._model; var selection = this._getSelection(); var scroll = this._getScroll(); var caret = selection.getCaret(); var start = selection.start; var end = selection.end; var startLine = model.getLineAtOffset(start); var endLine = model.getLineAtOffset(end); var endInclusive = Math.max(Math.max(start, model.getLineStart(endLine)), end - 1); var editorPad = this._getEditorPadding(); var clientWidth = this._getClientWidth(); var leftEdge = editorPad.left; var rightEdge = editorPad.left + clientWidth; var bounds = this._getBoundsAtOffset(caret === start ? start : endInclusive); var left = bounds.left; var right = bounds.right; var minScroll = clientWidth / 4; if (!selection.isEmpty() && startLine === endLine) { bounds = this._getBoundsAtOffset(caret === end ? start : endInclusive); var selectionWidth = caret === start ? bounds.right - left : right - bounds.left; if ((clientWidth - minScroll) > selectionWidth) { if (left > bounds.left) { left = bounds.left; } if (right < bounds.right) { right = bounds.right; } } } var editorRect = this._editorDiv.getBoundingClientRect(); left -= editorRect.left; right -= editorRect.left; var pixelX = 0; if (left < leftEdge) { pixelX = Math.min(left - leftEdge, -minScroll); } if (right > rightEdge) { var maxScroll = this._scrollDiv.scrollWidth - scroll.x - clientWidth; pixelX = Math.min(maxScroll, Math.max(right - rightEdge, minScroll)); } var pixelY = 0; var topIndex = this._getTopIndex(true); var bottomIndex = this._getBottomIndex(true); var caretLine = model.getLineAtOffset(caret); var clientHeight = this._getClientHeight(); if (!(topIndex <= caretLine && caretLine <= bottomIndex)) { var lineHeight = this._getLineHeight(); var selectionHeight = (endLine - startLine) * lineHeight; pixelY = caretLine * lineHeight; pixelY -= scroll.y; if (pixelY + lineHeight > clientHeight) { pixelY -= clientHeight - lineHeight; if (caret === start && start !== end) { pixelY += Math.min(clientHeight - lineHeight, selectionHeight); } } else { if (caret === end) { pixelY -= Math.min (clientHeight - lineHeight, selectionHeight); } } } if (pixelX !== 0 || pixelY !== 0) { this._scrollView (pixelX, pixelY); if (clientHeight !== this._getClientHeight() || clientWidth !== this._getClientWidth()) { this._showCaret(); } return true; } return false; }, _startIME: function () { if (this._imeOffset !== -1) { return; } var selection = this._getSelection(); if (!selection.isEmpty()) { this._modifyContent({text: "", start: selection.start, end: selection.end}, true); } this._imeOffset = selection.start; }, _unhookEvents: function() { this._model.removeListener(this._modelListener); this._modelListener = null; this._mouseMoveClosure = null; this._mouseUpClosure = null; for (var i=0; i<this._handlers.length; i++) { var h = this._handlers[i]; removeHandler(h.target, h.type, h.handler); } this._handlers = null; }, _updateDOMSelection: function () { if (this._ignoreDOMSelection) { return; } var selection = this._getSelection(); var model = this._model; var startLine = model.getLineAtOffset(selection.start); var endLine = model.getLineAtOffset(selection.end); var firstNode = this._getLineNext(); /* * Bug in Firefox. For some reason, after a update page sometimes the * firstChild returns null incorrectly. The fix is to ignore show selection. */ if (!firstNode) { return; } var lastNode = this._getLinePrevious(); var topNode, bottomNode, topOffset, bottomOffset; if (startLine < firstNode.lineIndex) { topNode = firstNode; topOffset = 0; } else if (startLine > lastNode.lineIndex) { topNode = lastNode; topOffset = 0; } else { topNode = this._getLineNode(startLine); topOffset = selection.start - model.getLineStart(startLine); } if (endLine < firstNode.lineIndex) { bottomNode = firstNode; bottomOffset = 0; } else if (endLine > lastNode.lineIndex) { bottomNode = lastNode; bottomOffset = 0; } else { bottomNode = this._getLineNode(endLine); bottomOffset = selection.end - model.getLineStart(endLine); } this._setDOMSelection(topNode, topOffset, bottomNode, bottomOffset); }, _updatePage: function() { if (this._updateTimer) { clearTimeout(this._updateTimer); this._updateTimer = null; } //************************************************************************************************** var document = this._frameDocument; var frameWidth = this._getFrameWidth(); var frameHeight = this._getFrameHeight(); //document.body.style.width = frameWidth + "px"; //document.body.style.height = frameHeight + "px"; var editorDiv = this._editorDiv; var clientDiv = this._clientDiv; var editorPad = this._getEditorPadding(); /* Update editor height in order to have client height computed */ editorDiv.style.height = Math.max(0, (frameHeight - editorPad.top - editorPad.bottom)) + "px"; var model = this._model; var lineHeight = 16; var scrollY = this._getScroll().y; var firstLine = Math.max(0, scrollY) / lineHeight; var topIndex = Math.floor(firstLine); var lineStart = Math.max(0, topIndex - 1); var top = Math.round((firstLine - lineStart) * lineHeight); var lineCount = model.getLineCount(); var clientHeight = 256; var partialY = Math.round((firstLine - topIndex) * lineHeight); var linesPerPage = Math.floor((clientHeight + partialY) / lineHeight); var bottomIndex = Math.min(topIndex + linesPerPage, lineCount - 1); var lineEnd = Math.min(bottomIndex + 1, lineCount - 1); this._partialY = partialY; //************************************************************************************************** var lineIndex, lineWidth, child, nextChild; //************************************************************************************************** (function _updatePage_removeLines(){ lineIndex, lineWidth; child = clientDiv.firstChild; while (child) { lineIndex = child.lineIndex; nextChild = child.nextSibling; if (!(lineStart <= lineIndex && lineIndex <= lineEnd) || child.lineChanged || child.lineIndex === -1) { if (this._mouseWheelLine === child) { child.style.display = "none"; child.lineIndex = -1; } else { clientDiv.removeChild(child); } } child = nextChild; } }).call(this); //************************************************************************************************** this._maxLineWidth = 1000; this._maxLineIndex = 1; //var rect; //************************************************************************************************** (function _updatePage_createLines(){ // Webkit still wraps even if pre is used clientDiv.style.width = (0x7FFFF).toString() + "px"; child = this._getLineNext(); for (lineIndex=lineStart; lineIndex<=lineEnd; lineIndex++) { if (!child || child.lineIndex > lineIndex) { child = this._createLine(clientDiv, child, document, lineIndex, model); /* rect = this._getLineBoundingClientRect(child); lineWidth = rect.right - rect.left; child.lineWidth = lineWidth; // when the maxLineIndex is known measure only the lines that have changed if (this._maxLineIndex !== -1) { if (lineWidth >= this._maxLineWidth) { this._maxLineWidth = lineWidth; this._maxLineIndex = lineIndex; } } */ } if (lineIndex === topIndex) { this._topChild = child; } if (lineIndex === bottomIndex) { this._bottomChild = child; } if (child.lineIndex === lineIndex) { child = this._getLineNext(child); } } }).call(this); //************************************************************************************************** //************************************************************************************************** /* (function _updatePage_updateMaxLineWidth(){ // when the maxLineIndex is not known all the visible lines need to be measured if (this._maxLineIndex === -1) { child = this._getLineNext(); while (child) { lineWidth = child.lineWidth; if (lineWidth >= this._maxLineWidth) { this._maxLineWidth = lineWidth; this._maxLineIndex = child.lineIndex; } child = this._getLineNext(child); } } }).call(this); */ //************************************************************************************************** //************************************************************************************************** (function _updatePage_updateRulers(){ // Update rulers this._updateRuler(this._leftDiv, topIndex, bottomIndex); this._updateRuler(this._rightDiv, topIndex, bottomIndex); }).call(this); //************************************************************************************************** var leftWidth, rightWidth, scrollDiv, scrollHeight, clientWidth, width, scrollWidth; //************************************************************************************************** if (window.editorDivStyleApplied < 3) (function _updatePage_updateEditorDivStyle(){ window.editorDivStyleApplied++; leftWidth = this._leftDiv ? this._leftDiv.scrollWidth : 0; rightWidth = this._rightDiv ? this._rightDiv.scrollWidth : 0; editorDiv.style.left = leftWidth + "px"; editorDiv.style.width = Math.max(0, frameWidth - leftWidth - rightWidth - editorPad.left - editorPad.right) + "px"; if (this._rightDiv) { this._rightDiv.style.left = (frameWidth - rightWidth) + "px"; } }).call(this); //************************************************************************************************** //************************************************************************************************** if (window.scrollDivStyleApplied < 3) (function _updatePage_updateScrollDivStyle(){ window.scrollDivStyleApplied++; scrollDiv = this._scrollDiv; /* Need to set the height first in order for the width to consider the vertical scrollbar */ scrollHeight = lineCount * lineHeight; scrollDiv.style.height = scrollHeight + "px"; clientWidth = this._getClientWidth(); width = Math.max(this._maxLineWidth, clientWidth); /* Except by IE, all other browsers are not allocating enough space for the right padding * in the scrollbar. It is possible this a bug since all other paddings are considered. */ scrollWidth = width; if (!isIE) { width += editorPad.right; } scrollDiv.style.width = width + "px"; }).call(this); //************************************************************************************************** //************************************************************************************************** (function _updatePage_updateDOMSelection(){ /* * Get client height after both scrollbars are visible and updatePage again to recalculate top and bottom indices. * * Note that updateDOMSelection() has to be called on IE before getting the new client height because it * forces the client area to be recomputed. */ this._updateDOMSelection(); }).call(this); //************************************************************************************************** /*if (clientHeight !== this._getClientHeight()) { this._updatePage(); return; }*/ var scroll, left, clipLeft, clipTop, clipRight, clipBottom, overlayDiv; //************************************************************************************************** (function _updatePage_updateViewport(){ // Get the left scroll after setting the width of the scrollDiv as this can change the horizontal scroll offset. scroll = this._getScroll(); left = scroll.x; clipLeft = left; clipTop = top; clipRight = left + clientWidth; clipBottom = top + clientHeight; if (clipLeft === 0) { clipLeft -= editorPad.left; } if (clipTop === 0) { clipTop -= editorPad.top; } if (clipRight === scrollWidth) { clipRight += editorPad.right; } if (scroll.y + clientHeight === scrollHeight) { clipBottom += editorPad.bottom; } clientDiv.style.clip = "rect(" + clipTop + "px," + clipRight + "px," + clipBottom + "px," + clipLeft + "px)"; clientDiv.style.left = (-left + leftWidth + editorPad.left) + "px"; clientDiv.style.top = (-top + editorPad.top) + "px"; clientDiv.style.width = (isWebkit ? scrollWidth : clientWidth + left) + "px"; clientDiv.style.height = (clientHeight + top) + "px"; overlayDiv = this._overlayDiv; if (overlayDiv) { overlayDiv.style.clip = clientDiv.style.clip; overlayDiv.style.left = clientDiv.style.left; overlayDiv.style.top = clientDiv.style.top; overlayDiv.style.width = clientDiv.style.width; overlayDiv.style.height = clientDiv.style.height; } }).call(this); //************************************************************************************************** function _updateRulerSize(divRuler) { if (!divRuler) { return; } var rulerHeight = clientHeight + editorPad.top + editorPad.bottom; var cells = divRuler.firstChild.rows[0].cells; for (var i = 0; i < cells.length; i++) { var div = cells[i].firstChild; var offset = lineHeight; if (div._ruler.getOverview() === "page") { offset += partialY; } div.style.top = -offset + "px"; div.style.height = (rulerHeight + offset) + "px"; div = div.nextSibling; } divRuler.style.height = rulerHeight + "px"; } //************************************************************************************************** (function _updatePage_updateRulerSize(){ _updateRulerSize(this._leftDiv); _updateRulerSize(this._rightDiv); }).call(this); //************************************************************************************************** }, _updateRuler: function (divRuler, topIndex, bottomIndex) { if (!divRuler) { return; } var cells = divRuler.firstChild.rows[0].cells; var lineHeight = this._getLineHeight(); var parentDocument = this._frameDocument; var editorPad = this._getEditorPadding(); for (var i = 0; i < cells.length; i++) { var div = cells[i].firstChild; var ruler = div._ruler, style; if (div.rulerChanged) { this._applyStyle(ruler.getStyle(), div); } var widthDiv; var child = div.firstChild; if (child) { widthDiv = child; child = child.nextSibling; } else { widthDiv = parentDocument.createElement("DIV"); widthDiv.style.visibility = "hidden"; div.appendChild(widthDiv); } var lineIndex; if (div.rulerChanged) { if (widthDiv) { lineIndex = -1; this._applyStyle(ruler.getStyle(lineIndex), widthDiv); widthDiv.innerHTML = ruler.getHTML(lineIndex); widthDiv.lineIndex = lineIndex; widthDiv.style.height = (lineHeight + editorPad.top) + "px"; } } var overview = ruler.getOverview(), lineDiv; if (overview === "page") { while (child) { lineIndex = child.lineIndex; var nextChild = child.nextSibling; if (!(topIndex <= lineIndex && lineIndex <= bottomIndex) || child.lineChanged) { div.removeChild(child); } child = nextChild; } child = div.firstChild.nextSibling; for (lineIndex=topIndex; lineIndex<=bottomIndex; lineIndex++) { if (!child || child.lineIndex > lineIndex) { lineDiv = parentDocument.createElement("DIV"); this._applyStyle(ruler.getStyle(lineIndex), lineDiv); lineDiv.innerHTML = ruler.getHTML(lineIndex); lineDiv.lineIndex = lineIndex; lineDiv.style.height = lineHeight + "px"; div.insertBefore(lineDiv, child); } if (child && child.lineIndex === lineIndex) { child = child.nextSibling; } } } else { var buttonHeight = 17; var clientHeight = this._getClientHeight (); var trackHeight = clientHeight + editorPad.top + editorPad.bottom - 2 * buttonHeight; var lineCount = this._model.getLineCount (); var divHeight = trackHeight / lineCount; if (div.rulerChanged) { var count = div.childNodes.length; while (count > 1) { div.removeChild(div.lastChild); count--; } var lines = ruler.getAnnotations (); for (var j = 0; j < lines.length; j++) { lineIndex = lines[j]; lineDiv = parentDocument.createElement("DIV"); this._applyStyle(ruler.getStyle(lineIndex), lineDiv); lineDiv.style.position = "absolute"; lineDiv.style.top = buttonHeight + lineHeight + Math.floor(lineIndex * divHeight) + "px"; lineDiv.innerHTML = ruler.getHTML(lineIndex); lineDiv.lineIndex = lineIndex; div.appendChild(lineDiv); } } else if (div._oldTrackHeight !== trackHeight) { lineDiv = div.firstChild ? div.firstChild.nextSibling : null; while (lineDiv) { lineDiv.style.top = buttonHeight + lineHeight + Math.floor(lineDiv.lineIndex * divHeight) + "px"; lineDiv = lineDiv.nextSibling; } } div._oldTrackHeight = trackHeight; } div.rulerChanged = false; div = div.nextSibling; } } };//end prototype return Editor; }());
{ "content_hash": "7d52a07814ffe3d243e42e57198f749e", "timestamp": "", "source": "github", "line_count": 4267, "max_line_length": 158, "avg_line_length": 36.29528943051324, "alnum_prop": 0.6101942249083114, "repo_name": "firebug/firebug-lite", "id": "c314b27d05b1018da1b003079df9de2c608fc5d6", "size": "155497", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "sandbox/sandbox/orion/js/editor_improved.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "420" }, { "name": "CSS", "bytes": "558654" }, { "name": "HTML", "bytes": "707847" }, { "name": "JavaScript", "bytes": "9073753" }, { "name": "PHP", "bytes": "9082" }, { "name": "Ruby", "bytes": "6070" }, { "name": "Shell", "bytes": "1287" }, { "name": "XSLT", "bytes": "2838" } ], "symlink_target": "" }
using SMSServices.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using WebApi.ErrorHelper; namespace SMSServices.Controllers { public class TeachersClassesController : ApiController { private SMSEntities entities = new SMSEntities(); // GET api/<controller> [Route("api/TeachersClasses/All/{TeacherID}")] //public IEnumerable<TeachersClasses> Get() public HttpResponseMessage Get(int TeacherID) { entities.Configuration.ProxyCreationEnabled = false; var query = entities.TeachersClasses//.Include("Classes").Include("Shifts"); //query.Include("Sections") .Where(t => t.TeacherID == TeacherID) .Select(e => new { e.TeacherClassID, e.TeacherID, Id = e.TeacherID, Name = e.Teachers.Name, NameAr = e.Teachers.Name, e.ClassID, ClassCode = e.Classes.Code, ClassName = e.Classes.Name, ClassNameAr = e.Classes.NameAr }); //return query.ToList(); //entities.TeachersClasses.Include("Classes").Include("Shifts").Include("Sections"); return this.Request.CreateResponse(HttpStatusCode.OK, query.ToList()); } [Route("api/TeachersClasses/ByClassID/{ClassID}")] //public IEnumerable<TeachersClasses> Get() public HttpResponseMessage GetByClassID(int ClassID) { entities.Configuration.ProxyCreationEnabled = false; var query = entities.TeachersClasses .Where(t => t.ClassID == ClassID) .Select(e => new { e.TeacherClassID, e.TeacherID, Id = e.TeacherID, Name = e.Teachers.Name, NameAr = e.Teachers.Name, e.ClassID, ClassCode = e.Classes.Code, ClassName = e.Classes.Name, ClassNameAr = e.Classes.NameAr }); return this.Request.CreateResponse(HttpStatusCode.OK, query.ToList()); } //// GET api/<controller>/5/1/2 //[Route("api/TeachersClasses/{ShiftId}/{ClassId}/{SectionId}")] //public TeachersClasses Get(int ShiftId, int ClassId, int SectionId) //{ // entities.Configuration.ProxyCreationEnabled = false; // TeachersClasses TeacherClass = entities.TeachersClasses // .Where(t => t.ShiftID == ShiftId && t.ClassID == ClassId && t.SectionID == SectionId).FirstOrDefault(); // if (TeacherClass == null) // { // TeacherClass = new TeachersClasses() { ClassID = 0 }; // } // return TeacherClass; //} //[Route("api/TeachersClassesById/{id}")] //public TeachersClasses Get(int id) //{ // entities.Configuration.ProxyCreationEnabled = false; // return entities.TeachersClasses.Where(t => t.TeacherClassID == id).FirstOrDefault(); //} // POST api/<controller> [Route("api/TeachersClasses/{TeacherID}/{ClassIDs}")] public HttpResponseMessage Post(int TeacherID, string ClassIDs) { try { foreach (string ID in ClassIDs.Split(',')) { entities.TeachersClasses.Add(new TeachersClasses() { TeacherID = TeacherID, ClassID = Convert.ToInt32(ID) }); } entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, "Done ..."); } //catch (Exception e) //{ // return Request.CreateResponse(HttpStatusCode.BadRequest, "I have some issue ..."); //} catch (DbUpdateException dbEx) { throw dbEx; //return Request.CreateResponse(HttpStatusCode.BadRequest, "I have more issue ..."); //StringBuilder sb = new StringBuilder(); //foreach (var item in dbEx.EntityValidationErrors) //{ // sb.Append(item + " errors: "); // foreach (var i in item.ValidationErrors) // { // sb.Append(i.PropertyName + " : " + i.ErrorMessage); // } // sb.Append(Environment.NewLine); //} ////throw new ApiDataException(GetErrorCode(dbEx), sb.ToString(), HttpStatusCode.BadRequest); //throw new ApiDataException(1021, "too many errors ...", HttpStatusCode.BadRequest); //return Request.CreateResponse(HttpStatusCode.OK, sb.ToString()); } //catch (DbUpdateException ex) //{ // throw ex; // //return Request.CreateResponse(HttpStatusCode.BadRequest, ex); //} } //public HttpResponseMessage Post(TeachersClasses teacher) //{ // try // { // entities.TeachersClasses.Add(new TeachersClasses() // { // TeacherID = teacher.TeacherID, // ClassID = teacher.ClassID // }); // entities.SaveChanges(); // return Request.CreateResponse(HttpStatusCode.OK, "Done ..."); // } // //catch (Exception e) // //{ // // return Request.CreateResponse(HttpStatusCode.BadRequest, "I have some issue ..."); // //} // catch (DbUpdateException dbEx) // { // throw dbEx; // //return Request.CreateResponse(HttpStatusCode.BadRequest, "I have more issue ..."); // //StringBuilder sb = new StringBuilder(); // //foreach (var item in dbEx.EntityValidationErrors) // //{ // // sb.Append(item + " errors: "); // // foreach (var i in item.ValidationErrors) // // { // // sb.Append(i.PropertyName + " : " + i.ErrorMessage); // // } // // sb.Append(Environment.NewLine); // //} // ////throw new ApiDataException(GetErrorCode(dbEx), sb.ToString(), HttpStatusCode.BadRequest); // //throw new ApiDataException(1021, "too many errors ...", HttpStatusCode.BadRequest); // //return Request.CreateResponse(HttpStatusCode.OK, sb.ToString()); // } // //catch (DbUpdateException ex) // //{ // // throw ex; // // //return Request.CreateResponse(HttpStatusCode.BadRequest, ex); // //} //} private int GetErrorCode(DbEntityValidationException dbEx) { int ErrorCode = (int)HttpStatusCode.BadRequest; if (dbEx.InnerException != null && dbEx.InnerException.InnerException != null) { if (dbEx.InnerException.InnerException is SqlException) { ErrorCode = (dbEx.InnerException.InnerException as SqlException).Number; } } return ErrorCode; } // PUT api/<controller>/5 public void Put(TeachersClasses TeacherClass) { try { var entity = entities.TeachersClasses.Find(TeacherClass.TeacherClassID); if (entity != null) { entities.Entry(entity).CurrentValues.SetValues(TeacherClass); entities.SaveChanges(); } } catch //(DbUpdateException) { throw; } } /* // DELETE api/<controller>/5 public void Delete(int id) { try { var teacher = new TeachersClasses { TeacherID = id }; if (teacher != null) { entities.Entry(teacher).State = EntityState.Deleted; entities.TeachersClasses.Remove(teacher); entities.SaveChanges(); } } catch (Exception) { throw; } } */ [HttpPost] [Route("api/RemoveTeacherClass/{id}")] public HttpResponseMessage RemoveTeacherClass(int id) { try { var TeacherClass = new TeachersClasses { TeacherClassID = id }; if (TeacherClass != null) { entities.Entry(TeacherClass).State = EntityState.Deleted; entities.TeachersClasses.Remove(TeacherClass); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, "Removed..."); } else return Request.CreateResponse(HttpStatusCode.NotFound, "not found..."); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest, ex); //return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message + // " inner ex: " + ex.InnerException !=null ? ex.InnerException.Message : "null" ); //throw; } } protected override void Dispose(bool disposing) { if (disposing) { entities.Dispose(); } base.Dispose(disposing); } } }
{ "content_hash": "0eca96ff7771c4ff9603e18ed010f747", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 121, "avg_line_length": 36.803636363636365, "alnum_prop": 0.5028159272799131, "repo_name": "zraees/sms-project", "id": "5f57a639814b0593bfb2eb7e446d51134289f77a", "size": "10123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SMSServices/SMSServices/Controllers/TeachersClassesController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "315" }, { "name": "C#", "bytes": "316292" }, { "name": "CSS", "bytes": "17386" }, { "name": "HTML", "bytes": "582045" }, { "name": "JavaScript", "bytes": "1853537" }, { "name": "PowerShell", "bytes": "101111" } ], "symlink_target": "" }
package com.base; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringOauth2ClientApplication.class) @WebAppConfiguration public class SpringOauth2ClientApplicationTests { @Test public void contextLoads() { } }
{ "content_hash": "c660747cab7a66f0c05fe9605fe81944", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 78, "avg_line_length": 25.9, "alnum_prop": 0.8455598455598455, "repo_name": "h819/spring-boot", "id": "edac46e950e2de1d29aea3a626d71e1500a4f990", "size": "518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-security-oauth/spring-security-oauth2-client/src/test/java/com/base/SpringOauth2ClientApplicationTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "35139903" } ], "symlink_target": "" }
'use strict'; var global = require('../internals/global'); var isArray = require('../internals/is-array'); var lengthOfArrayLike = require('../internals/length-of-array-like'); var bind = require('../internals/function-bind-context'); var TypeError = global.TypeError; // `FlattenIntoArray` abstract operation // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) { var targetIndex = start; var sourceIndex = 0; var mapFn = mapper ? bind(mapper, thisArg) : false; var element, elementLen; while (sourceIndex < sourceLen) { if (sourceIndex in source) { element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; if (depth > 0 && isArray(element)) { elementLen = lengthOfArrayLike(element); targetIndex = flattenIntoArray(target, original, element, elementLen, targetIndex, depth - 1) - 1; } else { if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError('Exceed the acceptable array length'); target[targetIndex] = element; } targetIndex++; } sourceIndex++; } return targetIndex; }; module.exports = flattenIntoArray;
{ "content_hash": "cdfcfdc6da4475be3c7c88939ab18069", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 106, "avg_line_length": 34.77777777777778, "alnum_prop": 0.6908945686900958, "repo_name": "thomasoboyle/Exercism", "id": "dd61434b1b5b07b837496823e1c5d003e67570a2", "size": "1252", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "typescript/hello-world/node_modules/core-js/internals/flatten-into-array.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "781" }, { "name": "Ruby", "bytes": "96197" }, { "name": "TypeScript", "bytes": "218" } ], "symlink_target": "" }
'use strict'; /** * @class * Initializes a new instance of the SummaryProperties class. * @constructor * Base for all summaries. * * @member {date} startTime Summary interval start time. * * @member {date} endTime Summary interval end time. * */ class SummaryProperties { constructor() { } /** * Defines the metadata of SummaryProperties * * @returns {object} metadata of SummaryProperties * */ mapper() { return { required: false, serializedName: 'SummaryProperties', type: { name: 'Composite', className: 'SummaryProperties', modelProperties: { startTime: { required: true, serializedName: 'startTime', type: { name: 'DateTime' } }, endTime: { required: true, serializedName: 'endTime', type: { name: 'DateTime' } } } } }; } } module.exports = SummaryProperties;
{ "content_hash": "566984073fa10ec2652a3c35b87a6d77", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 61, "avg_line_length": 19.12962962962963, "alnum_prop": 0.5285575992255567, "repo_name": "AuxMon/azure-sdk-for-node", "id": "4bf4335bcefac7de8d74edc6356386ea2c165fb0", "size": "1350", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/services/serviceMapManagement/lib/models/summaryProperties.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "661" }, { "name": "JavaScript", "bytes": "48689677" }, { "name": "Shell", "bytes": "437" } ], "symlink_target": "" }
class Room attr_accessor :name, :description, :paths def initialize(name, description) @name = name @description = description @paths = {} end def go(direction) @paths[direction] end def add_paths(paths) @paths.update(paths) end end central_corridor = Room.new("Central Corridor", %q{ The Gothons of Planet Percal #25 have invaded your ship and destroyed your entire crew. You are the last surviving member and your last mission is to get the neutron destruct bomb from the Weapons Armory, put it in the bridge, and blow the ship up after getting into an escape pod. You're running down the central corridor to the Weapons Armory when a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume flowing around his hate filled body. He's blocking the door to the Armory and about to pull a weapon to blast you. }) laser_weapon_armory = Room.new("Laser Weapon Armory", %q{ Lucky for you they made you learn Gothon insults in the academy. You tell the one Gothon joke you know: Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr. The Gothon stops, tries not to laugh, then busts out laughing and can't move. While he's laughing you run up and shoot him square in the head putting him down, then jump through the Weapon Armory door. You do a dive roll into the Weapon Armory, crouch and scan the room for more Gothons that might be hiding. It's dead quiet, too quiet. You stand up and run to the far side of the room and find the neutron bomb in its container. There's a keypad lock on the box and you need the code to get the bomb out. If you get the code wrong 10 times then the lock closes forever and you can't get the bomb. The code is 3 digits. }) the_bridge = Room.new("The Bridge", %q{ The container clicks open and the seal breaks, letting gas out. You grab the neutron bomb and run as fast as you can to the bridge where you must place it in the right spot. You burst onto the Bridge with the neutron destruct bomb under your arm and surprise 5 Gothons who are trying to take control of the ship. Each of them has an even uglier clown costume than the last. They haven't pulled their weapons out yet, as they see the active bomb under your arm and don't want to set it off. }) escape_pod = Room.new("Escape Pod", %q{ You point your blaster at the bomb under your arm and the Gothons put their hands up and start to sweat. You inch backward to the door, open it, and then carefully place the bomb on the floor, pointing your blaster at it. You then jump back through the door, punch the close button and blast the lock so the Gothons can't get out. Now that the bomb is placed you run to the escape pod to get off this tin can. You rush through the ship desperately trying to make it to the escape pod before the whole ship explodes. It seems like hardly any Gothons are on the ship, so your run is clear of interference. You get to the chamber with the escape pods, and now need to pick one to take. Some of them could be damaged but you don't have time to look. There's 5 pods, which one do you take? }) the_end_winner = Room.new("The End", %q{ You jump into pod 2 and hit the eject button. The pod easily slides out into space heading to the planet below. As it flies to the planet, you look back and see your ship implode then explode like a bright star, taking out the Gothon ship at the same time. You won! }) the_end_loser = Room.new("The End", %q{ You jump into a random pod and hit the eject button. The pod escapes out into the void of space, then implodes as the hull ruptures, crushing your body into jam jelly. }) escape_pod.add_paths({ '2' => the_end_winner, '*' => the_end_loser }) central_corridor_shoot = Room.new("Death", %q{ Quick on the draw you yank out your blaster and fire it at the Gothon. His clown costume is flowing and moving around his body, which throws off your aim. Your laser hits his costume but misses him entirely. This completely ruins his brand new costume his mother bought him, which makes him fly into an insane rage and blast you repeatedly in the face unitl you are dead. Then he eats you. }) central_corridor_dodge = Room.new("Death", %q{ Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out. You wake up shortly after only to die as the Gothon stomps on your head and eats you. }) the_bridge_bomb = Room.new("Death", %q{ In a panic you throw the bomb at the group of Gothons and make a leap for the door. Right as you drop it a Gothon shoots you right in hte back killing you. As you die you see another Gothon frantically tyr to disarm the bomb. You die knowing they will probably blow up when it goes off. }) laser_weapon_armory_fail = Room.new("Death", %q{ The lock buzzes one last time and then you hear a sickening melting sound as the mechanism is fused together. You decide to sit there, and finally the Gothons blow up the ship from their ship and you die. }) the_bridge.add_paths({ 'throw the bomb' => the_bridge_bomb, 'slowly place the bomb' => escape_pod }) laser_weapon_armory.add_paths({ '0132' => the_bridge, '*' => laser_weapon_armory_fail }) central_corridor.add_paths({ 'shoot!' => central_corridor_shoot, 'dodge!' => central_corridor_dodge, 'tell a joke' => laser_weapon_armory }) START = central_corridor ROOMS = { "central_corridor" => central_corridor, "central_corridor_shoot" => central_corridor_shoot, "central_corridor_dodge" => central_corridor_dodge, "laser_weapon_armory" => laser_weapon_armory, "laser_weapon_armory_fail" => laser_weapon_armory_fail, "the_bridge" => the_bridge, "the_bridge_bomb" => the_bridge_bomb, "escape_pod" => escape_pod, "the_end_winner" => the_end_winner, "the_end_loser" => the_end_loser }
{ "content_hash": "79bdf1f5afb031f0b6f0d47bc5dbb008", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 82, "avg_line_length": 35.72941176470588, "alnum_prop": 0.724399078037537, "repo_name": "j0rgy/gothonweb", "id": "0a5521729c53f049e097cae019927020d7ab463a", "size": "6074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/map.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "11917" } ], "symlink_target": "" }
<?php class Phoenix_Moneybookers_Model_Wlt extends Phoenix_Moneybookers_Model_Abstract { /** * unique internal payment method identifier */ protected $_code = 'moneybookers_wlt'; protected $_paymentMethod = 'WLT'; protected $_hidelogin = '0'; }
{ "content_hash": "19afa0b93f8c33c9e955ee17f6a0c281", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 80, "avg_line_length": 25, "alnum_prop": 0.6654545454545454, "repo_name": "melvyn-sopacua/magedepot", "id": "0e92adeb7b83fbf465192c9e3c7635409d19be86", "size": "1014", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "magento/app/code/community/Phoenix/Moneybookers/Model/Wlt.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "25548654" }, { "name": "Shell", "bytes": "642" } ], "symlink_target": "" }
export PATH="/Users/Shared/Jenkins/.nvm/v0.8.18/bin:$PATH" export JAVA_HOME="`/usr/libexec/java_home`" source /Users/Shared/Jenkins/.nvm/nvm.sh nvm use 0.8.18 rm -rf node_modules npm install grunt package
{ "content_hash": "792892572650ef6c205fc0b37b95ab36", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 58, "avg_line_length": 29.142857142857142, "alnum_prop": 0.7549019607843137, "repo_name": "apache/devicemap-browsermap", "id": "499ca3bccd846c71b6899d325bb5ce38e918a094", "size": "1081", "binary": false, "copies": "3", "ref": "refs/heads/trunk", "path": "ci/jenkins_build.sh", "mode": "33261", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.devgateway.toolkit.persistence.mongo.dao; public final class DBConstants { private DBConstants() { } public static final int MAX_DEFAULT_TEXT_LENGTH = 32000; public static final int STD_DEFAULT_TEXT_LENGTH = 255; public static final int MAX_DEFAULT_TEXT_LENGTH_ONE_LINE = 3000; public static final int MAX_DEFAULT_TEXT_AREA = 10000; }
{ "content_hash": "77607d8f70480664f32a89eeea98aba7", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 68, "avg_line_length": 28.846153846153847, "alnum_prop": 0.728, "repo_name": "devgateway/dg-toolkit", "id": "48cd8645ebdea6941d779abfcc321986585b52eb", "size": "905", "binary": false, "copies": "1", "ref": "refs/heads/dgtkit-4.x", "path": "persistence-mongodb/src/main/java/org/devgateway/toolkit/persistence/mongo/dao/DBConstants.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5623" }, { "name": "Dockerfile", "bytes": "1248" }, { "name": "HTML", "bytes": "34332" }, { "name": "Java", "bytes": "888536" }, { "name": "JavaScript", "bytes": "45824" } ], "symlink_target": "" }
package com.exsoloscript.challonge.gson; import com.exsoloscript.challonge.model.Participant; import com.google.common.collect.Lists; import com.google.gson.*; import java.lang.reflect.Type; import java.util.List; public class ParticipantListAdapter implements GsonAdapter, JsonDeserializer<List<Participant>> { private final Gson gson; ParticipantListAdapter() { this.gson = new GsonBuilder() .registerTypeAdapter(Participant.class, new ParticipantAdapter()) .create(); } @Override public List<Participant> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { if (jsonElement.isJsonArray()) { JsonArray array = jsonElement.getAsJsonArray(); List<Participant> participants = Lists.newArrayList(); for (JsonElement arrayElement : array) { participants.add(this.gson.fromJson(arrayElement, Participant.class)); } return participants; } return null; } }
{ "content_hash": "624b834545ee086273535d1c1019bb47", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 159, "avg_line_length": 29.83783783783784, "alnum_prop": 0.6865942028985508, "repo_name": "EXSolo/challonge-java", "id": "7b88bab1e45a62900f88ee4e64ffb990d04f223b", "size": "1728", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/exsoloscript/challonge/gson/ParticipantListAdapter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "180000" } ], "symlink_target": "" }
package org.onosproject.cfm.web; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.onlab.packet.Ip4Address; import org.onlab.packet.Ip6Address; import org.onlab.packet.IpAddress; import org.onosproject.codec.CodecContext; import org.onosproject.codec.JsonCodec; import org.onosproject.incubator.net.l2monitoring.cfm.Mep; import org.onosproject.incubator.net.l2monitoring.cfm.Mep.FngAddress; import java.util.Locale; import static com.google.common.base.Preconditions.checkNotNull; import static org.onlab.util.Tools.nullIsIllegal; /** * Encode and decode to/from JSON to FngAddress object. */ public class FngAddressCodec extends JsonCodec<FngAddress> { /** * Encodes the FngAddress entity into JSON. * * @param fngAddress FngAddress to encode * @param context encoding context * @return JSON node * @throws java.lang.UnsupportedOperationException if the codec does not * support encode operations */ @Override public ObjectNode encode(FngAddress fngAddress, CodecContext context) { checkNotNull(fngAddress, "FngAddress cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put("address-type", fngAddress.addressType().name()); if (fngAddress.addressType().equals(Mep.FngAddressType.IPV4) || fngAddress.addressType().equals(Mep.FngAddressType.IPV6)) { result.put("ip-address", fngAddress.ipAddress().toString()); } return result; } /** * Decodes the FngAddress entity from JSON. * * @param json JSON to decode * @param context decoding context * @return decoded FngAddress * @throws java.lang.UnsupportedOperationException if the codec does not * support decode operations */ @Override public FngAddress decode(ObjectNode json, CodecContext context) { if (json == null || !json.isObject()) { return null; } JsonNode node = json.get("fng-address"); String addressType = nullIsIllegal(node.get("address-type"), "address type is required").asText(); Mep.FngAddressType type = Mep.FngAddressType.valueOf(addressType.toUpperCase(Locale.ENGLISH)); JsonNode ipAddressNode = node.get("ipAddress"); switch (type) { case IPV4: return FngAddress.ipV4Address(Ip4Address.valueOf(ipAddressNode.asText())); case IPV6: return FngAddress.ipV6Address(Ip6Address.valueOf(ipAddressNode.asText())); case NOT_TRANSMITTED: return FngAddress.notTransmitted(IpAddress.valueOf(ipAddressNode.asText())); case NOT_SPECIFIED: default: return FngAddress.notSpecified(); } } }
{ "content_hash": "8ab39e0828fdc94b65e6f13eb3176c6d", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 102, "avg_line_length": 36.65432098765432, "alnum_prop": 0.6503873358033008, "repo_name": "kuujo/onos", "id": "1c0e725a0b5839a19954e6c2174ee9b63b37f1fc", "size": "3586", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "apps/cfm/nbi/src/main/java/org/onosproject/cfm/web/FngAddressCodec.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "345080" }, { "name": "Dockerfile", "bytes": "2131" }, { "name": "HTML", "bytes": "287821" }, { "name": "Java", "bytes": "44005752" }, { "name": "JavaScript", "bytes": "4021615" }, { "name": "Makefile", "bytes": "1472" }, { "name": "P4", "bytes": "149196" }, { "name": "Python", "bytes": "871103" }, { "name": "Ruby", "bytes": "7652" }, { "name": "Shell", "bytes": "309239" }, { "name": "TypeScript", "bytes": "710899" } ], "symlink_target": "" }
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #pragma once #ifndef NET_TCP_CONNECTION_HPP #define NET_TCP_CONNECTION_HPP #include "common.hpp" #include "packet_view.hpp" #include "read_request.hpp" #include "rttm.hpp" #include "tcp_errors.hpp" #include "write_queue.hpp" #include "sack.hpp" #include <net/socket.hpp> #include <delegate> #include <util/timer.hpp> #include <util/alloc_pmr.hpp> namespace net { // Forward declaration of the TCP object class TCP; } namespace net { namespace tcp { /* A connection between two Sockets (local and remote). Receives and handle TCP::Packet. Transist between many states. */ class Connection { friend class net::TCP; friend class Listener; public: /** Connection identifier */ using Tuple = std::pair<Socket, Socket>; /** Interface for TCP states */ class State; /** Disconnect event */ struct Disconnect; /** Reason for packet being dropped */ enum class Drop_reason; using Byte = uint8_t; using WriteBuffer = Write_queue::WriteBuffer; public: /** Called with the connection itself when it's been established. May be a nullptr if the connection failed. */ using ConnectCallback = delegate<void(Connection_ptr self)>; /** * @brief Event when a connection has been established. * This event lets you know when to start using the connection, * and should always be assigned. * NOTE: The Connection_ptr will be a nullptr when an outgoing connection failed. * * @param[in] callback The callback * * @return This connection */ inline Connection& on_connect(ConnectCallback callback); /** Called with a shared buffer and the length of the data when received. */ using ReadCallback = delegate<void(buffer_t)>; /** * @brief Event when incoming data is received by the connection. * The recv_bufsz determines the size of the receive buffer. * The callback is called when either 1) PSH is seen, or 2) the buffer is full * * @param[in] recv_bufsz The size of the receive buffer * @param[in] callback The callback * * @return This connection */ inline Connection& on_read(size_t recv_bufsz, ReadCallback callback); using DataCallback = delegate<void()>; /** * @brief Event when incoming data is received by the connection. * The callback is called when either 1) PSH is seen, or 2) the buffer is full * * The user is expected to fetch data by calling read_next, otherwise the * event will be triggered again. Unread data will be buffered as long as * there is capacity in the read queue. * If an on_read callback is also registered, this event has no effect. * * @param[in] callback The callback * * @return This connection */ inline Connection& on_data(DataCallback callback); /** * @brief Read the next fully acked chunk of received data if any. * * @return Pointer to buffer if any, otherwise nullptr. */ inline buffer_t read_next(); /** * @return The size of the next fully acked chunk of received data. */ inline size_t next_size(); /** Called with the connection itself and the reason wrapped in a Disconnect struct. */ using DisconnectCallback = delegate<void(Connection_ptr self, Disconnect)>; /** * @brief Event when a connection is being disconnected. * This is when either 1) The peer has sent a FIN, indicating it wants to close, * or 2) A RST is received telling the connection to reset * * @note The default is to close the connection from our end as well. * Remember to ::close() the connection inside this event (if that's what you want to do) * * @param[in] callback The callback * * @return This connection */ inline Connection& on_disconnect(DisconnectCallback callback); /** Called with nothing ¯\_(ツ)_/¯ */ using CloseCallback = delegate<void()>; /** * @brief Event when a connection is closing down. * After this event has been called, the connection is useless. * This is useful for cleaning up copies of the connection, * and is more important than disconnect. * * @param[in] callback The callback * * @return This connection */ inline Connection& on_close(CloseCallback callback); /** Called with the number of bytes written. */ using WriteCallback = delegate<void(size_t)>; /** * @brief Event when a connection has finished sending a write request. * This event does not tell if the data has been received by the peer, * only that it has been transmitted. * This can also be called with the amount written by the current request * if a connection is aborted/closed with a non-empty queue. * * @param[in] callback The callback * * @return This connection */ inline Connection& on_write(WriteCallback callback); /** Called with the packet that got dropped and the reason why. */ using PacketDroppedCallback = delegate<void(const Packet&, Drop_reason)>; /** * @brief Only change the on_read callback without touching the buffer. * Only useful in special cases. Assumes on_read has been called. * * @param[in] callback The callback * * @return This connection */ inline Connection& set_on_read_callback(ReadCallback callback); /** * @brief Async write of a shared buffer with a length. * Avoids any copy of the data into the internal buffer. * * @param[in] buffer shared buffer * @param[in] n length */ void write(buffer_t buffer); /** * @brief Async write of a data with a length. * Copies data into an internal (shared) buffer. * * @param[in] buf data * @param[in] n length */ inline void write(const void* buf, size_t n); /** * @brief Async write of a string. * Calls write(const void* buf, size_t n) * * @param[in] str The string */ inline void write(const std::string& str); /** * @brief Async close of the connection, sending FIN. */ void close(); /** * @brief Aborts the connection immediately, sending RST. */ inline void abort(); /** * @brief Reason for disconnect event. */ struct Disconnect { public: enum Reason { CLOSING, REFUSED, RESET }; Reason reason; explicit Disconnect(Reason reason) : reason(reason) {} operator Reason() const noexcept { return reason; } operator std::string() const noexcept { return to_string(); } bool operator ==(const Disconnect& dc) const { return reason == dc.reason; } std::string to_string() const noexcept { switch(reason) { case CLOSING: return "Connection closing"; case REFUSED: return "Connection refused"; case RESET: return "Connection reset"; default: return "Unknown reason"; } // < switch(reason) } }; // < struct Connection::Disconnect /** * Reason for packet being dropped. */ enum class Drop_reason { NA, // N/A SEQ_OUT_OF_ORDER, ACK_NOT_SET, ACK_OUT_OF_ORDER, RCV_WND_ZERO, RST }; // < Drop_reason /** * @brief Represent the Connection as a string (STATUS). * Local:Port Remote:Port (STATE) * * @return String representation of the object. */ std::string to_string() const noexcept { return {local().to_string() + " " + remote_.to_string() + " (" + state_->to_string() + ")"}; } /** * @brief Returns the current state of the connection. * * @return The current state */ const Connection::State& state() const noexcept { return *state_; } /** * @brief Returns the previous state of the connection. * * @return The previous state */ const Connection::State& prev_state() const noexcept { return *prev_state_; } /** * @brief Total number of bytes in read buffer * * @return bytes not yet read */ size_t readq_size() const { return (read_request) ? read_request->size() : 0; } /** * @brief Total number of bytes in send queue * * @return total bytes in send queue */ uint32_t sendq_size() const noexcept { return writeq.bytes_total(); } /** * @brief Total number of bytes not yet sent * * @return bytes not yet sent */ uint32_t sendq_remaining() const noexcept { return writeq.bytes_remaining(); } /** * @brief Determines ability to send. * Is the usable window large enough, and is there data to send. * * @return True if able to send, False otherwise. */ bool can_send() const noexcept { return (usable_window() >= SMSS()) and writeq.has_remaining_requests(); } /** * @brief Return the "tuple" (id) of the connection. * This is not a real tuple since the ip of the local socket * is decided by the network stack. * * @return A "tuple" of [[local port], [remote ip, remote port]] */ Connection::Tuple tuple() const noexcept { return {local_, remote_}; } /// --- State checks --- /// /** * @brief Determines if listening. * * @return True if listening, False otherwise. */ bool is_listening() const noexcept; /** * @brief Determines if connected (established). * * @return True if connected, False otherwise. */ bool is_connected() const noexcept { return state_->is_connected(); } /** * @brief Determines if writable. (write is allowed) * * @return True if writable, False otherwise. */ bool is_writable() const noexcept { return state_->is_writable(); } /** * @brief Determines if readable. (data can be received) * * @return True if readable, False otherwise. */ bool is_readable() const noexcept { return state_->is_readable(); } /** * @brief Determines if closing. * * @return True if closing, False otherwise. */ bool is_closing() const noexcept { return state_->is_closing(); } /** * @brief Determines if closed. * * @return True if closed, False otherwise. */ bool is_closed() const noexcept { return state_->is_closed(); }; /** * @brief Determines if the TCP has the Connection in its write queue * * @return True if queued, False otherwise. */ bool is_queued() const noexcept { return queued_; } /** * @brief Helper function for state checks. * * @param[in] state The state to be checked for * * @return True if state, False otherwise. */ bool is_state(const State& state) const noexcept { return state_ == &state; } /** * @brief Helper function for state checks. * * @param[in] state_str The state string to be checked for * * @return True if state, False otherwise. */ bool is_state(const std::string& state_str) const noexcept { return state_->to_string() == state_str; } /** * @brief The "hosting" TCP instance. The TCP object that the Connection is handled by. * * @return A TCP object */ TCP& host() noexcept { return host_; } /** * @brief The local port bound to this connection. * * @return A 16 bit unsigned port number */ port_t local_port() const noexcept { return local_.port(); } /** * @brief The local Socket bound to this connection. * * @return A TCP Socket */ const Socket& local() const noexcept { return local_; } /** * @brief The remote Socket bound to this connection. * * @return A TCP Socket */ const Socket& remote() const noexcept { return remote_; } Protocol ipv() const noexcept { return is_ipv6_ ? Protocol::IPv6 : Protocol::IPv4; } auto bytes_sacked() const noexcept { return bytes_sacked_; } /** * @brief Interface for one of the many states a Connection can have. * Based on RFC 793 */ class State { public: enum Result { CLOSED = -1, // This inditactes that a Connection is done and should be closed. OK = 0, // Keep on processing }; /** Open a Connection [OPEN] */ virtual void open(Connection&, bool active = false); /** Write to a Connection [SEND] */ virtual size_t send(Connection&, WriteBuffer&); /** Close a Connection [CLOSE] */ virtual void close(Connection&); /** Terminate a Connection [ABORT] */ virtual void abort(Connection&); /** Handle a Packet [SEGMENT ARRIVES] */ virtual Result handle(Connection&, Packet_view& in) = 0; /** The current state represented as a string [STATUS] */ virtual std::string to_string() const = 0; virtual bool is_connected() const { return false; } virtual bool is_writable() const { return false; } virtual bool is_readable() const { return false; } virtual bool is_closing() const { return false; } virtual bool is_closed() const { return false; } protected: /* Helper functions TODO: Clean up names. */ virtual bool check_seq(Connection&, Packet_view&); virtual void unallowed_syn_reset_connection(Connection&, const Packet_view&); virtual bool check_ack(Connection&, const Packet_view&); virtual void process_fin(Connection&, const Packet_view&); virtual void send_reset(Connection&); }; // < class Connection::State // Forward declaration of concrete states. // Definition in "tcp_connection_states.hpp" class Closed; class Listen; class SynSent; class SynReceived; class Established; class FinWait1; class FinWait2; class CloseWait; class Closing; class LastAck; class TimeWait; /** * @brief Transmission Control Block. * Keep tracks of all the data for a connection. RFC 793: Page 19 Among the variables stored in the TCB are the local and remote socket numbers, the security and precedence of the connection, pointers to the user's send and receive buffers, pointers to the retransmit queue and to the current segment. In addition several variables relating to the send and receive sequence numbers are stored in the TCB. */ struct TCB { /* Send Sequence Variables */ struct { seq_t UNA; // send unacknowledged seq_t NXT; // send next uint32_t WND; // send window uint16_t UP; // send urgent pointer seq_t WL1; // segment sequence number used for last window update seq_t WL2; // segment acknowledgment number used for last window update uint16_t MSS; // Maximum segment size for outgoing segments. uint8_t wind_shift; // WS factor bool TS_OK; // Use timestamp option } SND; // << seq_t ISS; // initial send sequence number /* Receive Sequence Variables */ struct { seq_t NXT; // receive next uint32_t WND; // receive window uint16_t UP; // receive urgent pointer uint16_t rwnd; // receivers advertised window [RFC 5681] uint8_t wind_shift; // WS factor } RCV; // << seq_t IRS; // initial receive sequence number uint32_t ssthresh; // slow start threshold [RFC 5681] uint32_t cwnd; // Congestion window [RFC 5681] seq_t recover; // New Reno [RFC 6582] uint32_t TS_recent; // Recent timestamp received from user [RFC 7323] TCB(const uint16_t mss, const uint32_t recvwin); TCB(const uint16_t mss); void init() { ISS = Connection::generate_iss(); recover = ISS; // [RFC 6582] } uint32_t get_ts_recent() const noexcept { return TS_recent; } bool slow_start() const noexcept { return cwnd < ssthresh; } std::string to_string() const; }__attribute__((packed)); // < struct Connection::TCB /** * @brief Creates a connection with a remote end point * * @param host The TCP host * @param[in] local_port The local port * @param[in] remote The remote socket * @param[in] callback The connection callback */ Connection(TCP& host, Socket local, Socket remote, ConnectCallback callback = nullptr); ~Connection(); Connection(const Connection&) = delete; Connection(Connection&&) = delete; Connection& operator=(const Connection&) = delete; Connection& operator=(Connection&&) = delete; /** * @brief Open the connection. * Active determines whether the connection is active or passive. * May throw if no remote host, or state isnt valid for opening. * * @param[in] active Whether its an active (outgoing) or passive (listening) */ void open(bool active = false); /** * @brief Set remote Socket bound to this connection. * * @param[in] remote The remote socket */ void set_remote(Socket remote) { remote_ = remote; } // ??? void deserialize_from(void*); int serialize_to(void*) const; static const int VERSION = 2; /** * @brief Reset all callbacks back to default */ void reset_callbacks(); using Recv_window_getter = delegate<uint32_t()>; void set_recv_wnd_getter(Recv_window_getter func) { recv_wnd_getter = func; } void release_memory() { read_request = nullptr; bufalloc.reset(); } private: /** "Parent" for Connection. */ TCP& host_; /* End points. */ Socket local_; Socket remote_; const bool is_ipv6_ = false; /** The current state the Connection is in. Handles most of the logic. */ State* state_; // Previous state. Used to keep track of state transitions. State* prev_state_; /** Keep tracks of all sequence variables. */ TCB cb; /** The given read request */ std::unique_ptr<Read_request> read_request; os::mem::Pmr_pool::Resource_ptr bufalloc{nullptr}; /** Queue for write requests to process */ Write_queue writeq; /** Round Trip Time Measurer */ RTTM rttm; /** Callbacks */ ConnectCallback on_connect_; DisconnectCallback on_disconnect_; CloseCallback on_close_; /** Retransmission timer */ Timer rtx_timer; /** Time Wait / DACK timeout timer */ Timer timewait_dack_timer; Recv_window_getter recv_wnd_getter; bool close_signaled_ = false; /** Number of retransmission attempts on the packet first in RT-queue */ int8_t rtx_attempt_ = 0; /** number of retransmitted SYN packets. */ int8_t syn_rtx_ = 0; /** State if connection is in TCP write queue or not. */ bool queued_; using Sack_list = sack::List<sack::Fixed_list<default_sack_entries>>; std::unique_ptr<Sack_list> sack_list; /** If SACK is permitted (option has been seen from peer) */ bool sack_perm = false; size_t bytes_sacked_ = 0; /** Congestion control */ // is fast recovery state bool fast_recovery_ = false; // First partial ack seen bool reno_fpack_seen = false; /** limited transmit [RFC 3042] active */ bool limited_tx_ = true; // Number of current duplicate ACKs. Is reset for every new ACK. uint16_t dup_acks_ = 0; seq_t highest_ack_ = 0; seq_t prev_highest_ack_ = 0; uint32_t last_acked_ts_ = 0; /** Delayed ACK - number of seg received without ACKing */ uint8_t dack_{0}; seq_t last_ack_sent_; /** * The size of the largest segment that the sender can transmit * Updated by the Path MTU Discovery process (RFC 1191) */ uint16_t smss_; /** RFC 3522 - The Eifel Detection Algorithm for TCP */ //int16_t spurious_recovery = 0; //static constexpr int8_t SPUR_TO {1}; //uint32_t rtx_ts_ = 0; /** RFC 4015 - The Eifel Response Algorithm for TCP */ //uint32_t pipe_prev = 0; //static constexpr int8_t LATE_SPUR_TO {1}; //RTTM::seconds SRTT_prev{1.0f}; //RTTM::seconds RTTVAR_prev{1.0f}; /** * @brief Set the Read_request * * @param[in] recv_bufsz The receive bufsz * @param[in] cb The read callback */ void _on_read(size_t recv_bufsz, ReadCallback cb); /** * @brief Set the on_data handler * * @param[in] cb The callback */ void _on_data(DataCallback cb); // Retrieve the associated shared_ptr for a connection, if it exists // Throws out_of_range if it doesn't Connection_ptr retrieve_shared(); /// --- CALLBACKS --- /// /** * @brief Cleanup callback * @details This is called to make sure TCP/Listener doesn't hold any shared ptr of * the given connection. This is only for internal use, and not visible for the user. * * @param Connection to be cleaned up */ using CleanupCallback = delegate<void(const Connection* self)>; CleanupCallback _on_cleanup_; inline Connection& _on_cleanup(CleanupCallback cb); void default_on_disconnect(Connection_ptr, Disconnect); /// --- READING --- /// /* Receive data into the current read requests buffer. */ size_t receive(seq_t seq, const uint8_t* data, size_t n, bool PUSH); /* Remote is closing, no more data will be received. Returns receive buffer to user. */ void receive_disconnect(); /// --- WRITING --- /// /* Process the write queue with the given amount of packets. Called by TCP. */ void offer(size_t& packets); /* Returns if the connection has a doable write job. */ bool has_doable_job() const { return writeq.has_remaining_requests() and usable_window() >= SMSS(); } /* Try to process the current write queue. */ void writeq_push(); /* Try to write (some of) queue on connected. */ void writeq_on_connect() { writeq_push(); } /* Reset queue on disconnect. Clears the queue and notice every requests callback. */ void writeq_reset(); /* Mark whether the Connection is in TCP write queue or not. */ void set_queued(bool queued) { queued_ = queued; } /** * @brief Sets the size of the largest segment that the sender can transmit * Updated through the Path MTU Discovery process (RFC 1191) when TCP * gets a notification about an updated PMTU value for this connection * Set in TCP if Path MTU Discovery is enabled * * @param[in] smss The new SMSS (The PMTU value minus the size of the IP4 header and * the size of the TCP header) */ void set_SMSS(uint16_t smss) noexcept { smss_ = smss; } /** * @brief Sends an acknowledgement. */ void send_ack(); /* Invoke/signal the diffrent TCP events. */ void signal_connect(const bool success = true); void signal_disconnect(Disconnect::Reason&& reason) { on_disconnect_(retrieve_shared(), Disconnect{reason}); } void signal_rtx_timeout() { } /* Drop a packet. Used for debug/callback. */ void drop(const Packet_view& packet, Drop_reason reason = Drop_reason::NA); // RFC 3042 void limited_tx(); /// TCB HANDLING /// /* Returns the TCB. */ Connection::TCB& tcb() { return cb; } /* Generate a new ISS. */ static seq_t generate_iss(); /* SND.UNA + SND.WND - SND.NXT SND.UNA + WINDOW - SND.NXT */ uint32_t usable_window() const noexcept { const int64_t x = (int64_t)send_window() - (int64_t)flight_size(); return (uint32_t) std::max(static_cast<int64_t>(0), x); } uint32_t send_window() const noexcept { return std::min(cb.SND.WND, cb.cwnd); } uint32_t flight_size() const noexcept { return cb.SND.NXT - cb.SND.UNA; } bool uses_window_scaling() const noexcept; bool uses_timestamps() const noexcept; bool uses_SACK() const noexcept; /// --- INCOMING / TRANSMISSION --- /// /* Receive a TCP Packet. */ void segment_arrived(Packet_view&); /* Acknowledge a packet - TCB update, Congestion control handling, RTT calculation and RT handling. */ bool handle_ack(const Packet_view&); void update_rcv_wnd() { cb.RCV.WND = (recv_wnd_getter == nullptr) ? calculate_rcv_wnd() : recv_wnd_getter(); } uint32_t calculate_rcv_wnd() const; void send_window_update() { update_rcv_wnd(); send_ack(); } void trigger_window_update(os::mem::Pmr_resource& res); /** * @brief Receive data from an incoming packet containing data. * * @param[in] in TCP Packet containing payload */ void recv_data(const Packet_view& in); void recv_out_of_order(const Packet_view& in); /** * @brief Acknowledge incoming data. This is done by: * - Trying to send data if possible (can send) * - If not, regular ACK (use DACK if enabled) */ void ack_data(); /** * @brief Determines if the incoming segment is a legit window update. * * @param[in] in TCP Segment * @param[in] win The calculated window * * @return True if window update, False otherwise. */ bool is_win_update(const Packet_view& in, const uint32_t win) const { return cb.SND.WND != win and (cb.SND.WL1 < in.seq() or (cb.SND.WL1 == in.seq() and cb.SND.WL2 <= in.ack())); } /** * @brief Determines if duplicate acknowledge, described in [RFC 5681] p.3 * * @param[in] in TCP segment * * @return True if duplicate acknowledge, False otherwise. */ bool is_dup_ack(const Packet_view& in, const uint32_t win) const { return in.ack() == cb.SND.UNA and flight_size() > 0 and !in.has_tcp_data() and cb.SND.WND == win and !in.isset(SYN) and !in.isset(FIN); } /** * @brief Handle duplicate ACK according to New Reno * * @param[in] <unnamed> Incoming TCP segment (duplicate ACK) */ void on_dup_ack(const Packet_view&); /** * @brief Handle segment according to congestion control (New Reno) * * @param[in] <unnamed> Incoming TCP segment */ void congestion_control(const Packet_view&); /** * @brief Handle segment according to fast recovery (New Reno) * * @param[in] <unnamed> Incoming TCP segment */ void fast_recovery(const Packet_view&); /** * @brief Determines ability to send ONE segment, not caring about the usable window. * * @return True if able to send one, False otherwise. */ bool can_send_one() const { return send_window() >= SMSS() and writeq.has_remaining_requests(); } /** * @brief Send as much as possible from write queue. */ void send_much() { writeq_push(); } /** * @brief Fills the packet with data, limited to SMSS * * @param packet The packet * @param[in] data The data * @param[in] n The number of bytes to fill * * @return The amount of data filled into the packet. */ size_t fill_packet(Packet_view& packet, const uint8_t* data, size_t n) { return packet.fill(data, std::min(n, (size_t)SMSS())); } /* Transmit the packet and hooks up retransmission. */ void transmit(Packet_view_ptr); /* Creates a new outgoing packet with the current TCB values and options. */ Packet_view_ptr create_outgoing_packet(); Packet_view_ptr outgoing_packet() { return create_outgoing_packet(); } uint16_t MSS() const noexcept; /** * @brief Maximum Segment Data Size * Limits the size for outgoing packets * * @return MSDS */ uint16_t MSDS() const noexcept; /// --- Congestion Control [RFC 5681] --- /// void setup_congestion_control() { reno_init(); } /** * @brief Sender Maximum Segment Size * The size of the largest segment that the sender can transmit * * @return SMSS */ uint16_t SMSS() const noexcept { return smss_; // Updated by Path MTU Discovery process } /** * @brief Receiver Maximum Segment Size * The size of the largest segment the receiver is willing to accept * * @return RMSS */ uint16_t RMSS() const noexcept { return cb.SND.MSS; } // Reno specifics // void reno_init() { reno_init_cwnd(3); reno_init_sshtresh(); } void reno_init_cwnd(const size_t segments) { cb.cwnd = segments*SMSS(); } void reno_init_sshtresh() { cb.ssthresh = cb.SND.WND; } void reno_increase_cwnd(const uint16_t n) { cb.cwnd += std::min(n, SMSS()); } void reno_deflate_cwnd(const uint16_t n) { cb.cwnd -= (n >= SMSS()) ? n-SMSS() : n; } void reduce_ssthresh(); void fast_retransmit(); void finish_fast_recovery(); bool reno_full_ack(seq_t ACK) { return static_cast<int32_t>(ACK - cb.recover) > 1; } /// --- STATE HANDLING --- /// /* Set state. (used by substates) */ void set_state(State& state); /// --- RETRANSMISSION --- /// /* Retransmit the first packet in retransmission queue. */ void retransmit(); /** * @brief Take an RTT measurment from an incoming packet. * Uses timestamp if timestamp options are in use, * else RTTM start/stop. * * @param[in] <unnamed> An incomming TCP packet */ void take_rtt_measure(const Packet_view&); /* Start retransmission timer. */ void rtx_start() { rtx_timer.start(rttm.rto_ms()); } /* Stop retransmission timer. */ void rtx_stop() { rtx_timer.stop(); } /* Restart retransmission timer. */ void rtx_reset() { rtx_timer.restart(rttm.rto_ms()); } /* Retransmission timeout limit reached */ bool rto_limit_reached() const { return rtx_attempt_ >= 14 or syn_rtx_ >= 4; }; /* Remove all packets acknowledge by ACK in retransmission queue */ void rtx_ack(seq_t ack); /* Delete retransmission queue */ void rtx_clear(); /* When retransmission times out. */ void rtx_timeout(); /** Start the timewait timeout for 2*MSL */ void timewait_start(); /** Restart the timewait timer if active */ void timewait_restart(); /** When timewait timer times out */ void timewait_timeout() { signal_close(); } /** Whether to use Delayed ACK or not */ bool use_dack() const noexcept; /** * @brief Called when the DACK timeout timesout. */ void dack_timeout() { send_ack(); } /** * @brief Starts the DACK timer. */ void start_dack(); /** * @brief Stops the DACK timer. */ void stop_dack() { timewait_dack_timer.stop(); } /* Tell the host (TCP) to delete this connection. */ void signal_close(); /** * @brief Clean up user callbacks * @details Removes all the user defined lambdas to avoid any potential * copies of a Connection_ptr to the this connection. */ void clean_up(); /// --- OPTIONS --- /// /* Parse and apply options. */ void parse_options(const Packet_view&); /* Add an option. */ void add_option(Option::Kind, Packet_view&); }; // < class Connection } // < namespace tcp } // < namespace net #include "connection.inc" #endif // < NET_TCP_CONNECTION_HPP
{ "content_hash": "f09330b10ab8b31fc3fa2d54d26a2d44", "timestamp": "", "source": "github", "line_count": 1214, "max_line_length": 113, "avg_line_length": 26.387149917627678, "alnum_prop": 0.6190297808578386, "repo_name": "AndreasAakesson/IncludeOS", "id": "0fa2cd80ff1389f0932e0f70b1ece42b28c9ba74", "size": "32038", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "api/net/tcp/connection.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "74689" }, { "name": "C", "bytes": "42647" }, { "name": "C++", "bytes": "3355508" }, { "name": "CMake", "bytes": "121023" }, { "name": "Dockerfile", "bytes": "846" }, { "name": "GDB", "bytes": "255" }, { "name": "JavaScript", "bytes": "2898" }, { "name": "Makefile", "bytes": "1719" }, { "name": "Python", "bytes": "96273" }, { "name": "Ruby", "bytes": "586" }, { "name": "Shell", "bytes": "35133" } ], "symlink_target": "" }
package com.alibaba.json.bvt.serializer; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; public class JSONFieldTest4 extends TestCase { public void test_jsonField() throws Exception { VO vo = new VO(); vo.setId(123); vo.setFlag(true); String text = JSON.toJSONString(vo); Assert.assertEquals("{\"id\":123}", text); } public static class VO { private int id; @JSONField(serialize = false) private boolean m_flag; @JSONField(serialize = false) private int m_id2; public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isFlag() { return m_flag; } public void setFlag(boolean flag) { this.m_flag = flag; } public int getId2() { return m_id2; } public void setId2(int id2) { this.m_id2 = id2; } } }
{ "content_hash": "3fe9b73b85908c9f1df7329f00c86400", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 49, "avg_line_length": 17.087719298245613, "alnum_prop": 0.6232032854209446, "repo_name": "alibaba/fastjson", "id": "896bcafa30ce761c8bcd3447cef0391e834a11c1", "size": "974", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest4.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7489145" }, { "name": "JavaScript", "bytes": "3661" }, { "name": "Kotlin", "bytes": "5407" }, { "name": "Shell", "bytes": "414" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.cart.shipping"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="summary-block-config" xsi:type="array"> <item name="children" xsi:type="array"> <item name="shipping-rates-validation" xsi:type="array"> <item name="children" xsi:type="array"> <item name="dhl-rates-validation" xsi:type="array"> <item name="component" xsi:type="string">Magento_Dhl/js/view/shipping-rates-validation</item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
{ "content_hash": "388d4970ff60d6e63238e2cbd90f506e", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 153, "avg_line_length": 46.81481481481482, "alnum_prop": 0.4438291139240506, "repo_name": "enettolima/magento-training", "id": "49d31ff3efb3b2d68ca3d9fa33645667ec0097e8", "size": "1362", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "magento2ce/app/code/Magento/Dhl/view/frontend/layout/checkout_cart_index.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "22648" }, { "name": "CSS", "bytes": "3382928" }, { "name": "HTML", "bytes": "8749335" }, { "name": "JavaScript", "bytes": "7355635" }, { "name": "PHP", "bytes": "58607662" }, { "name": "Perl", "bytes": "10258" }, { "name": "Shell", "bytes": "41887" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
package org.bouncycastle.asn1.sec; import java.math.BigInteger; import java.util.Enumeration; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.util.BigIntegers; /** * the elliptic curve private key object from SEC 1 */ public class ECPrivateKey extends ASN1Object { private ASN1Sequence seq; private ECPrivateKey( ASN1Sequence seq) { this.seq = seq; } public static ECPrivateKey getInstance( Object obj) { if (obj instanceof ECPrivateKey) { return (ECPrivateKey)obj; } if (obj != null) { return new ECPrivateKey(ASN1Sequence.getInstance(obj)); } return null; } public ECPrivateKey( BigInteger key) { byte[] bytes = BigIntegers.asUnsignedByteArray(key); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(1)); v.add(new DEROctetString(bytes)); seq = new DERSequence(v); } public ECPrivateKey( BigInteger key, ASN1Encodable parameters) { this(key, null, parameters); } public ECPrivateKey( BigInteger key, DERBitString publicKey, ASN1Encodable parameters) { byte[] bytes = BigIntegers.asUnsignedByteArray(key); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(1)); v.add(new DEROctetString(bytes)); if (parameters != null) { v.add(new DERTaggedObject(true, 0, parameters)); } if (publicKey != null) { v.add(new DERTaggedObject(true, 1, publicKey)); } seq = new DERSequence(v); } public BigInteger getKey() { ASN1OctetString octs = (ASN1OctetString)seq.getObjectAt(1); return new BigInteger(1, octs.getOctets()); } public DERBitString getPublicKey() { return (DERBitString)getObjectInTag(1); } public ASN1Primitive getParameters() { return getObjectInTag(0); } private ASN1Primitive getObjectInTag(int tagNo) { Enumeration e = seq.getObjects(); while (e.hasMoreElements()) { ASN1Encodable obj = (ASN1Encodable)e.nextElement(); if (obj instanceof ASN1TaggedObject) { ASN1TaggedObject tag = (ASN1TaggedObject)obj; if (tag.getTagNo() == tagNo) { return tag.getObject().toASN1Primitive(); } } } return null; } /** * ECPrivateKey ::= SEQUENCE { * version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), * privateKey OCTET STRING, * parameters [0] Parameters OPTIONAL, * publicKey [1] BIT STRING OPTIONAL } */ public ASN1Primitive toASN1Primitive() { return seq; } }
{ "content_hash": "4436383bd071a0ac9fb28e9481f85f1a", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 67, "avg_line_length": 24.055944055944057, "alnum_prop": 0.6156976744186047, "repo_name": "alphallc/connectbot", "id": "df2238a3beef95726f2662e8e5eb451d7d5be17e", "size": "3440", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "src/org/bouncycastle/asn1/sec/ECPrivateKey.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "5383" }, { "name": "Java", "bytes": "8679024" } ], "symlink_target": "" }
package com.zhokhov.graphql.datetime; import graphql.PublicApi; import graphql.schema.GraphQLScalarType; @PublicApi public final class OffsetDateTimeScalar { private OffsetDateTimeScalar() { } public static GraphQLScalarType create(String name) { return GraphQLScalarType.newScalar() .name(name != null ? name : "OffsetDateTime") .description("A Java OffsetDateTime") .coercing(new GraphqlOffsetDateTimeCoercing()) .build(); } }
{ "content_hash": "0884f6a691f8a23dd779b495eafbf61c", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 62, "avg_line_length": 24.904761904761905, "alnum_prop": 0.6577437858508605, "repo_name": "donbeave/graphql-java-datetime", "id": "0188ebf7fdb3b40ca038710a63f55c6da711e8f2", "size": "1117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "graphql-java-datetime/src/main/java/com/zhokhov/graphql/datetime/OffsetDateTimeScalar.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "41007" }, { "name": "Java", "bytes": "61436" }, { "name": "Kotlin", "bytes": "14313" }, { "name": "Shell", "bytes": "2320" } ], "symlink_target": "" }
RESTful Webservices with TYPO3 Flow =================================== Martin Helmich <typo3@martin-helmich.de> Synopsis -------- This repository contains an example application that demonstrates on how to implement RESTful Webservices with TYPO3 Flow. It contains three packages: - `Helmich.Products` contains entity classes and repositories around a simple inventory management domain model - `Helmich.ProductsApiSimple` contains a simple REST-like API (level 2 of the [Richardson Maturity Model](http://martinfowler.com/articles/richardsonMaturityModel.html)) which allows you to CRUD products and manufacturers using respective HTTP methods. - `Helmich.ProductsApiAdvanced` contains an advanced API (level 3 of the RMM), which is _hypermedia controlled_ (which means that there are links between resources) and also shows some design patterns to decouple your REST resource representations from your domain entities. Installation ------------ You can install this application using [Composer](http://getcomposer.org): composer create-project helmich/flow-restapi-example Follow the [TYPO3 Flow installation instructions](http://docs.typo3.org/flow/TYPO3FlowDocumentation/Quickstart/Index.html#installing-typo3-flow) in all other ways. Also [set up your database](http://docs.typo3.org/flow/TYPO3FlowDocumentation/Quickstart/Index.html#database-setup) and run the database migrations: ./flow doctrine:migrate
{ "content_hash": "352a7a4c2307d8ad466397da5e222eab", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 144, "avg_line_length": 46.38709677419355, "alnum_prop": 0.7788595271210014, "repo_name": "martin-helmich/flow-restapi-example", "id": "d0025b177f450b973758f319da848d3c3294da3e", "size": "1438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "24709" } ], "symlink_target": "" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (14.0.1) on Tue Jun 09 12:08:35 EDT 2020 --> <title>Constant Field Values (Database 1.5.38 API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2020-06-09"> <meta name="description" content="summary of constants"> <meta name="generator" content="javadoc/ConstantsSummaryWriterImpl"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="script-dir/jquery-ui.css" title="Style"> <script type="text/javascript" src="script.js"></script> <script type="text/javascript" src="script-dir/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="script-dir/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="script-dir/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="script-dir/jquery-3.4.1.js"></script> <script type="text/javascript" src="script-dir/jquery-ui.js"></script> </head> <body class="constants-summary"> <script type="text/javascript">var pathtoroot = "./"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flexBox"> <header role="banner" class="flexHeader"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="com/brettonw/bedrock/database/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="com/brettonw/bedrock/database/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"> <div class="navListSearch"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="skipNav"><a id="skip.navbar.top"> <!-- --> </a></div> </nav> </header> <div class="flexContent"> <main role="main"> <div class="header"> <h1 title="Constant Field Values" class="title">Constant Field Values</h1> <section class="packages"> <h2 title="Contents">Contents</h2> <ul> <li><a href="#com.brettonw">com.brettonw.*</a></li> </ul> </section> </div> <div class="constantValuesContainer"><a id="com.brettonw"> <!-- --> </a> <section class="constantsSummary"> <h2 title="com.brettonw">com.brettonw.*</h2> <ul class="blockList"> <li class="blockList"> <div class="constantsSummary"> <table> <caption><span>com.brettonw.bedrock.database.<a href="com/brettonw/bedrock/database/MongoDatabase.html" title="class in com.brettonw.bedrock.database">MongoDatabase</a></span><span class="tabEnd">&nbsp;</span></caption> <thead> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colSecond" scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> </thead> <tbody> <tr class="altColor"> <td class="colFirst"><a id="com.brettonw.bedrock.database.MongoDatabase.COLLECTION_NAME"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a></code></td> <th class="colSecond" scope="row"><code><a href="com/brettonw/bedrock/database/MongoDatabase.html#COLLECTION_NAME">COLLECTION_NAME</a></code></th> <td class="colLast"><code>"collection-name"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a id="com.brettonw.bedrock.database.MongoDatabase.COLLECTION_NAMES"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a></code></td> <th class="colSecond" scope="row"><code><a href="com/brettonw/bedrock/database/MongoDatabase.html#COLLECTION_NAMES">COLLECTION_NAMES</a></code></th> <td class="colLast"><code>"collection-names"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a id="com.brettonw.bedrock.database.MongoDatabase.CONNECTION_STRING"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a></code></td> <th class="colSecond" scope="row"><code><a href="com/brettonw/bedrock/database/MongoDatabase.html#CONNECTION_STRING">CONNECTION_STRING</a></code></th> <td class="colLast"><code>"connection-string"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a id="com.brettonw.bedrock.database.MongoDatabase.DATABASE_NAME"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a></code></td> <th class="colSecond" scope="row"><code><a href="com/brettonw/bedrock/database/MongoDatabase.html#DATABASE_NAME">DATABASE_NAME</a></code></th> <td class="colLast"><code>"database-name"</code></td> </tr> </tbody> </table> </div> </li> </ul> </section> </div> </main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="com/brettonw/bedrock/database/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="com/brettonw/bedrock/database/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> <a id="skip.navbar.bottom"> <!-- --> </a> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small>Copyright &#169; 2020. All rights reserved.</small></p> </footer> </div> </div> </body> </html>
{ "content_hash": "facf8414009682574c9c7201895ed266", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 238, "avg_line_length": 42.294871794871796, "alnum_prop": 0.6885419824189148, "repo_name": "brettonw/Bedrock", "id": "c098eafe18ab49f9e05e057f619c59d4a09b78f5", "size": "6598", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "applications/bedrock-site/src/main/webapp/dist/1.5.38/docs/database/constant-values.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "428" }, { "name": "Dockerfile", "bytes": "138" }, { "name": "HTML", "bytes": "53" }, { "name": "Java", "bytes": "403879" }, { "name": "JavaScript", "bytes": "8122" }, { "name": "Shell", "bytes": "6368" } ], "symlink_target": "" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef REMOTING_HOST_CHROMOTING_MESSAGES_H_ #define REMOTING_HOST_CHROMOTING_MESSAGES_H_ #include <stdint.h> #include "base/memory/shared_memory_handle.h" #include "ipc/ipc_platform_file.h" #include "remoting/host/chromoting_param_traits.h" #include "remoting/host/screen_resolution.h" #include "remoting/protocol/errors.h" #include "remoting/protocol/transport.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" #endif // REMOTING_HOST_CHROMOTING_MESSAGES_H_ // Multiply-included message file, no traditional include guard. #include "ipc/ipc_message_macros.h" #define IPC_MESSAGE_START ChromotingMsgStart //----------------------------------------------------------------------------- // Chromoting messages sent from the daemon. // Requests the receiving process to crash producing a crash dump. The daemon // sends this message when a fatal error has been detected indicating that // the receiving process misbehaves. The daemon passes the location of the code // that detected the error. IPC_MESSAGE_CONTROL3(ChromotingDaemonMsg_Crash, std::string /* function_name */, std::string /* file_name */, int /* line_number */) //----------------------------------------------------------------------------- // Chromoting messages sent from the daemon to the network process. // Delivers the host configuration (and updates) to the network process. IPC_MESSAGE_CONTROL1(ChromotingDaemonNetworkMsg_Configuration, std::string) // Initializes the pairing registry on Windows. The passed key handles are // already duplicated by the sender. IPC_MESSAGE_CONTROL2(ChromotingDaemonNetworkMsg_InitializePairingRegistry, IPC::PlatformFileForTransit /* privileged_key */, IPC::PlatformFileForTransit /* unprivileged_key */) // Notifies the network process that the terminal |terminal_id| has been // disconnected from the desktop session. IPC_MESSAGE_CONTROL1(ChromotingDaemonNetworkMsg_TerminalDisconnected, int /* terminal_id */) // Notifies the network process that |terminal_id| is now attached to // a desktop integration process. |desktop_process| is the handle of the desktop // process. |desktop_pipe| is the client end of the desktop-to-network pipe // opened. // // Windows only: |desktop_pipe| has to be duplicated from the desktop process // by the receiver of the message. |desktop_process| is already duplicated by // the sender. IPC_MESSAGE_CONTROL3(ChromotingDaemonNetworkMsg_DesktopAttached, int /* terminal_id */, base::ProcessHandle /* desktop_process */, IPC::PlatformFileForTransit /* desktop_pipe */) //----------------------------------------------------------------------------- // Chromoting messages sent from the network to the daemon process. // Connects the terminal |terminal_id| (i.e. a remote client) to a desktop // session. IPC_MESSAGE_CONTROL3(ChromotingNetworkHostMsg_ConnectTerminal, int /* terminal_id */, remoting::ScreenResolution /* resolution */, bool /* virtual_terminal */) // Disconnects the terminal |terminal_id| from the desktop session it was // connected to. IPC_MESSAGE_CONTROL1(ChromotingNetworkHostMsg_DisconnectTerminal, int /* terminal_id */) // Changes the screen resolution in the given desktop session. IPC_MESSAGE_CONTROL2(ChromotingNetworkDaemonMsg_SetScreenResolution, int /* terminal_id */, remoting::ScreenResolution /* resolution */) // Serialized remoting::protocol::TransportRoute structure. IPC_STRUCT_BEGIN(SerializedTransportRoute) IPC_STRUCT_MEMBER(remoting::protocol::TransportRoute::RouteType, type) IPC_STRUCT_MEMBER(std::vector<uint8_t>, remote_ip) IPC_STRUCT_MEMBER(uint16_t, remote_port) IPC_STRUCT_MEMBER(std::vector<uint8_t>, local_ip) IPC_STRUCT_MEMBER(uint16_t, local_port) IPC_STRUCT_END() IPC_ENUM_TRAITS_MAX_VALUE(remoting::protocol::TransportRoute::RouteType, remoting::protocol::TransportRoute::ROUTE_TYPE_MAX) // Hosts status notifications (see HostStatusObserver interface) sent by // IpcHostEventLogger. IPC_MESSAGE_CONTROL1(ChromotingNetworkDaemonMsg_AccessDenied, std::string /* jid */) IPC_MESSAGE_CONTROL1(ChromotingNetworkDaemonMsg_ClientAuthenticated, std::string /* jid */) IPC_MESSAGE_CONTROL1(ChromotingNetworkDaemonMsg_ClientConnected, std::string /* jid */) IPC_MESSAGE_CONTROL1(ChromotingNetworkDaemonMsg_ClientDisconnected, std::string /* jid */) IPC_MESSAGE_CONTROL3(ChromotingNetworkDaemonMsg_ClientRouteChange, std::string /* jid */, std::string /* channel_name */, SerializedTransportRoute /* route */) IPC_MESSAGE_CONTROL1(ChromotingNetworkDaemonMsg_HostStarted, std::string /* xmpp_login */) IPC_MESSAGE_CONTROL0(ChromotingNetworkDaemonMsg_HostShutdown) //----------------------------------------------------------------------------- // Chromoting messages sent from the desktop to the daemon process. // Notifies the daemon that a desktop integration process has been initialized. // |desktop_pipe| specifies the client end of the desktop pipe. It is to be // forwarded to the desktop environment stub. // // Windows only: |desktop_pipe| has to be duplicated from the desktop process by // the receiver of the message. IPC_MESSAGE_CONTROL1(ChromotingDesktopDaemonMsg_DesktopAttached, IPC::PlatformFileForTransit /* desktop_pipe */) // Asks the daemon to inject Secure Attention Sequence (SAS) in the session // where the desktop process is running. IPC_MESSAGE_CONTROL0(ChromotingDesktopDaemonMsg_InjectSas) //----------------------------------------------------------------------------- // Chromoting messages sent from the desktop to the network process. // Notifies the network process that a shared buffer has been created. IPC_MESSAGE_CONTROL3(ChromotingDesktopNetworkMsg_CreateSharedBuffer, int /* id */, base::SharedMemoryHandle /* handle */, uint32_t /* size */) // Request the network process to stop using a shared buffer. IPC_MESSAGE_CONTROL1(ChromotingDesktopNetworkMsg_ReleaseSharedBuffer, int /* id */) // Serialized webrtc::DesktopFrame. IPC_STRUCT_BEGIN(SerializedDesktopFrame) // ID of the shared memory buffer containing the pixels. IPC_STRUCT_MEMBER(int, shared_buffer_id) // Width of a single row of pixels in bytes. IPC_STRUCT_MEMBER(int, bytes_per_row) // Captured region. IPC_STRUCT_MEMBER(std::vector<webrtc::DesktopRect>, dirty_region) // Dimensions of the buffer in pixels. IPC_STRUCT_MEMBER(webrtc::DesktopSize, dimensions) // Time spent in capture. Unit is in milliseconds. IPC_STRUCT_MEMBER(int64_t, capture_time_ms) // Latest event timestamp supplied by the client for performance tracking. IPC_STRUCT_MEMBER(int64_t, latest_event_timestamp) // DPI for this frame. IPC_STRUCT_MEMBER(webrtc::DesktopVector, dpi) IPC_STRUCT_END() IPC_ENUM_TRAITS_MAX_VALUE(webrtc::DesktopCapturer::Result, webrtc::DesktopCapturer::Result::MAX_VALUE) // Notifies the network process that a shared buffer has been created. IPC_MESSAGE_CONTROL2(ChromotingDesktopNetworkMsg_CaptureResult, webrtc::DesktopCapturer::Result /* result */, SerializedDesktopFrame /* frame */) // Carries a cursor share update from the desktop session agent to the client. IPC_MESSAGE_CONTROL1(ChromotingDesktopNetworkMsg_MouseCursor, webrtc::MouseCursor /* cursor */ ) // Carries a clipboard event from the desktop session agent to the client. // |serialized_event| is a serialized protocol::ClipboardEvent. IPC_MESSAGE_CONTROL1(ChromotingDesktopNetworkMsg_InjectClipboardEvent, std::string /* serialized_event */ ) IPC_ENUM_TRAITS_MAX_VALUE(remoting::protocol::ErrorCode, remoting::protocol::ERROR_CODE_MAX) // Requests the network process to terminate the client session. IPC_MESSAGE_CONTROL1(ChromotingDesktopNetworkMsg_DisconnectSession, remoting::protocol::ErrorCode /* error */) // Carries an audio packet from the desktop session agent to the client. // |serialized_packet| is a serialized AudioPacket. IPC_MESSAGE_CONTROL1(ChromotingDesktopNetworkMsg_AudioPacket, std::string /* serialized_packet */ ) //----------------------------------------------------------------------------- // Chromoting messages sent from the network to the desktop process. // Passes the client session data to the desktop session agent and starts it. // This must be the first message received from the host. IPC_MESSAGE_CONTROL3(ChromotingNetworkDesktopMsg_StartSessionAgent, std::string /* authenticated_jid */, remoting::ScreenResolution /* resolution */, bool /* virtual_terminal */) IPC_MESSAGE_CONTROL0(ChromotingNetworkDesktopMsg_CaptureFrame) // Carries a clipboard event from the client to the desktop session agent. // |serialized_event| is a serialized protocol::ClipboardEvent. IPC_MESSAGE_CONTROL1(ChromotingNetworkDesktopMsg_InjectClipboardEvent, std::string /* serialized_event */ ) // Carries a keyboard event from the client to the desktop session agent. // |serialized_event| is a serialized protocol::KeyEvent. IPC_MESSAGE_CONTROL1(ChromotingNetworkDesktopMsg_InjectKeyEvent, std::string /* serialized_event */ ) // Carries a keyboard event from the client to the desktop session agent. // |serialized_event| is a serialized protocol::TextEvent. IPC_MESSAGE_CONTROL1(ChromotingNetworkDesktopMsg_InjectTextEvent, std::string /* serialized_event */ ) // Carries a mouse event from the client to the desktop session agent. // |serialized_event| is a serialized protocol::MouseEvent. IPC_MESSAGE_CONTROL1(ChromotingNetworkDesktopMsg_InjectMouseEvent, std::string /* serialized_event */ ) // Carries a touch event from the client to the desktop session agent. // |serialized_event| is a serialized protocol::TouchEvent. IPC_MESSAGE_CONTROL1(ChromotingNetworkDesktopMsg_InjectTouchEvent, std::string /* serialized_event */ ) // Changes the screen resolution in the desktop session. IPC_MESSAGE_CONTROL1(ChromotingNetworkDesktopMsg_SetScreenResolution, remoting::ScreenResolution /* resolution */) //--------------------------------------------------------------------- // Chromoting messages sent from the remote_security_key process to the // network process. // The array of bytes representing a security key request to be sent to the // remote client. IPC_MESSAGE_CONTROL1(ChromotingRemoteSecurityKeyToNetworkMsg_Request, std::string /* request bytes */) //--------------------------------------------------------- // Chromoting messages sent from the network process to the remote_security_key // process. The network process uses two types of IPC channels to communicate // with the remote_security_key process. The first is the 'service' channel. // It uses a hard-coded path known by the client and server classes and its job // is to create a new, private IPC channel for the client and provide the path // to that channel over the original IPC channel. This purpose for this // mechanism is to allow the network process to service multiple concurrent // security key requests. Once a client receives the connection details for // its private IPC channel, the server channel is reset and can be called by // another client. // The second type of IPC channel is strictly used for passing security key // request and response messages. It is destroyed once the client disconnects. // The IPC channel path for this remote_security_key connection. This message // is sent from the well-known IPC server channel. IPC_MESSAGE_CONTROL1(ChromotingNetworkToRemoteSecurityKeyMsg_ConnectionDetails, std::string /* IPC Server path */) // The array of bytes representing a security key response from the remote // client. This message is sent over the per-client IPC channel. IPC_MESSAGE_CONTROL1(ChromotingNetworkToRemoteSecurityKeyMsg_Response, std::string /* response bytes */)
{ "content_hash": "2d3f4f5f43605baefde10894a39cec1b", "timestamp": "", "source": "github", "line_count": 278, "max_line_length": 80, "avg_line_length": 46.305755395683455, "alnum_prop": 0.6823584246096481, "repo_name": "ssaroha/node-webrtc", "id": "db17927c5ab3d37be6640901ccc593ee5580f2c1", "size": "12873", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "third_party/webrtc/include/chromium/src/remoting/host/chromoting_messages.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "6179" }, { "name": "C", "bytes": "2679" }, { "name": "C++", "bytes": "54327" }, { "name": "HTML", "bytes": "434" }, { "name": "JavaScript", "bytes": "42707" }, { "name": "Python", "bytes": "3835" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="aspect">notlong</string> </resources>
{ "content_hash": "1cc9ab4dee53c0059aa34d108bea382f", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 42, "avg_line_length": 26.75, "alnum_prop": 0.6635514018691588, "repo_name": "inloop/ScreenInfo", "id": "4db74ffd5d7949f8523bd7a3d9bbb210aaa71c04", "size": "107", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/res/values-notlong/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8358" } ], "symlink_target": "" }
'use strict'; angular.module('escritorio').controller('EscritorioController', ['$scope','Authentication','$location', function($scope,Authentication,$location) { if(Authentication.user === ''){ $location.path('/'); }else{ $scope.$emit('FullInitSession', {}); } } ]) .controller('DatepickerDemoCtrl', function ($scope) { $scope.today = function() { $scope.dt = new Date(); }; $scope.today(); $scope.clear = function () { $scope.dt = null; }; // Disable weekend selection $scope.disabled = function(date, mode) { return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) ); }; $scope.toggleMin = function() { $scope.minDate = $scope.minDate ? null : new Date(); }; $scope.toggleMin(); $scope.open = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']; $scope.format = $scope.formats[0]; });
{ "content_hash": "c05310517ddfc17816665e2a85236c09", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 103, "avg_line_length": 22.95744680851064, "alnum_prop": 0.5940685820203893, "repo_name": "cethap/ScrumTools.io", "id": "c1eefe741f149d4088db806c03d2dbf9bba1a07d", "size": "1079", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/modules/escritorio/controllers/escritorio.client.controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "161346" }, { "name": "HTML", "bytes": "257210" }, { "name": "JavaScript", "bytes": "1900626" }, { "name": "Shell", "bytes": "881" } ], "symlink_target": "" }
package server import ( "errors" "fmt" "io" "net" "sync" "time" "github.com/getcfs/megacfs/ftls" "github.com/getcfs/megacfs/oort/proto" "github.com/getcfs/megacfs/oort/valueproto" "github.com/gholt/ring" "github.com/gholt/store" "github.com/grpc-ecosystem/go-grpc-prometheus" "github.com/prometheus/client_golang/prometheus" "go.uber.org/zap" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) type ValueStore struct { sync.RWMutex waitGroup *sync.WaitGroup shutdownChan chan struct{} started bool valueStore store.ValueStore valueStoreMsgRing *ring.TCPMsgRing grpcServer *grpc.Server grpcAddressIndex int grpcCertFile string grpcKeyFile string replCertFile string replKeyFile string caFile string logger *zap.Logger } type ValueStoreConfig struct { GRPCAddressIndex int ReplAddressIndex int GRPCCertFile string GRPCKeyFile string ReplCertFile string ReplKeyFile string CAFile string Path string Scale float64 Ring ring.Ring Logger *zap.Logger } func resolveValueStoreConfig(c *ValueStoreConfig) *ValueStoreConfig { cfg := &ValueStoreConfig{} if c != nil { *cfg = *c } if cfg.Logger == nil { var err error cfg.Logger, err = zap.NewProduction() if err != nil { panic(err) } } return cfg } func NewValueStore(cfg *ValueStoreConfig) (*ValueStore, chan error, error) { cfg = resolveValueStoreConfig(cfg) s := &ValueStore{ waitGroup: &sync.WaitGroup{}, grpcAddressIndex: cfg.GRPCAddressIndex, grpcCertFile: cfg.GRPCCertFile, grpcKeyFile: cfg.GRPCKeyFile, replCertFile: cfg.ReplCertFile, replKeyFile: cfg.ReplKeyFile, caFile: cfg.CAFile, logger: cfg.Logger, } var err error s.valueStoreMsgRing, err = ring.NewTCPMsgRing(&ring.TCPMsgRingConfig{ AddressIndex: cfg.ReplAddressIndex, UseTLS: true, MutualTLS: true, CertFile: s.replCertFile, KeyFile: s.replKeyFile, CAFile: s.caFile, DefaultPort: 12321, }) if err != nil { return nil, nil, err } s.valueStoreMsgRing.SetRing(cfg.Ring) var valueStoreRestartChan chan error s.valueStore, valueStoreRestartChan = store.NewValueStore(&store.ValueStoreConfig{ Scale: cfg.Scale, Path: cfg.Path, MsgRing: s.valueStoreMsgRing, }) return s, valueStoreRestartChan, nil } func (s *ValueStore) Startup(ctx context.Context) error { s.Lock() defer s.Unlock() if s.started { return nil } s.started = true s.shutdownChan = make(chan struct{}) err := s.valueStore.Startup(ctx) if err != nil { return err } s.waitGroup.Add(1) go func() { mRingChanges := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "RingChanges", Help: "Number of received ring changes.", }) mRingChangeCloses := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "RingChangeCloses", Help: "Number of connections closed due to ring changes.", }) mMsgToNodes := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToNodes", Help: "Number of times MsgToNode function has been called; single message to single node.", }) mMsgToNodeNoRings := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToNodeNoRings", Help: "Number of times MsgToNode function has been called with no ring yet available.", }) mMsgToNodeNoNodes := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToNodeNoNodes", Help: "Number of times MsgToNode function has been called with no matching node.", }) mMsgToOtherReplicas := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToOtherReplicas", Help: "Number of times MsgToOtherReplicas function has been called; single message to all replicas, excluding the local replica if responsible.", }) mMsgToOtherReplicasNoRings := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToOtherReplicasNoRings", Help: "Number of times MsgToOtherReplicas function has been called with no ring yet available.", }) mListenErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "ListenErrors", Help: "Number of errors trying to establish a TCP listener.", }) mIncomingConnections := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "IncomingConnections", Help: "Number of incoming TCP connections made.", }) mDials := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "Dials", Help: "Number of attempts to establish outgoing TCP connections.", }) mDialErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "DialErrors", Help: "Number of errors trying to establish outgoing TCP connections.", }) mOutgoingConnections := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "OutgoingConnections", Help: "Number of outgoing TCP connections established.", }) mMsgChanCreations := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgChanCreations", Help: "Number of internal message channels created.", }) mMsgToAddrs := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "MsgToAddrsTCPMsgRing", Help: "Number times internal function msgToAddr has been called.", }) mMsgToAddrQueues := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToAddrQueues", Help: "Number of messages msgToAddr successfully queued.", }) mMsgToAddrTimeoutDrops := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToAddrTimeoutDrops", Help: "Number of messages msgToAddr dropped after timeout.", }) mMsgToAddrShutdownDrops := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgToAddrShutdownDrops", Help: "Number of messages msgToAddr dropped due to a shutdown.", }) mMsgReads := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgReads", Help: "Number of incoming messages read.", }) mMsgReadErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgReadErrors", Help: "Number of errors reading incoming messages.", }) mMsgWrites := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgWrites", Help: "Number of outgoing messages written.", }) mMsgWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStoreTCPMsgRing", Name: "MsgWriteErrors", Help: "Number of errors writing outgoing messages.", }) mValues := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "Values", Help: "Current number of values stored.", }) mValueBytes := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "ValueBytes", Help: "Current number of bytes for the values stored.", }) mLookups := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "Lookups", Help: "Count of lookup requests executed.", }) mLookupErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "LookupErrors", Help: "Count of lookup requests executed resulting in errors.", }) mReads := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "Reads", Help: "Count of read requests executed.", }) mReadErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "ReadErrors", Help: "Count of read requests executed resulting in errors.", }) mWrites := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "Writes", Help: "Count of write requests executed.", }) mWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "WriteErrors", Help: "Count of write requests executed resulting in errors.", }) mWritesOverridden := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "WritesOverridden", Help: "Count of write requests that were outdated or repeated.", }) mDeletes := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "Deletes", Help: "Count of delete requests executed.", }) mDeleteErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "DeleteErrors", Help: "Count of delete requests executed resulting in errors.", }) mDeletesOverridden := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "DeletesOverridden", Help: "Count of delete requests that were outdated or repeated.", }) mOutBulkSets := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "OutBulkSets", Help: "Count of outgoing bulk-set messages in response to incoming pull replication messages.", }) mOutBulkSetValues := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "OutBulkSetValues", Help: "Count of values in outgoing bulk-set messages; these bulk-set messages are those in response to incoming pull-replication messages.", }) mOutBulkSetPushes := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "OutBulkSetPushes", Help: "Count of outgoing bulk-set messages due to push replication.", }) mOutBulkSetPushValues := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "OutBulkSetPushValues", Help: "Count of values in outgoing bulk-set messages; these bulk-set messages are those due to push replication.", }) mOutPushReplicationSeconds := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "OutPushReplicationSeconds", Help: "How long the last out push replication pass took.", }) mInBulkSets := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSets", Help: "Count of incoming bulk-set messages.", }) mInBulkSetDrops := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetDrops", Help: "Count of incoming bulk-set messages dropped due to the local system being overworked at the time.", }) mInBulkSetInvalids := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetInvalids", Help: "Count of incoming bulk-set messages that couldn't be parsed.", }) mInBulkSetWrites := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetWrites", Help: "Count of writes due to incoming bulk-set messages.", }) mInBulkSetWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetWriteErrors", Help: "Count of errors returned from writes due to incoming bulk-set messages.", }) mInBulkSetWritesOverridden := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetWritesOverridden", Help: "Count of writes from incoming bulk-set messages that result in no change.", }) mOutBulkSetAcks := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "OutBulkSetAcks", Help: "Count of outgoing bulk-set-ack messages.", }) mInBulkSetAcks := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetAcks", Help: "Count of incoming bulk-set-ack messages.", }) mInBulkSetAckDrops := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetAckDrops", Help: "Count of incoming bulk-set-ack messages dropped due to the local system being overworked at the time.", }) mInBulkSetAckInvalids := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetAckInvalids", Help: "Count of incoming bulk-set-ack messages that couldn't be parsed.", }) mInBulkSetAckWrites := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetAckWrites", Help: "Count of writes (for local removal) due to incoming bulk-set-ack messages.", }) mInBulkSetAckWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetAckWriteErrors", Help: "Count of errors returned from writes due to incoming bulk-set-ack messages.", }) mInBulkSetAckWritesOverridden := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InBulkSetAckWritesOverridden", Help: "Count of writes from incoming bulk-set-ack messages that result in no change.", }) mOutPullReplications := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "OutPullReplications", Help: "Count of outgoing pull-replication messages.", }) mOutPullReplicationSeconds := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "OutPullReplicationSeconds", Help: "How long the last out pull replication pass took.", }) mInPullReplications := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InPullReplications", Help: "Count of incoming pull-replication messages.", }) mInPullReplicationDrops := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InPullReplicationDrops", Help: "Count of incoming pull-replication messages droppped due to the local system being overworked at the time.", }) mInPullReplicationInvalids := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "InPullReplicationInvalids", Help: "Count of incoming pull-replication messages that couldn't be parsed.", }) mExpiredDeletions := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "ExpiredDeletions", Help: "Count of recent deletes that have become old enough to be completely discarded.", }) mTombstoneDiscardSeconds := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "TombstoneDiscardSeconds", Help: "How long the last tombstone discard pass took.", }) mCompactionSeconds := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "CompactionSeconds", Help: "How long the last compaction pass took.", }) mCompactions := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "Compactions", Help: "Count of disk file sets compacted due to their contents exceeding a staleness threshold. For example, this happens when enough of the values have been overwritten or deleted in more recent operations.", }) mSmallFileCompactions := prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "ValueStore", Name: "SmallFileCompactions", Help: "Count of disk file sets compacted due to the entire file size being too small. For example, this may happen when the store is shutdown and restarted.", }) mReadOnly := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "ReadOnly", Help: "Indicates when the store has been put in read-only mode, whether by an operator or automatically by the watcher.", }) mAuditSeconds := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "ValueStore", Name: "AuditSeconds", Help: "How long the last audit pass took.", }) prometheus.Register(mRingChanges) prometheus.Register(mRingChangeCloses) prometheus.Register(mMsgToNodes) prometheus.Register(mMsgToNodeNoRings) prometheus.Register(mMsgToNodeNoNodes) prometheus.Register(mMsgToOtherReplicas) prometheus.Register(mMsgToOtherReplicasNoRings) prometheus.Register(mListenErrors) prometheus.Register(mIncomingConnections) prometheus.Register(mDials) prometheus.Register(mDialErrors) prometheus.Register(mOutgoingConnections) prometheus.Register(mMsgChanCreations) prometheus.Register(mMsgToAddrs) prometheus.Register(mMsgToAddrQueues) prometheus.Register(mMsgToAddrTimeoutDrops) prometheus.Register(mMsgToAddrShutdownDrops) prometheus.Register(mMsgReads) prometheus.Register(mMsgReadErrors) prometheus.Register(mMsgWrites) prometheus.Register(mMsgWriteErrors) prometheus.Register(mValues) prometheus.Register(mValueBytes) prometheus.Register(mLookups) prometheus.Register(mLookupErrors) prometheus.Register(mReads) prometheus.Register(mReadErrors) prometheus.Register(mWrites) prometheus.Register(mWriteErrors) prometheus.Register(mWritesOverridden) prometheus.Register(mDeletes) prometheus.Register(mDeleteErrors) prometheus.Register(mDeletesOverridden) prometheus.Register(mOutBulkSets) prometheus.Register(mOutBulkSetValues) prometheus.Register(mOutBulkSetPushes) prometheus.Register(mOutBulkSetPushValues) prometheus.Register(mOutPushReplicationSeconds) prometheus.Register(mInBulkSets) prometheus.Register(mInBulkSetDrops) prometheus.Register(mInBulkSetInvalids) prometheus.Register(mInBulkSetWrites) prometheus.Register(mInBulkSetWriteErrors) prometheus.Register(mInBulkSetWritesOverridden) prometheus.Register(mOutBulkSetAcks) prometheus.Register(mInBulkSetAcks) prometheus.Register(mInBulkSetAckDrops) prometheus.Register(mInBulkSetAckInvalids) prometheus.Register(mInBulkSetAckWrites) prometheus.Register(mInBulkSetAckWriteErrors) prometheus.Register(mInBulkSetAckWritesOverridden) prometheus.Register(mOutPullReplications) prometheus.Register(mOutPullReplicationSeconds) prometheus.Register(mInPullReplications) prometheus.Register(mInPullReplicationDrops) prometheus.Register(mInPullReplicationInvalids) prometheus.Register(mExpiredDeletions) prometheus.Register(mTombstoneDiscardSeconds) prometheus.Register(mCompactionSeconds) prometheus.Register(mCompactions) prometheus.Register(mSmallFileCompactions) prometheus.Register(mReadOnly) prometheus.Register(mAuditSeconds) tcpMsgRingStats := s.valueStoreMsgRing.Stats(false) for { select { case <-s.shutdownChan: s.waitGroup.Done() return case <-time.After(time.Minute): tcpMsgRingStats = s.valueStoreMsgRing.Stats(false) mRingChanges.Add(float64(tcpMsgRingStats.RingChanges)) mRingChangeCloses.Add(float64(tcpMsgRingStats.RingChangeCloses)) mMsgToNodes.Add(float64(tcpMsgRingStats.MsgToNodes)) mMsgToNodeNoRings.Add(float64(tcpMsgRingStats.MsgToNodeNoRings)) mMsgToNodeNoNodes.Add(float64(tcpMsgRingStats.MsgToNodeNoNodes)) mMsgToOtherReplicas.Add(float64(tcpMsgRingStats.MsgToOtherReplicas)) mMsgToOtherReplicasNoRings.Add(float64(tcpMsgRingStats.MsgToOtherReplicasNoRings)) mListenErrors.Add(float64(tcpMsgRingStats.ListenErrors)) mIncomingConnections.Add(float64(tcpMsgRingStats.IncomingConnections)) mDials.Add(float64(tcpMsgRingStats.Dials)) mDialErrors.Add(float64(tcpMsgRingStats.DialErrors)) mOutgoingConnections.Add(float64(tcpMsgRingStats.OutgoingConnections)) mMsgChanCreations.Add(float64(tcpMsgRingStats.MsgChanCreations)) mMsgToAddrs.Add(float64(tcpMsgRingStats.MsgToAddrs)) mMsgToAddrQueues.Add(float64(tcpMsgRingStats.MsgToAddrQueues)) mMsgToAddrTimeoutDrops.Add(float64(tcpMsgRingStats.MsgToAddrTimeoutDrops)) mMsgToAddrShutdownDrops.Add(float64(tcpMsgRingStats.MsgToAddrShutdownDrops)) mMsgReads.Add(float64(tcpMsgRingStats.MsgReads)) mMsgReadErrors.Add(float64(tcpMsgRingStats.MsgReadErrors)) mMsgWrites.Add(float64(tcpMsgRingStats.MsgWrites)) mMsgWriteErrors.Add(float64(tcpMsgRingStats.MsgWriteErrors)) stats, err := s.valueStore.Stats(context.Background(), false) if err != nil { s.logger.Debug("stats error", zap.Error(err)) } else if sstats, ok := stats.(*store.ValueStoreStats); ok { mValues.Set(float64(sstats.Values)) mValueBytes.Set(float64(sstats.ValueBytes)) mLookups.Add(float64(sstats.Lookups)) mLookupErrors.Add(float64(sstats.LookupErrors)) mReads.Add(float64(sstats.Reads)) mReadErrors.Add(float64(sstats.ReadErrors)) mWrites.Add(float64(sstats.Writes)) mWriteErrors.Add(float64(sstats.WriteErrors)) mWritesOverridden.Add(float64(sstats.WritesOverridden)) mDeletes.Add(float64(sstats.Deletes)) mDeleteErrors.Add(float64(sstats.DeleteErrors)) mDeletesOverridden.Add(float64(sstats.DeletesOverridden)) mOutBulkSets.Add(float64(sstats.OutBulkSets)) mOutBulkSetValues.Add(float64(sstats.OutBulkSetValues)) mOutBulkSetPushes.Add(float64(sstats.OutBulkSetPushes)) mOutBulkSetPushValues.Add(float64(sstats.OutBulkSetPushValues)) mOutPushReplicationSeconds.Set(float64(sstats.OutPushReplicationNanoseconds) / 1000000000) mInBulkSets.Add(float64(sstats.InBulkSets)) mInBulkSetDrops.Add(float64(sstats.InBulkSetDrops)) mInBulkSetInvalids.Add(float64(sstats.InBulkSetInvalids)) mInBulkSetWrites.Add(float64(sstats.InBulkSetWrites)) mInBulkSetWriteErrors.Add(float64(sstats.InBulkSetWriteErrors)) mInBulkSetWritesOverridden.Add(float64(sstats.InBulkSetWritesOverridden)) mOutBulkSetAcks.Add(float64(sstats.OutBulkSetAcks)) mInBulkSetAcks.Add(float64(sstats.InBulkSetAcks)) mInBulkSetAckDrops.Add(float64(sstats.InBulkSetAckDrops)) mInBulkSetAckInvalids.Add(float64(sstats.InBulkSetAckInvalids)) mInBulkSetAckWrites.Add(float64(sstats.InBulkSetAckWrites)) mInBulkSetAckWriteErrors.Add(float64(sstats.InBulkSetAckWriteErrors)) mInBulkSetAckWritesOverridden.Add(float64(sstats.InBulkSetAckWritesOverridden)) mOutPullReplications.Add(float64(sstats.OutPullReplications)) mOutPullReplicationSeconds.Set(float64(sstats.OutPullReplicationNanoseconds) / 1000000000) mInPullReplications.Add(float64(sstats.InPullReplications)) mInPullReplicationDrops.Add(float64(sstats.InPullReplicationDrops)) mInPullReplicationInvalids.Add(float64(sstats.InPullReplicationInvalids)) mExpiredDeletions.Add(float64(sstats.ExpiredDeletions)) mTombstoneDiscardSeconds.Set(float64(sstats.TombstoneDiscardNanoseconds) / 1000000000) mCompactionSeconds.Set(float64(sstats.CompactionNanoseconds) / 1000000000) mCompactions.Add(float64(sstats.Compactions)) mSmallFileCompactions.Add(float64(sstats.SmallFileCompactions)) if sstats.ReadOnly { mReadOnly.Set(1) } else { mReadOnly.Set(0) } mAuditSeconds.Set(float64(sstats.AuditNanoseconds) / 1000000000) } else { s.logger.Debug("unknown stats type", zap.Any("stats", stats)) } } } }() s.waitGroup.Add(1) go func() { s.valueStoreMsgRing.Listen() s.waitGroup.Done() }() s.waitGroup.Add(1) go func() { <-s.shutdownChan s.valueStoreMsgRing.Shutdown() s.waitGroup.Done() }() ln := s.valueStoreMsgRing.Ring().LocalNode() if ln == nil { return errors.New("no local node set") } grpcAddr := ln.Address(s.grpcAddressIndex) if grpcAddr == "" { return fmt.Errorf("no local node address index %d", s.grpcAddressIndex) } grpcHostPort, err := ring.CanonicalHostPort(grpcAddr, 12320) if err != nil { return err } lis, err := net.Listen("tcp", grpcHostPort) if err != nil { return err } tlsCfg, err := ftls.NewServerTLSConfig(ftls.DefaultServerFTLSConf(s.grpcCertFile, s.grpcKeyFile, s.caFile)) if err != nil { return err } s.grpcServer = grpc.NewServer( grpc.Creds(credentials.NewTLS(tlsCfg)), grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor), grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor), ) valueproto.RegisterValueStoreServer(s.grpcServer, s) grpc_prometheus.Register(s.grpcServer) s.waitGroup.Add(1) go func() { err := s.grpcServer.Serve(lis) if err != nil { s.logger.Debug("grpcServer.Serve error", zap.Error(err)) } lis.Close() s.waitGroup.Done() }() s.waitGroup.Add(1) go func() { <-s.shutdownChan s.grpcServer.Stop() lis.Close() s.waitGroup.Done() }() return nil } func (s *ValueStore) Shutdown(ctx context.Context) error { s.Lock() defer s.Unlock() if !s.started { return nil } close(s.shutdownChan) s.waitGroup.Wait() return s.valueStore.Shutdown(ctx) } func (s *ValueStore) Write(stream valueproto.ValueStore_WriteServer) error { // NOTE: Each of these streams is synchronized req1, resp1, req2, resp2. // But it doesn't have to be that way, it was just simpler to code. Each // client/server pair will have a stream for each request/response type, so // there's a pretty good amount of concurrency going on there already. // Perhaps later we can experiment with intrastream concurrency and see if // the complexity is worth it. // // The main reason for using streams over unary grpc requests was // benchmarked speed gains. I suspect it is because unary requests actually // set up and tear down streams for each request, but that's just a guess. // We stopped looking into it once we noticed the speed gains from // switching to streaming. var resp valueproto.WriteResponse for { req, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } resp.Reset() resp.RPCID = req.RPCID resp.TimestampMicro, err = s.valueStore.Write(stream.Context(), req.KeyA, req.KeyB, req.TimestampMicro, req.Value) if err != nil { resp.Err = proto.TranslateError(err) } if err := stream.Send(&resp); err != nil { return err } } } func (s *ValueStore) Read(stream valueproto.ValueStore_ReadServer) error { var resp valueproto.ReadResponse for { req, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } resp.Reset() resp.RPCID = req.RPCID resp.TimestampMicro, resp.Value, err = s.valueStore.Read(stream.Context(), req.KeyA, req.KeyB, resp.Value) if err != nil { resp.Err = proto.TranslateError(err) } if err := stream.Send(&resp); err != nil { return err } } } func (s *ValueStore) Lookup(stream valueproto.ValueStore_LookupServer) error { var resp valueproto.LookupResponse for { req, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } resp.Reset() resp.RPCID = req.RPCID resp.TimestampMicro, resp.Length, err = s.valueStore.Lookup(stream.Context(), req.KeyA, req.KeyB) if err != nil { resp.Err = proto.TranslateError(err) } if err := stream.Send(&resp); err != nil { return err } } } func (s *ValueStore) Delete(stream valueproto.ValueStore_DeleteServer) error { var resp valueproto.DeleteResponse for { req, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } resp.Reset() resp.RPCID = req.RPCID resp.TimestampMicro, err = s.valueStore.Delete(stream.Context(), req.KeyA, req.KeyB, req.TimestampMicro) if err != nil { resp.Err = proto.TranslateError(err) } if err := stream.Send(&resp); err != nil { return err } } } func (s *ValueStore) Stats() []byte { stats, err := s.valueStore.Stats(context.Background(), true) if err != nil { return nil } return []byte(stats.String()) } // Wait isn't implemented yet, need graceful shutdowns in grpc func (s *ValueStore) Wait() {}
{ "content_hash": "da63af2852f2d15c339e11a61f343178", "timestamp": "", "source": "github", "line_count": 766, "max_line_length": 217, "avg_line_length": 36.88120104438642, "alnum_prop": 0.7272308944816113, "repo_name": "getcfs/megacfs", "id": "0e5adabfd41ccd99c6b6b84f77670d3151100564", "size": "28251", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "oort/server/valuestore_GEN_.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "460017" }, { "name": "Makefile", "bytes": "1942" }, { "name": "Protocol Buffer", "bytes": "14425" }, { "name": "Shell", "bytes": "213" } ], "symlink_target": "" }
import { HandlerConfig } from './HandlerConfig'; /** * Configuration settings for a Handler object. */ export interface ProxyHandlerConfig extends HandlerConfig { /** * Remote root path where the request will be redirected. Defaults to '/'. e.g. */ baseUrl?: string; /** * Name of the Path Parameter on the AWS request that contains the path of the request. This will default to `path` * if not specified. */ pathParameterName?: string; /** * Whatever the request should be handle over HTTPS. Default to true. */ ssl?: boolean; /** * Remote Port where the request should be directed. Defaults to 443 for HTTPS request and 80 for HTTP request. */ port?: number; /** * whatever OPTIONS request should be process locally. If set to `true`, pre-flight OPTIONS request will be handle * locally. An empty response will be sent and the cors headers will be defined via the HandlerConfig options. * * If set to false, the the request will be relayed to the remtoe server. * * Defaults to true. */ processOptionsLocally?: boolean; /** * List of headers that should be copied over from the original request to the proxy request. */ whiteListedHeaders?: string[]; /** * List of headers that should be copied over from the proxy response to the lambda response. */ whiteListedResponseHeaders?: string[] }
{ "content_hash": "707d43ee6438501a0336fe87a9636be2", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 119, "avg_line_length": 29.877551020408163, "alnum_prop": 0.6584699453551912, "repo_name": "syrp-nz/ts-lambda-handler", "id": "8ad0633d1512502853de95e6b1797e72a2a6bcd7", "size": "1464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Config/ProxyHandlerConfig.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "18" }, { "name": "TypeScript", "bytes": "184483" } ], "symlink_target": "" }
function vals=rgbimg2vals(img,normFlag) %Function vals=rgbimg2vals(img,normFlag) inputs an RGB image and %outputs an Nx3 vector of vals % %Inputs: img - The image to be vectorized % normFlag - Optional argument specifying a normalized output % %Outputs: vals - An Nx3 vector of RGB vals when N=X*Y, [X Y Z]=size(img) % % %5/25/03 - Leo Grady % Copyright (C) 2002, 2003 Leo Grady <lgrady@cns.bu.edu> % Computer Vision and Computational Neuroscience Lab % Department of Cognitive and Neural Systems % Boston University % Boston, MA 02215 % % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % % Date - $Id: rgbimg2vals.m,v 1.2 2003/08/21 17:29:29 lgrady Exp $ %========================================================================% %Read arguments if nargin < 2 normFlag=0; end %Decompose image into channels redChannel=img(:,:,1); greenChannel=img(:,:,2); blueChannel=img(:,:,3); %Compose vals vals=[redChannel(:),greenChannel(:),blueChannel(:)]; %Perform normalization if normFlag vals=normalize(vals); end
{ "content_hash": "cff5d6249d617e6988f3f82e8ffa5175", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 77, "avg_line_length": 32.67307692307692, "alnum_prop": 0.7004120070629782, "repo_name": "pranavtbhat/CS275", "id": "bdc0fed15cc9a36c2871590120ac000906756088", "size": "1699", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "resources/graphAnalysisToolbox-1.0/rgbimg2vals.m", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "11759" }, { "name": "Matlab", "bytes": "351839" }, { "name": "TeX", "bytes": "132086" } ], "symlink_target": "" }
#import <UIKit/UIKit.h> #import <Foundation/Foundation.h> @interface XMLImageManager : NSObject /** There are 3 way to get reaource image 1. @image/[file_name] : return image named file_name 2. @resizable/t l b r/[file_name] : return resizable image named file_name with parms (insets area is optional) 3. [file_name] : same to 1 Image cached if you use @+ instead of @ */ + (UIImage *)imageWithString:(NSString *)string; + (UIImage *)imageWithResourceName:(NSString *)resourceName cached:(BOOL)cached; @end
{ "content_hash": "689765c81467d890ba37a5e1475de1f2", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 112, "avg_line_length": 32.294117647058826, "alnum_prop": 0.6830601092896175, "repo_name": "naru-jpn/XMLLayouts", "id": "eb39dce71beb754b729c95d36f2e37a3ce65a607", "size": "549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XMLLayouts/R/Managers/XMLImageManager.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "133748" }, { "name": "Ruby", "bytes": "616" } ], "symlink_target": "" }
require File.expand_path(File.dirname(__FILE__) + '/selenium/client') # Backward compatibility SeleniumHelper = Selenium::Client::SeleniumHelper SeleniumCommandError = Selenium::CommandError Selenium::SeleniumDriver = Selenium::Client::Driver
{ "content_hash": "41625f8e1031a0fec138d6678d44a0ce", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 69, "avg_line_length": 34.857142857142854, "alnum_prop": 0.7991803278688525, "repo_name": "Jeff-Tian/mybnb", "id": "e12735dbe79ff331250f58cd728b0ccad71854d9", "size": "439", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Ruby200/lib/ruby/gems/2.0.0/gems/selenium-client-1.2.18/lib/selenium.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "455330" }, { "name": "Batchfile", "bytes": "6263" }, { "name": "C", "bytes": "2304983" }, { "name": "C#", "bytes": "8440" }, { "name": "C++", "bytes": "31815" }, { "name": "CSS", "bytes": "30628" }, { "name": "Cucumber", "bytes": "248616" }, { "name": "F#", "bytes": "2310" }, { "name": "Forth", "bytes": "506" }, { "name": "GLSL", "bytes": "1040" }, { "name": "Groff", "bytes": "31983" }, { "name": "HTML", "bytes": "376863" }, { "name": "JavaScript", "bytes": "20239" }, { "name": "M4", "bytes": "67848" }, { "name": "Makefile", "bytes": "142926" }, { "name": "Mask", "bytes": "969" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "Python", "bytes": "19913027" }, { "name": "REXX", "bytes": "3862" }, { "name": "Ruby", "bytes": "14954382" }, { "name": "Shell", "bytes": "366205" }, { "name": "Tcl", "bytes": "2150972" }, { "name": "TeX", "bytes": "230259" }, { "name": "Visual Basic", "bytes": "494" }, { "name": "XSLT", "bytes": "3736" }, { "name": "Yacc", "bytes": "14342" } ], "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. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ReadOnlyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.StaticKeyword, }; public ReadOnlyKeywordRecommender() : base(SyntaxKind.ReadOnlyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || IsRefReadOnlyContext(context) || IsValidContextForType(context, cancellationToken) || context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } private static bool IsRefReadOnlyContext(CSharpSyntaxContext context) => context.TargetToken.IsKind(SyntaxKind.RefKeyword) && (context.TargetToken.Parent.IsKind(SyntaxKind.RefType) || context.IsFunctionPointerTypeArgumentContext); private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: true, cancellationToken); } } }
{ "content_hash": "2726919cef9cacc1ae6aadc5e308a971", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 147, "avg_line_length": 46.018181818181816, "alnum_prop": 0.7020940339786645, "repo_name": "stephentoub/roslyn", "id": "bd18a594aecd150bd70fa8130698f822479c1b23", "size": "2533", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "src/Features/CSharp/Portable/Completion/KeywordRecommenders/ReadOnlyKeywordRecommender.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "257760" }, { "name": "Batchfile", "bytes": "8025" }, { "name": "C#", "bytes": "141577774" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "9153" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "242771" }, { "name": "Shell", "bytes": "94346" }, { "name": "Visual Basic .NET", "bytes": "71902552" } ], "symlink_target": "" }
import { ActionTypes } from 'mongorito' const defaultGetTimestamp = () => new Date() const createdAt = 'created' const updatedAt = 'updated' export default () => { return ({ model }) => (next) => (action) => { if (action.type === ActionTypes.SAVE) { const timestamp = defaultGetTimestamp() const { fields } = action if (Object.is(action.fields[createdAt], undefined)) { fields[createdAt] = timestamp model.set(createdAt, timestamp) } fields[updatedAt] = timestamp model.set(updatedAt, timestamp) } if (action.type === ActionTypes.QUERY) { const isSelectUsed = action.query.filter((q) => q[0] === 'select').length > 0 if (isSelectUsed) { action.query.push(['select', { [createdAt]: 1, [updatedAt]: 1 }]) } } return next(action) } }
{ "content_hash": "e14cec957f1ae99234fa3a9c3d2448d9", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 83, "avg_line_length": 26.25, "alnum_prop": 0.5988095238095238, "repo_name": "nguyen504e/eblog", "id": "5ed5b151291005a119440695a8a430901aa90a1a", "size": "840", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/server/models/plugins/timestamp.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2034" }, { "name": "HTML", "bytes": "13253" }, { "name": "JavaScript", "bytes": "71790" } ], "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_09) on Wed Mar 06 22:32:47 PST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.SolrTestCaseJ4.IVals (Solr 4.2.0 API)</title> <meta name="date" content="2013-03-06"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.SolrTestCaseJ4.IVals (Solr 4.2.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/apache/solr/SolrTestCaseJ4.IVals.html" title="class in org.apache.solr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/solr/class-use/SolrTestCaseJ4.IVals.html" target="_top">Frames</a></li> <li><a href="SolrTestCaseJ4.IVals.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.SolrTestCaseJ4.IVals" class="title">Uses of Class<br>org.apache.solr.SolrTestCaseJ4.IVals</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../org/apache/solr/SolrTestCaseJ4.IVals.html" title="class in org.apache.solr">SolrTestCaseJ4.IVals</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.solr">org.apache.solr</a></td> <td class="colLast"> <div class="block">Common base classes for implementing tests.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.solr"> <!-- --> </a> <h3>Uses of <a href="../../../../org/apache/solr/SolrTestCaseJ4.IVals.html" title="class in org.apache.solr">SolrTestCaseJ4.IVals</a> in <a href="../../../../org/apache/solr/package-summary.html">org.apache.solr</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../org/apache/solr/SolrTestCaseJ4.IVals.html" title="class in org.apache.solr">SolrTestCaseJ4.IVals</a> in <a href="../../../../org/apache/solr/package-summary.html">org.apache.solr</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/solr/SolrTestCaseJ4.IRange.html" title="class in org.apache.solr">SolrTestCaseJ4.IRange</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/apache/solr/SolrTestCaseJ4.IVals.html" title="class in org.apache.solr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/solr/class-use/SolrTestCaseJ4.IVals.html" target="_top">Frames</a></li> <li><a href="SolrTestCaseJ4.IVals.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2013 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
{ "content_hash": "35dfc022b2188ced08eb3d462e07209b", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 283, "avg_line_length": 37.73410404624278, "alnum_prop": 0.6205575980392157, "repo_name": "gibrantd/solr-4.2.0", "id": "53ba8f8d1c744e55d3afe595ecd541736e2707f2", "size": "6528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/solr-test-framework/org/apache/solr/class-use/SolrTestCaseJ4.IVals.html", "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> <HEAD> <!-- Generated by javadoc (build 1.6.0_03) on Mon Nov 19 21:41:20 CET 2007 --> <TITLE> Uses of Class org.springframework.jms.JmsSecurityException (Spring Framework API 2.5) </TITLE> <META NAME="date" CONTENT="2007-11-19"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.springframework.jms.JmsSecurityException (Spring Framework API 2.5)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/springframework/jms/JmsSecurityException.html" title="class in org.springframework.jms"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/springframework/jms/\class-useJmsSecurityException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JmsSecurityException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.springframework.jms.JmsSecurityException</B></H2> </CENTER> No usage of org.springframework.jms.JmsSecurityException <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/springframework/jms/JmsSecurityException.html" title="class in org.springframework.jms"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/springframework/jms/\class-useJmsSecurityException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JmsSecurityException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &copy; 2002-2007 <a href=http://www.springframework.org/ target=_top>The Spring Framework</a>.</i> </BODY> </HTML>
{ "content_hash": "775ce3c20e919f1e967de1c896d536b6", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 221, "avg_line_length": 43.31944444444444, "alnum_prop": 0.630650849631292, "repo_name": "mattxia/spring-2.5-analysis", "id": "cc64d51500cdf343674d5767ac25ebea004c51d0", "size": "6238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/springframework/jms/class-use/JmsSecurityException.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "18516" }, { "name": "CSS", "bytes": "20368" }, { "name": "Groovy", "bytes": "2361" }, { "name": "Java", "bytes": "16366293" }, { "name": "Ruby", "bytes": "623" }, { "name": "Shell", "bytes": "684" }, { "name": "XSLT", "bytes": "2674" } ], "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_162) on Sat Apr 25 17:14:54 PDT 2020 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.fasterxml.jackson.databind.util.ArrayBuilders.ShortBuilder (jackson-databind 2.11.0 API)</title> <meta name="date" content="2020-04-25"> <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="Uses of Class com.fasterxml.jackson.databind.util.ArrayBuilders.ShortBuilder (jackson-databind 2.11.0 API)"; } } catch(err) { } //--> </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><a href="../../../../../../com/fasterxml/jackson/databind/util/ArrayBuilders.ShortBuilder.html" title="class in com.fasterxml.jackson.databind.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/util/class-use/ArrayBuilders.ShortBuilder.html" target="_top">Frames</a></li> <li><a href="ArrayBuilders.ShortBuilder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.fasterxml.jackson.databind.util.ArrayBuilders.ShortBuilder" class="title">Uses of Class<br>com.fasterxml.jackson.databind.util.ArrayBuilders.ShortBuilder</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../com/fasterxml/jackson/databind/util/ArrayBuilders.ShortBuilder.html" title="class in com.fasterxml.jackson.databind.util">ArrayBuilders.ShortBuilder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.fasterxml.jackson.databind.util">com.fasterxml.jackson.databind.util</a></td> <td class="colLast"> <div class="block">Utility classes for Mapper package.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.fasterxml.jackson.databind.util"> <!-- --> </a> <h3>Uses of <a href="../../../../../../com/fasterxml/jackson/databind/util/ArrayBuilders.ShortBuilder.html" title="class in com.fasterxml.jackson.databind.util">ArrayBuilders.ShortBuilder</a> in <a href="../../../../../../com/fasterxml/jackson/databind/util/package-summary.html">com.fasterxml.jackson.databind.util</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../com/fasterxml/jackson/databind/util/package-summary.html">com.fasterxml.jackson.databind.util</a> that return <a href="../../../../../../com/fasterxml/jackson/databind/util/ArrayBuilders.ShortBuilder.html" title="class in com.fasterxml.jackson.databind.util">ArrayBuilders.ShortBuilder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../com/fasterxml/jackson/databind/util/ArrayBuilders.ShortBuilder.html" title="class in com.fasterxml.jackson.databind.util">ArrayBuilders.ShortBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">ArrayBuilders.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/util/ArrayBuilders.html#getShortBuilder--">getShortBuilder</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= 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><a href="../../../../../../com/fasterxml/jackson/databind/util/ArrayBuilders.ShortBuilder.html" title="class in com.fasterxml.jackson.databind.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/util/class-use/ArrayBuilders.ShortBuilder.html" target="_top">Frames</a></li> <li><a href="ArrayBuilders.ShortBuilder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2008&#x2013;2020 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "af43cd474be26e1b16c185895760e677", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 393, "avg_line_length": 43.726190476190474, "alnum_prop": 0.650966512387694, "repo_name": "FasterXML/jackson-databind", "id": "348a36f840cef5ad92a8420f0d6ad87d7bdd1a93", "size": "7346", "binary": false, "copies": "1", "ref": "refs/heads/2.15", "path": "docs/javadoc/2.11/com/fasterxml/jackson/databind/util/class-use/ArrayBuilders.ShortBuilder.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7940640" }, { "name": "Logos", "bytes": "173041" }, { "name": "Shell", "bytes": "264" } ], "symlink_target": "" }
(function () { "use strict"; // MP3 Framesize and length for Layer II and Layer III var SAMPLE_SIZE = 1152; var SAMPLE_DURATION_MS = 70; // namespace aliases var Storage = Windows.Storage; var Streams = Windows.Storage.Streams; var XORMediaSource = WinJS.Class.define(function (url, key) { this.url = url; this.key = key; this.streamInfo = null; }, { initAsync: function () { var self = this; // load the URL var p1 = this._loadStream(this.url); // extract display name from url var displayName = self.url.substr(self.url.lastIndexOf("/") + 1); // created streamed file var p2 = Storage.StorageFile.createStreamedFileAsync( displayName, self._streamedDataProvider.bind(self), null); return WinJS.Promise.join([p1, p2]).then(function (results) { self.streamInfo = results[0]; var file = results[1]; return file.openAsync(Storage.FileAccessMode.read).then(function (stream) { return { file: file, stream: stream }; }); }).then(function (data) { // get encoding properties of the mp3 file var props = [ "System.Audio.SampleRate", "System.Audio.ChannelCount", "System.Audio.EncodingBitrate" ]; return data.file.properties.retrievePropertiesAsync(props); }).then(function (props) { var b = props.hasKey("System.Audio.SampleRate"); //var sampleRate = props["System.Audio.SampleRate"]; //var channelCount = props["System.Audio.ChannelCount"]; //var encodingBitRate = props["System.Audio.EncodingBitRate"]; }); }, _streamedDataProvider: function (request) { // xor-decrypt the stream and load into a memory stream var reader = new Streams.DataReader(this.streamInfo.inputStream); // write the contents of "stream" into "request" var writer = new Streams.DataWriter(request); // copy the streams return this._copyStreamAsync( reader, writer, this._xorTransform.bind(self)).then(function () { writer.close(); }); }, _xorTransform: function (buffer) { for (var i = 0; i < buffer.length; i++) { buffer[i] = buffer[i] ^ this.key; } }, _copyStreamAsync: function (dataReader, dataWriter, transform) { var BUFFER_SIZE = 1024; var buffer = new Uint8Array(BUFFER_SIZE); var loop = function (bytesLoaded) { // load the data into buffer if (bytesLoaded < BUFFER_SIZE) { buffer = new Uint8Array(bytesLoaded); } dataReader.readBytes(buffer); // transform data transform(buffer); // write the data into dataWriter dataWriter.writeBytes(buffer); // if bytesLoaded is less than BUFFER_SIZE then we are done if (bytesLoaded < BUFFER_SIZE) { dataReader.close(); } else { // Create another promise to asynchronously execute the next iteration. // Because loadAsync is permitted to complete synchronously, we avoid using a simple // nested call to loop. Such a nested call could lead to deep recursion, and, if enough // loadAsync calls complete synchronously, eventual stack overflow. return WinJS.Promise.timeout(0).then(function () { return dataReader.loadAsync(BUFFER_SIZE); }).then(loop); } }; return dataReader.loadAsync(BUFFER_SIZE).then(loop); }, _loadStream: function(url) { return new WinJS.Promise(function (success, error, progress) { var streamProcessed = false; WinJS.xhr({ url: url, responseType: "ms-stream" }).done(null,function (xhr) { error(xhr); }, function (xhr) { if (xhr.readyState === 3 && xhr.status === 200 && streamProcessed === false) { streamProcessed = true; var msstream = xhr.response; // this is an MSStream object var inputStream = msstream.msDetachStream(); success({ inputStream: inputStream, mimeType: msstream.type }); } }); }); } }); // add XORMediaSource to namespace WinJS.Namespace.define("StreamUtils", { XORMediaSource: XORMediaSource }); })();
{ "content_hash": "1123524b06296491f60f1293c3ba99f6", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 109, "avg_line_length": 36.58741258741259, "alnum_prop": 0.5005733944954128, "repo_name": "MavenRain/AudioPlayerWithCustomStream", "id": "b340d2ec9cf20d840ff056f001b35597e9924f59", "size": "5234", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MediaPlayerWithCustomStream/js/XORMediaSourceWithStorageFile.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "346" }, { "name": "C#", "bytes": "2837" }, { "name": "C++", "bytes": "2977" }, { "name": "CSS", "bytes": "75" }, { "name": "HTML", "bytes": "888" }, { "name": "JavaScript", "bytes": "16535" } ], "symlink_target": "" }
create class coo( col1 char(20), col2 char(20), col3 char(20), col4 char(20), col5 char(20), col6 char(20), col7 char(20), col8 char(20), col9 char(20), col10 char(20), col11 char(20), col12 char(20), col13 char(20), col14 char(20), col15 char(20), col16 char(20), col17 char(20), col18 char(20), col19 char(20), col20 char(20) ); insert into coo (col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14,col15, col16, col17, col18, col19, col20) values('aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii', 'jjj', 'kkk', 'lll', 'mmm', 'nnn', 'ooo', 'ppp', 'qqq', 'rrr', 'sss', 'ttt'); insert into coo (col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14,col15, col16, col17, col18, col19, col20) values('bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii', 'jjj', 'kkk', 'lll', 'mmm', 'nnn', 'ooo', 'ppp', 'qqq', 'rrr', 'sss', 'ttt', 'uuu'); show columns in coo; --change to the same type alter table coo change col1 aaa char(20), change col2 bbb nchar(20); select col1, col2 from coo order by 1; alter table coo change col3 ccc nchar varying(20); select col3 from coo order by 1; alter table coo change col4 ddd bit(8), change col5 eee bit varying(8); select col4, col5 from coo order by 1; alter table coo change col6 fff numeric, change col7 ggg integer primary key; select col6, col7 from coo order by 1; alter table coo change col8 hhh smallint not null, change col9 iii monetary, change col10 jjj float default 10.01; select hhh, iii, jjj from coo order by 1; alter table coo change col11 kkk double unique, change col12 lll date; select col11, col12 from coo order by 1; alter table coo change col13 mmm time, change col14 nnn timestamp not null; select mmm, nnn from coo order by 1; alter table coo change col15 ooo set, change col16 ppp multiset, change col17 qqq sequence, change col18 rrr blob, change col19 sss clob; select col15, col16, col17, col18, col19 from coo order by 1; --change the same column twice in one statement alter table coo change col20 sss varchar, change col20 ttt varchar(100); select * from coo order by 1; show columns in coo; delete from coo; drop table coo;
{ "content_hash": "67d119dd97e7cccfabaf7d362fef0178", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 148, "avg_line_length": 35.54545454545455, "alnum_prop": 0.6534526854219949, "repo_name": "CUBRID/cubrid-testcases", "id": "98b745fa40ea813f241314de4ab82248081d0b8a", "size": "2391", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "sql/_17_sql_extension2/_02_full_test/_03_alter_table/_01_alter_change/cases/alter_change_038.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PLSQL", "bytes": "682246" }, { "name": "Roff", "bytes": "23262735" }, { "name": "TSQL", "bytes": "5619" }, { "name": "eC", "bytes": "710" } ], "symlink_target": "" }
package org.apache.kafka.common.network; import java.io.IOException; import java.io.EOFException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.channels.SelectionKey; import java.nio.channels.CancelledKeyException; import java.security.Principal; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLKeyException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLProtocolException; import javax.net.ssl.SSLSession; import org.apache.kafka.common.errors.SslAuthenticationException; import org.apache.kafka.common.security.auth.KafkaPrincipal; import org.apache.kafka.common.utils.ByteUtils; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.ByteBufferUnmapper; import org.apache.kafka.common.utils.Utils; import org.slf4j.Logger; /* * Transport layer for SSL communication * * * TLS v1.3 notes: * https://tools.ietf.org/html/rfc8446#section-4.6 : Post-Handshake Messages * "TLS also allows other messages to be sent after the main handshake. * These messages use a handshake content type and are encrypted under * the appropriate application traffic key." */ public class SslTransportLayer implements TransportLayer { private enum State { // Initial state NOT_INITALIZED, // SSLEngine is in handshake mode HANDSHAKE, // SSL handshake failed, connection will be terminated HANDSHAKE_FAILED, // SSLEngine has completed handshake, post-handshake messages may be pending for TLSv1.3 POST_HANDSHAKE, // SSLEngine has completed handshake, any post-handshake messages have been processed for TLSv1.3 // For TLSv1.3, we move the channel to READY state when incoming data is processed after handshake READY, // Channel is being closed CLOSING } private final String channelId; private final SSLEngine sslEngine; private final SelectionKey key; private final SocketChannel socketChannel; private final ChannelMetadataRegistry metadataRegistry; private final Logger log; private HandshakeStatus handshakeStatus; private SSLEngineResult handshakeResult; private State state; private SslAuthenticationException handshakeException; private ByteBuffer netReadBuffer; private ByteBuffer netWriteBuffer; private ByteBuffer appReadBuffer; private ByteBuffer fileChannelBuffer; private boolean hasBytesBuffered; public static SslTransportLayer create(String channelId, SelectionKey key, SSLEngine sslEngine, ChannelMetadataRegistry metadataRegistry) throws IOException { return new SslTransportLayer(channelId, key, sslEngine, metadataRegistry); } // Prefer `create`, only use this in tests SslTransportLayer(String channelId, SelectionKey key, SSLEngine sslEngine, ChannelMetadataRegistry metadataRegistry) { this.channelId = channelId; this.key = key; this.socketChannel = (SocketChannel) key.channel(); this.sslEngine = sslEngine; this.state = State.NOT_INITALIZED; this.metadataRegistry = metadataRegistry; final LogContext logContext = new LogContext(String.format("[SslTransportLayer channelId=%s key=%s] ", channelId, key)); this.log = logContext.logger(getClass()); } // Visible for testing protected void startHandshake() throws IOException { if (state != State.NOT_INITALIZED) throw new IllegalStateException("startHandshake() can only be called once, state " + state); this.netReadBuffer = ByteBuffer.allocate(netReadBufferSize()); this.netWriteBuffer = ByteBuffer.allocate(netWriteBufferSize()); this.appReadBuffer = ByteBuffer.allocate(applicationBufferSize()); netWriteBuffer.limit(0); netReadBuffer.limit(0); state = State.HANDSHAKE; //initiate handshake sslEngine.beginHandshake(); handshakeStatus = sslEngine.getHandshakeStatus(); } @Override public boolean ready() { return state == State.POST_HANDSHAKE || state == State.READY; } /** * does socketChannel.finishConnect() */ @Override public boolean finishConnect() throws IOException { boolean connected = socketChannel.finishConnect(); if (connected) key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT | SelectionKey.OP_READ); return connected; } /** * disconnects selectionKey. */ @Override public void disconnect() { key.cancel(); } @Override public SocketChannel socketChannel() { return socketChannel; } @Override public SelectionKey selectionKey() { return key; } @Override public boolean isOpen() { return socketChannel.isOpen(); } @Override public boolean isConnected() { return socketChannel.isConnected(); } /** * Sends an SSL close message and closes socketChannel. */ @Override public void close() throws IOException { State prevState = state; if (state == State.CLOSING) return; state = State.CLOSING; sslEngine.closeOutbound(); try { if (prevState != State.NOT_INITALIZED && isConnected()) { if (!flush(netWriteBuffer)) { throw new IOException("Remaining data in the network buffer, can't send SSL close message."); } //prep the buffer for the close message netWriteBuffer.clear(); //perform the close, since we called sslEngine.closeOutbound SSLEngineResult wrapResult = sslEngine.wrap(ByteUtils.EMPTY_BUF, netWriteBuffer); //we should be in a close state if (wrapResult.getStatus() != SSLEngineResult.Status.CLOSED) { throw new IOException("Unexpected status returned by SSLEngine.wrap, expected CLOSED, received " + wrapResult.getStatus() + ". Will not send close message to peer."); } netWriteBuffer.flip(); flush(netWriteBuffer); } } catch (IOException ie) { log.debug("Failed to send SSL Close message", ie); } finally { socketChannel.socket().close(); socketChannel.close(); netReadBuffer = null; netWriteBuffer = null; appReadBuffer = null; if (fileChannelBuffer != null) { ByteBufferUnmapper.unmap("fileChannelBuffer", fileChannelBuffer); fileChannelBuffer = null; } } } /** * returns true if there are any pending contents in netWriteBuffer */ @Override public boolean hasPendingWrites() { return netWriteBuffer.hasRemaining(); } /** * Reads available bytes from socket channel to `netReadBuffer`. * Visible for testing. * @return number of bytes read */ protected int readFromSocketChannel() throws IOException { return socketChannel.read(netReadBuffer); } /** * Flushes the buffer to the network, non blocking. * Visible for testing. * @param buf ByteBuffer * @return boolean true if the buffer has been emptied out, false otherwise * @throws IOException */ protected boolean flush(ByteBuffer buf) throws IOException { int remaining = buf.remaining(); if (remaining > 0) { int written = socketChannel.write(buf); return written >= remaining; } return true; } /** * Performs SSL handshake, non blocking. * Before application data (kafka protocols) can be sent client & kafka broker must * perform ssl handshake. * During the handshake SSLEngine generates encrypted data that will be transported over socketChannel. * Each SSLEngine operation generates SSLEngineResult , of which SSLEngineResult.handshakeStatus field is used to * determine what operation needs to occur to move handshake along. * A typical handshake might look like this. * +-------------+----------------------------------+-------------+ * | client | SSL/TLS message | HSStatus | * +-------------+----------------------------------+-------------+ * | wrap() | ClientHello | NEED_UNWRAP | * | unwrap() | ServerHello/Cert/ServerHelloDone | NEED_WRAP | * | wrap() | ClientKeyExchange | NEED_WRAP | * | wrap() | ChangeCipherSpec | NEED_WRAP | * | wrap() | Finished | NEED_UNWRAP | * | unwrap() | ChangeCipherSpec | NEED_UNWRAP | * | unwrap() | Finished | FINISHED | * +-------------+----------------------------------+-------------+ * * @throws IOException if read/write fails * @throws SslAuthenticationException if handshake fails with an {@link SSLException} */ @Override public void handshake() throws IOException { if (state == State.NOT_INITALIZED) { try { startHandshake(); } catch (SSLException e) { maybeProcessHandshakeFailure(e, false, null); } } if (ready()) throw renegotiationException(); if (state == State.CLOSING) throw closingException(); int read = 0; boolean readable = key.isReadable(); try { // Read any available bytes before attempting any writes to ensure that handshake failures // reported by the peer are processed even if writes fail (since peer closes connection // if handshake fails) if (readable) read = readFromSocketChannel(); doHandshake(); if (ready()) updateBytesBuffered(true); } catch (SSLException e) { maybeProcessHandshakeFailure(e, true, null); } catch (IOException e) { maybeThrowSslAuthenticationException(); // This exception could be due to a write. If there is data available to unwrap in the buffer, or data available // in the socket channel to read and unwrap, process the data so that any SSL handshake exceptions are reported. try { do { handshakeUnwrap(false, true); } while (readable && readFromSocketChannel() > 0); } catch (SSLException e1) { maybeProcessHandshakeFailure(e1, false, e); } // If we get here, this is not a handshake failure, throw the original IOException throw e; } // Read from socket failed, so throw any pending handshake exception or EOF exception. if (read == -1) { maybeThrowSslAuthenticationException(); throw new EOFException("EOF during handshake, handshake status is " + handshakeStatus); } } @SuppressWarnings("fallthrough") private void doHandshake() throws IOException { boolean read = key.isReadable(); boolean write = key.isWritable(); handshakeStatus = sslEngine.getHandshakeStatus(); if (!flush(netWriteBuffer)) { key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return; } // Throw any pending handshake exception since `netWriteBuffer` has been flushed maybeThrowSslAuthenticationException(); switch (handshakeStatus) { case NEED_TASK: log.trace("SSLHandshake NEED_TASK channelId {}, appReadBuffer pos {}, netReadBuffer pos {}, netWriteBuffer pos {}", channelId, appReadBuffer.position(), netReadBuffer.position(), netWriteBuffer.position()); handshakeStatus = runDelegatedTasks(); break; case NEED_WRAP: log.trace("SSLHandshake NEED_WRAP channelId {}, appReadBuffer pos {}, netReadBuffer pos {}, netWriteBuffer pos {}", channelId, appReadBuffer.position(), netReadBuffer.position(), netWriteBuffer.position()); handshakeResult = handshakeWrap(write); if (handshakeResult.getStatus() == Status.BUFFER_OVERFLOW) { int currentNetWriteBufferSize = netWriteBufferSize(); netWriteBuffer.compact(); netWriteBuffer = Utils.ensureCapacity(netWriteBuffer, currentNetWriteBufferSize); netWriteBuffer.flip(); if (netWriteBuffer.limit() >= currentNetWriteBufferSize) { throw new IllegalStateException("Buffer overflow when available data size (" + netWriteBuffer.limit() + ") >= network buffer size (" + currentNetWriteBufferSize + ")"); } } else if (handshakeResult.getStatus() == Status.BUFFER_UNDERFLOW) { throw new IllegalStateException("Should not have received BUFFER_UNDERFLOW during handshake WRAP."); } else if (handshakeResult.getStatus() == Status.CLOSED) { throw new EOFException(); } log.trace("SSLHandshake NEED_WRAP channelId {}, handshakeResult {}, appReadBuffer pos {}, netReadBuffer pos {}, netWriteBuffer pos {}", channelId, handshakeResult, appReadBuffer.position(), netReadBuffer.position(), netWriteBuffer.position()); //if handshake status is not NEED_UNWRAP or unable to flush netWriteBuffer contents //we will break here otherwise we can do need_unwrap in the same call. if (handshakeStatus != HandshakeStatus.NEED_UNWRAP || !flush(netWriteBuffer)) { key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); break; } case NEED_UNWRAP: log.trace("SSLHandshake NEED_UNWRAP channelId {}, appReadBuffer pos {}, netReadBuffer pos {}, netWriteBuffer pos {}", channelId, appReadBuffer.position(), netReadBuffer.position(), netWriteBuffer.position()); do { handshakeResult = handshakeUnwrap(read, false); if (handshakeResult.getStatus() == Status.BUFFER_OVERFLOW) { int currentAppBufferSize = applicationBufferSize(); appReadBuffer = Utils.ensureCapacity(appReadBuffer, currentAppBufferSize); if (appReadBuffer.position() > currentAppBufferSize) { throw new IllegalStateException("Buffer underflow when available data size (" + appReadBuffer.position() + ") > packet buffer size (" + currentAppBufferSize + ")"); } } } while (handshakeResult.getStatus() == Status.BUFFER_OVERFLOW); if (handshakeResult.getStatus() == Status.BUFFER_UNDERFLOW) { int currentNetReadBufferSize = netReadBufferSize(); netReadBuffer = Utils.ensureCapacity(netReadBuffer, currentNetReadBufferSize); if (netReadBuffer.position() >= currentNetReadBufferSize) { throw new IllegalStateException("Buffer underflow when there is available data"); } } else if (handshakeResult.getStatus() == Status.CLOSED) { throw new EOFException("SSL handshake status CLOSED during handshake UNWRAP"); } log.trace("SSLHandshake NEED_UNWRAP channelId {}, handshakeResult {}, appReadBuffer pos {}, netReadBuffer pos {}, netWriteBuffer pos {}", channelId, handshakeResult, appReadBuffer.position(), netReadBuffer.position(), netWriteBuffer.position()); //if handshakeStatus completed than fall-through to finished status. //after handshake is finished there is no data left to read/write in socketChannel. //so the selector won't invoke this channel if we don't go through the handshakeFinished here. if (handshakeStatus != HandshakeStatus.FINISHED) { if (handshakeStatus == HandshakeStatus.NEED_WRAP) { key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); } else if (handshakeStatus == HandshakeStatus.NEED_UNWRAP) { key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); } break; } case FINISHED: handshakeFinished(); break; case NOT_HANDSHAKING: handshakeFinished(); break; default: throw new IllegalStateException(String.format("Unexpected status [%s]", handshakeStatus)); } } private SSLHandshakeException renegotiationException() { return new SSLHandshakeException("Renegotiation is not supported"); } private IllegalStateException closingException() { throw new IllegalStateException("Channel is in closing state"); } /** * Executes the SSLEngine tasks needed. * @return HandshakeStatus */ private HandshakeStatus runDelegatedTasks() { for (;;) { Runnable task = delegatedTask(); if (task == null) { break; } task.run(); } return sslEngine.getHandshakeStatus(); } /** * Checks if the handshake status is finished * Sets the interestOps for the selectionKey. */ private void handshakeFinished() throws IOException { // SSLEngine.getHandshakeStatus is transient and it doesn't record FINISHED status properly. // It can move from FINISHED status to NOT_HANDSHAKING after the handshake is completed. // Hence we also need to check handshakeResult.getHandshakeStatus() if the handshake finished or not if (handshakeResult.getHandshakeStatus() == HandshakeStatus.FINISHED) { //we are complete if we have delivered the last packet //remove OP_WRITE if we are complete, otherwise we still have data to write if (netWriteBuffer.hasRemaining()) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); else { state = sslEngine.getSession().getProtocol().equals("TLSv1.3") ? State.POST_HANDSHAKE : State.READY; key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); SSLSession session = sslEngine.getSession(); log.debug("SSL handshake completed successfully with peerHost '{}' peerPort {} peerPrincipal '{}' cipherSuite '{}'", session.getPeerHost(), session.getPeerPort(), peerPrincipal(), session.getCipherSuite()); metadataRegistry.registerCipherInformation( new CipherInformation(session.getCipherSuite(), session.getProtocol())); } log.trace("SSLHandshake FINISHED channelId {}, appReadBuffer pos {}, netReadBuffer pos {}, netWriteBuffer pos {} ", channelId, appReadBuffer.position(), netReadBuffer.position(), netWriteBuffer.position()); } else { throw new IOException("NOT_HANDSHAKING during handshake"); } } /** * Performs the WRAP function * @param doWrite boolean * @return SSLEngineResult * @throws IOException */ private SSLEngineResult handshakeWrap(boolean doWrite) throws IOException { log.trace("SSLHandshake handshakeWrap {}", channelId); if (netWriteBuffer.hasRemaining()) throw new IllegalStateException("handshakeWrap called with netWriteBuffer not empty"); //this should never be called with a network buffer that contains data //so we can clear it here. netWriteBuffer.clear(); SSLEngineResult result = sslEngine.wrap(ByteUtils.EMPTY_BUF, netWriteBuffer); //prepare the results to be written netWriteBuffer.flip(); handshakeStatus = result.getHandshakeStatus(); if (result.getStatus() == SSLEngineResult.Status.OK && result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { handshakeStatus = runDelegatedTasks(); } if (doWrite) flush(netWriteBuffer); return result; } /** * Perform handshake unwrap * @param doRead boolean If true, read more from the socket channel * @param ignoreHandshakeStatus If true, continue to unwrap if data available regardless of handshake status * @return SSLEngineResult * @throws IOException */ private SSLEngineResult handshakeUnwrap(boolean doRead, boolean ignoreHandshakeStatus) throws IOException { log.trace("SSLHandshake handshakeUnwrap {}", channelId); SSLEngineResult result; int read = 0; if (doRead) read = readFromSocketChannel(); boolean cont; do { //prepare the buffer with the incoming data int position = netReadBuffer.position(); netReadBuffer.flip(); result = sslEngine.unwrap(netReadBuffer, appReadBuffer); netReadBuffer.compact(); handshakeStatus = result.getHandshakeStatus(); if (result.getStatus() == SSLEngineResult.Status.OK && result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { handshakeStatus = runDelegatedTasks(); } cont = (result.getStatus() == SSLEngineResult.Status.OK && handshakeStatus == HandshakeStatus.NEED_UNWRAP) || (ignoreHandshakeStatus && netReadBuffer.position() != position); log.trace("SSLHandshake handshakeUnwrap: handshakeStatus {} status {}", handshakeStatus, result.getStatus()); } while (netReadBuffer.position() != 0 && cont); // Throw EOF exception for failed read after processing already received data // so that handshake failures are reported correctly if (read == -1) throw new EOFException("EOF during handshake, handshake status is " + handshakeStatus); return result; } /** * Reads a sequence of bytes from this channel into the given buffer. Reads as much as possible * until either the dst buffer is full or there is no more data in the socket. * * @param dst The buffer into which bytes are to be transferred * @return The number of bytes read, possible zero or -1 if the channel has reached end-of-stream * and no more data is available * @throws IOException if some other I/O error occurs */ @Override public int read(ByteBuffer dst) throws IOException { if (state == State.CLOSING) return -1; else if (!ready()) return 0; //if we have unread decrypted data in appReadBuffer read that into dst buffer. int read = 0; if (appReadBuffer.position() > 0) { read = readFromAppBuffer(dst); } boolean readFromNetwork = false; boolean isClosed = false; // Each loop reads at most once from the socket. while (dst.remaining() > 0) { int netread = 0; netReadBuffer = Utils.ensureCapacity(netReadBuffer, netReadBufferSize()); if (netReadBuffer.remaining() > 0) { netread = readFromSocketChannel(); if (netread > 0) readFromNetwork = true; } while (netReadBuffer.position() > 0) { netReadBuffer.flip(); SSLEngineResult unwrapResult; try { unwrapResult = sslEngine.unwrap(netReadBuffer, appReadBuffer); if (state == State.POST_HANDSHAKE && appReadBuffer.position() != 0) { // For TLSv1.3, we have finished processing post-handshake messages since we are now processing data state = State.READY; } } catch (SSLException e) { // For TLSv1.3, handle SSL exceptions while processing post-handshake messages as authentication exceptions if (state == State.POST_HANDSHAKE) { state = State.HANDSHAKE_FAILED; throw new SslAuthenticationException("Failed to process post-handshake messages", e); } else throw e; } netReadBuffer.compact(); // handle ssl renegotiation. if (unwrapResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && unwrapResult.getHandshakeStatus() != HandshakeStatus.FINISHED && unwrapResult.getStatus() == Status.OK) { log.error("Renegotiation requested, but it is not supported, channelId {}, " + "appReadBuffer pos {}, netReadBuffer pos {}, netWriteBuffer pos {} handshakeStatus {}", channelId, appReadBuffer.position(), netReadBuffer.position(), netWriteBuffer.position(), unwrapResult.getHandshakeStatus()); throw renegotiationException(); } if (unwrapResult.getStatus() == Status.OK) { read += readFromAppBuffer(dst); } else if (unwrapResult.getStatus() == Status.BUFFER_OVERFLOW) { int currentApplicationBufferSize = applicationBufferSize(); appReadBuffer = Utils.ensureCapacity(appReadBuffer, currentApplicationBufferSize); if (appReadBuffer.position() >= currentApplicationBufferSize) { throw new IllegalStateException("Buffer overflow when available data size (" + appReadBuffer.position() + ") >= application buffer size (" + currentApplicationBufferSize + ")"); } // appReadBuffer will extended upto currentApplicationBufferSize // we need to read the existing content into dst before we can do unwrap again. If there are no space in dst // we can break here. if (dst.hasRemaining()) read += readFromAppBuffer(dst); else break; } else if (unwrapResult.getStatus() == Status.BUFFER_UNDERFLOW) { int currentNetReadBufferSize = netReadBufferSize(); netReadBuffer = Utils.ensureCapacity(netReadBuffer, currentNetReadBufferSize); if (netReadBuffer.position() >= currentNetReadBufferSize) { throw new IllegalStateException("Buffer underflow when available data size (" + netReadBuffer.position() + ") > packet buffer size (" + currentNetReadBufferSize + ")"); } break; } else if (unwrapResult.getStatus() == Status.CLOSED) { // If data has been read and unwrapped, return the data. Close will be handled on the next poll. if (appReadBuffer.position() == 0 && read == 0) throw new EOFException(); else { isClosed = true; break; } } } if (read == 0 && netread < 0) throw new EOFException("EOF during read"); if (netread <= 0 || isClosed) break; } updateBytesBuffered(readFromNetwork || read > 0); // If data has been read and unwrapped, return the data even if end-of-stream, channel will be closed // on a subsequent poll. return read; } /** * Reads a sequence of bytes from this channel into the given buffers. * * @param dsts - The buffers into which bytes are to be transferred. * @return The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream. * @throws IOException if some other I/O error occurs */ @Override public long read(ByteBuffer[] dsts) throws IOException { return read(dsts, 0, dsts.length); } /** * Reads a sequence of bytes from this channel into a subsequence of the given buffers. * @param dsts - The buffers into which bytes are to be transferred * @param offset - The offset within the buffer array of the first buffer into which bytes are to be transferred; must be non-negative and no larger than dsts.length. * @param length - The maximum number of buffers to be accessed; must be non-negative and no larger than dsts.length - offset * @return The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream. * @throws IOException if some other I/O error occurs */ @Override public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) throw new IndexOutOfBoundsException(); int totalRead = 0; int i = offset; while (i < length) { if (dsts[i].hasRemaining()) { int read = read(dsts[i]); if (read > 0) totalRead += read; else break; } if (!dsts[i].hasRemaining()) { i++; } } return totalRead; } /** * Writes a sequence of bytes to this channel from the given buffer. * * @param src The buffer from which bytes are to be retrieved * @return The number of bytes read from src, possibly zero, or -1 if the channel has reached end-of-stream * @throws IOException If some other I/O error occurs */ @Override public int write(ByteBuffer src) throws IOException { if (state == State.CLOSING) throw closingException(); if (!ready()) return 0; int written = 0; while (flush(netWriteBuffer) && src.hasRemaining()) { netWriteBuffer.clear(); SSLEngineResult wrapResult = sslEngine.wrap(src, netWriteBuffer); netWriteBuffer.flip(); //handle ssl renegotiation if (wrapResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && wrapResult.getStatus() == Status.OK) throw renegotiationException(); if (wrapResult.getStatus() == Status.OK) { written += wrapResult.bytesConsumed(); } else if (wrapResult.getStatus() == Status.BUFFER_OVERFLOW) { // BUFFER_OVERFLOW means that the last `wrap` call had no effect, so we expand the buffer and try again netWriteBuffer = Utils.ensureCapacity(netWriteBuffer, netWriteBufferSize()); netWriteBuffer.position(netWriteBuffer.limit()); } else if (wrapResult.getStatus() == Status.BUFFER_UNDERFLOW) { throw new IllegalStateException("SSL BUFFER_UNDERFLOW during write"); } else if (wrapResult.getStatus() == Status.CLOSED) { throw new EOFException(); } } return written; } /** * Writes a sequence of bytes to this channel from the subsequence of the given buffers. * * @param srcs The buffers from which bytes are to be retrieved * @param offset The offset within the buffer array of the first buffer from which bytes are to be retrieved; must be non-negative and no larger than srcs.length. * @param length - The maximum number of buffers to be accessed; must be non-negative and no larger than srcs.length - offset. * @return returns no.of bytes written , possibly zero. * @throws IOException If some other I/O error occurs */ @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) throw new IndexOutOfBoundsException(); int totalWritten = 0; int i = offset; while (i < length) { if (srcs[i].hasRemaining() || hasPendingWrites()) { int written = write(srcs[i]); if (written > 0) { totalWritten += written; } } if (!srcs[i].hasRemaining() && !hasPendingWrites()) { i++; } else { // if we are unable to write the current buffer to socketChannel we should break, // as we might have reached max socket send buffer size. break; } } return totalWritten; } /** * Writes a sequence of bytes to this channel from the given buffers. * * @param srcs The buffers from which bytes are to be retrieved * @return returns no.of bytes consumed by SSLEngine.wrap , possibly zero. * @throws IOException If some other I/O error occurs */ @Override public long write(ByteBuffer[] srcs) throws IOException { return write(srcs, 0, srcs.length); } /** * SSLSession's peerPrincipal for the remote host. * @return Principal */ public Principal peerPrincipal() { try { return sslEngine.getSession().getPeerPrincipal(); } catch (SSLPeerUnverifiedException se) { log.debug("SSL peer is not authenticated, returning ANONYMOUS instead"); return KafkaPrincipal.ANONYMOUS; } } /** * returns an SSL Session after the handshake is established * throws IllegalStateException if the handshake is not established */ public SSLSession sslSession() throws IllegalStateException { return sslEngine.getSession(); } /** * Adds interestOps to SelectionKey of the TransportLayer * @param ops SelectionKey interestOps */ @Override public void addInterestOps(int ops) { if (!key.isValid()) throw new CancelledKeyException(); else if (!ready()) throw new IllegalStateException("handshake is not completed"); key.interestOps(key.interestOps() | ops); } /** * removes interestOps to SelectionKey of the TransportLayer * @param ops SelectionKey interestOps */ @Override public void removeInterestOps(int ops) { if (!key.isValid()) throw new CancelledKeyException(); else if (!ready()) throw new IllegalStateException("handshake is not completed"); key.interestOps(key.interestOps() & ~ops); } /** * returns delegatedTask for the SSLEngine. */ protected Runnable delegatedTask() { return sslEngine.getDelegatedTask(); } /** * transfers appReadBuffer contents (decrypted data) into dst bytebuffer * @param dst ByteBuffer */ private int readFromAppBuffer(ByteBuffer dst) { appReadBuffer.flip(); int remaining = Math.min(appReadBuffer.remaining(), dst.remaining()); if (remaining > 0) { int limit = appReadBuffer.limit(); appReadBuffer.limit(appReadBuffer.position() + remaining); dst.put(appReadBuffer); appReadBuffer.limit(limit); } appReadBuffer.compact(); return remaining; } protected int netReadBufferSize() { return sslEngine.getSession().getPacketBufferSize(); } protected int netWriteBufferSize() { return sslEngine.getSession().getPacketBufferSize(); } protected int applicationBufferSize() { return sslEngine.getSession().getApplicationBufferSize(); } protected ByteBuffer netReadBuffer() { return netReadBuffer; } // Visibility for testing protected ByteBuffer appReadBuffer() { return appReadBuffer; } /** * SSL exceptions are propagated as authentication failures so that clients can avoid * retries and report the failure. If `flush` is true, exceptions are propagated after * any pending outgoing bytes are flushed to ensure that the peer is notified of the failure. */ private void handshakeFailure(SSLException sslException, boolean flush) throws IOException { //Release all resources such as internal buffers that SSLEngine is managing sslEngine.closeOutbound(); try { sslEngine.closeInbound(); } catch (SSLException e) { log.debug("SSLEngine.closeInBound() raised an exception.", e); } state = State.HANDSHAKE_FAILED; handshakeException = new SslAuthenticationException("SSL handshake failed", sslException); // Attempt to flush any outgoing bytes. If flush doesn't complete, delay exception handling until outgoing bytes // are flushed. If write fails because remote end has closed the channel, log the I/O exception and continue to // handle the handshake failure as an authentication exception. try { if (!flush || flush(netWriteBuffer)) throw handshakeException; } catch (IOException e) { log.debug("Failed to flush all bytes before closing channel", e); throw handshakeException; } } // SSL handshake failures are typically thrown as SSLHandshakeException, SSLProtocolException, // SSLPeerUnverifiedException or SSLKeyException if the cause is known. These exceptions indicate // authentication failures (e.g. configuration errors) which should not be retried. But the SSL engine // may also throw exceptions using the base class SSLException in a few cases: // a) If there are no matching ciphers or TLS version or the private key is invalid, client will be // unable to process the server message and an SSLException is thrown: // javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection? // b) If server closes the connection gracefully during handshake, client may receive close_notify // and and an SSLException is thrown: // javax.net.ssl.SSLException: Received close_notify during handshake // We want to handle a) as a non-retriable SslAuthenticationException and b) as a retriable IOException. // To do this we need to rely on the exception string. Since it is safer to throw a retriable exception // when we are not sure, we will treat only the first exception string as a handshake exception. private void maybeProcessHandshakeFailure(SSLException sslException, boolean flush, IOException ioException) throws IOException { if (sslException instanceof SSLHandshakeException || sslException instanceof SSLProtocolException || sslException instanceof SSLPeerUnverifiedException || sslException instanceof SSLKeyException || sslException.getMessage().contains("Unrecognized SSL message") || sslException.getMessage().contains("Received fatal alert: ")) handshakeFailure(sslException, flush); else if (ioException == null) throw sslException; else { log.debug("SSLException while unwrapping data after IOException, original IOException will be propagated", sslException); throw ioException; } } // If handshake has already failed, throw the authentication exception. private void maybeThrowSslAuthenticationException() { if (handshakeException != null) throw handshakeException; } @Override public boolean isMute() { return key.isValid() && (key.interestOps() & SelectionKey.OP_READ) == 0; } @Override public boolean hasBytesBuffered() { return hasBytesBuffered; } // Update `hasBytesBuffered` status. If any bytes were read from the network or // if data was returned from read, `hasBytesBuffered` is set to true if any buffered // data is still remaining. If not, `hasBytesBuffered` is set to false since no progress // can be made until more data is available to read from the network. private void updateBytesBuffered(boolean madeProgress) { if (madeProgress) hasBytesBuffered = netReadBuffer.position() != 0 || appReadBuffer.position() != 0; else hasBytesBuffered = false; } @Override public long transferFrom(FileChannel fileChannel, long position, long count) throws IOException { if (state == State.CLOSING) throw closingException(); if (state != State.READY) return 0; if (!flush(netWriteBuffer)) return 0; long channelSize = fileChannel.size(); if (position > channelSize) return 0; int totalBytesToWrite = (int) Math.min(Math.min(count, channelSize - position), Integer.MAX_VALUE); if (fileChannelBuffer == null) { // Pick a size that allows for reasonably efficient disk reads, keeps the memory overhead per connection // manageable and can typically be drained in a single `write` call. The `netWriteBuffer` is typically 16k // and the socket send buffer is 100k by default, so 32k is a good number given the mentioned trade-offs. int transferSize = 32768; // Allocate a direct buffer to avoid one heap to heap buffer copy. SSLEngine copies the source // buffer (fileChannelBuffer) to the destination buffer (netWriteBuffer) and then encrypts in-place. // FileChannel.read() to a heap buffer requires a copy from a direct buffer to a heap buffer, which is not // useful here. fileChannelBuffer = ByteBuffer.allocateDirect(transferSize); // The loop below drains any remaining bytes from the buffer before reading from disk, so we ensure there // are no remaining bytes in the empty buffer fileChannelBuffer.position(fileChannelBuffer.limit()); } int totalBytesWritten = 0; long pos = position; try { while (totalBytesWritten < totalBytesToWrite) { if (!fileChannelBuffer.hasRemaining()) { fileChannelBuffer.clear(); int bytesRemaining = totalBytesToWrite - totalBytesWritten; if (bytesRemaining < fileChannelBuffer.limit()) fileChannelBuffer.limit(bytesRemaining); int bytesRead = fileChannel.read(fileChannelBuffer, pos); if (bytesRead <= 0) break; fileChannelBuffer.flip(); } int networkBytesWritten = write(fileChannelBuffer); totalBytesWritten += networkBytesWritten; // In the case of a partial write we only return the written bytes to the caller. As a result, the // `position` passed in the next `transferFrom` call won't include the bytes remaining in // `fileChannelBuffer`. By draining `fileChannelBuffer` first, we ensure we update `pos` before // we invoke `fileChannel.read`. if (fileChannelBuffer.hasRemaining()) break; pos += networkBytesWritten; } return totalBytesWritten; } catch (IOException e) { if (totalBytesWritten > 0) return totalBytesWritten; throw e; } } }
{ "content_hash": "049d98dd322d8c26fd1be6715833fada", "timestamp": "", "source": "github", "line_count": 991, "max_line_length": 170, "avg_line_length": 44.909182643794146, "alnum_prop": 0.6113021008875408, "repo_name": "sslavic/kafka", "id": "0b11cd18b4de9abf24fb4b95821bccdb26ed73c0", "size": "45303", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "clients/src/main/java/org/apache/kafka/common/network/SslTransportLayer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "26633" }, { "name": "Dockerfile", "bytes": "5117" }, { "name": "HTML", "bytes": "3739" }, { "name": "Java", "bytes": "14966996" }, { "name": "Python", "bytes": "802091" }, { "name": "Scala", "bytes": "5802403" }, { "name": "Shell", "bytes": "94955" }, { "name": "XSLT", "bytes": "7116" } ], "symlink_target": "" }
#include "tensorflow_serving/model_servers/platform_config_util.h" #include "google/protobuf/any.pb.h" #include "tensorflow_serving/model_servers/model_platform_types.h" #include "tensorflow_serving/servables/tensorflow/saved_model_bundle_source_adapter.pb.h" namespace tensorflow { namespace serving { PlatformConfigMap CreateTensorFlowPlatformConfigMap( const SessionBundleConfig& session_bundle_config) { PlatformConfigMap platform_config_map; ::google::protobuf::Any source_adapter_config; SavedModelBundleSourceAdapterConfig saved_model_bundle_source_adapter_config; *saved_model_bundle_source_adapter_config.mutable_legacy_config() = session_bundle_config; source_adapter_config.PackFrom(saved_model_bundle_source_adapter_config); (*(*platform_config_map.mutable_platform_configs())[kTensorFlowModelPlatform] .mutable_source_adapter_config()) = source_adapter_config; return platform_config_map; } } // namespace serving } // namespace tensorflow
{ "content_hash": "ad37111d8b3a2f59f022169613502119", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 89, "avg_line_length": 38.19230769230769, "alnum_prop": 0.7865055387713998, "repo_name": "tensorflow/serving", "id": "a0906d663283b39a2123f9bd7d241c84fae37e6d", "size": "1649", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow_serving/model_servers/platform_config_util.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5556" }, { "name": "C++", "bytes": "2368802" }, { "name": "Dockerfile", "bytes": "2057" }, { "name": "Python", "bytes": "119915" }, { "name": "Shell", "bytes": "27873" }, { "name": "Starlark", "bytes": "172729" } ], "symlink_target": "" }
<?php // Consumer Key define('CONSUMER_KEY', ''); define('CONSUMER_SECRET', ''); // User Access Token define('ACCESS_TOKEN', ''); define('ACCESS_SECRET', ''); ?>
{ "content_hash": "3bed38d660bc084a593f54f8fbb57b15", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 34, "avg_line_length": 20.666666666666668, "alnum_prop": 0.543010752688172, "repo_name": "Edelskjold/Edelskjold.dk", "id": "7597cb4c783082d59b91d992a1385004d3fa4734", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/config.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "99471" }, { "name": "JavaScript", "bytes": "18934" }, { "name": "PHP", "bytes": "52363" } ], "symlink_target": "" }
<?php namespace Smartbox\Integration\FrameworkBundle\Core\Messages; use Smartbox\CoreBundle\Type\SerializableArray; use Smartbox\Integration\FrameworkBundle\Core\Exchange; use Smartbox\Integration\FrameworkBundle\Core\Messages\Traits\HasProcessingContext; /** * Class ErrorExchangeEnvelope. */ abstract class ErrorExchangeEnvelope extends ExchangeEnvelope { use HasProcessingContext; const HEADER_CREATED_AT = 'created_at'; const HEADER_ERROR_MESSAGE = 'error_message'; const HEADER_ERROR_PROCESSOR_ID = 'error_processor_id'; const HEADER_ERROR_PROCESSOR_DESCRIPTION = 'error_processor_description'; const HEADER_ERROR_NUM_RETRY = 'error_num_retry'; /** * FailedExchangeEnvelope constructor. * * @param Exchange|null $exchange * @param SerializableArray|null $processingContext */ public function __construct(Exchange $exchange, SerializableArray $processingContext = null) { parent::__construct($exchange); $this->processingContext = $processingContext; } }
{ "content_hash": "c3110768137a958d6303c68cf59f1a66", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 96, "avg_line_length": 32, "alnum_prop": 0.7329545454545454, "repo_name": "smartboxgroup/integration-framework-bundle", "id": "82f682d615963472eaf9fb2da2ebe014d31b77bc", "size": "1056", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Messages/ErrorExchangeEnvelope.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "553" }, { "name": "PHP", "bytes": "832849" }, { "name": "Shell", "bytes": "297" } ], "symlink_target": "" }
class CreateDesiginations < ActiveRecord::Migration[5.0] def change create_table :desiginations do |t| t.string :name t.timestamps end end end
{ "content_hash": "ffed752baf2c793158f755a7a3223479", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 56, "avg_line_length": 18.666666666666668, "alnum_prop": 0.6785714285714286, "repo_name": "jeyavelnkl/jel_apps", "id": "8010be95e8aff5b7af71fee8a1a8e51f4372c89e", "size": "168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VLS_V1_SDT/db/migrate/20170301122605_create_desiginations.rb", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1360" }, { "name": "CSS", "bytes": "243399" }, { "name": "CoffeeScript", "bytes": "18561" }, { "name": "Gherkin", "bytes": "126424" }, { "name": "HTML", "bytes": "956511" }, { "name": "JavaScript", "bytes": "695824" }, { "name": "Ruby", "bytes": "2815275" }, { "name": "Shell", "bytes": "1249" } ], "symlink_target": "" }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; namespace Microsoft.Azure.Mobile.Server { /// <summary> /// The "aps" property contains the definition of a notification targeting Apple Push Notification Service (APNS). It is intended /// to be used from the <see cref="ApplePushMessage"/> class. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is a property bag.")] [Serializable] public class ApsProperties : Dictionary<string, object> { private const string AlertKey = "alert"; private const string BadgeKey = "badge"; private const string SoundKey = "sound"; private const string ContentAvailableKey = "content-available"; /// <summary> /// Initializes a new instance of the <see cref="ApsProperties"/> class. /// </summary> public ApsProperties() : base(StringComparer.OrdinalIgnoreCase) { } /// <summary> /// Initializes a new instance of the <see cref="ApsProperties"/> class with the specified serialization information and streaming context. /// </summary> /// <param name="info">A <see cref="SerializationInfo"/> containing information about the <see cref="ApsProperties"/> to be initialized.</param> /// <param name="context">A <see cref="StreamingContext"/> that indicates the source destination and context information of a serialized stream.</param> protected ApsProperties(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// The alert message as a single string. For more complex alert message options, please use <see cref="M:AlertProperties"/>. /// </summary> public string Alert { get { return this.GetValueOrDefault<string>(AlertKey); } set { this.SetOrClearValue(AlertKey, value); } } /// <summary> /// The alert message as a dictionary with additional properties describing the alert such as localization information, which image to display, etc. /// If the alert is simply a string then please use <see cref="M:Alert"/>. /// </summary> public AlertProperties AlertProperties { get { AlertProperties alerts = this.GetValueOrDefault<AlertProperties>(AlertKey); if (alerts == null) { alerts = new AlertProperties(); this[AlertKey] = alerts; } return alerts; } } /// <summary> /// The number to display as the badge of the application icon. If this property is absent, the badge is not changed. /// To remove the badge, set the value of this property to 0. /// </summary> public int? Badge { get { return this.GetValueOrDefault<int?>(BadgeKey); } set { this.SetOrClearValue(BadgeKey, value); } } /// <summary> /// The name of a sound file in the application bundle. The sound in this file is played as an alert. If the sound file /// doesn’t exist or default is specified as the value, the default alert sound is played. The audio must be in one /// of the audio data formats that are compatible with system sounds; /// </summary> public string Sound { get { return this.GetValueOrDefault<string>(SoundKey); } set { this.SetOrClearValue(SoundKey, value); } } /// <summary> /// Provide this key with a value of 1 to indicate that new content is available. This is used to support /// Newsstand apps and background content downloads. /// </summary> public bool ContentAvailable { get { return this.GetValueOrDefault<bool>(ContentAvailableKey); } set { this.SetOrClearValue(ContentAvailableKey, value); } } } }
{ "content_hash": "0f241e606408c320d1073f1f2a1e4a7e", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 160, "avg_line_length": 36.246153846153845, "alnum_prop": 0.5534804753820034, "repo_name": "dhei/azure-mobile-apps-net-server", "id": "e1f513360738bed2cf724707952a739509fdc3a8", "size": "4716", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/Microsoft.Azure.Mobile.Server.Notifications/ApsProperties.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1419388" }, { "name": "HTML", "bytes": "155382" }, { "name": "Roff", "bytes": "32858" }, { "name": "SQLPL", "bytes": "2430" }, { "name": "Visual Basic", "bytes": "13204" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../lib/typed_class' require File.dirname(__FILE__) + '/lib/test_util.rb'
{ "content_hash": "8a16262ddbe0180e0259719bd899e6ed", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 54, "avg_line_length": 54, "alnum_prop": 0.6481481481481481, "repo_name": "mbryzek/typed-class", "id": "0f752355f402ae752683e71d4ef0713a4be78671", "size": "108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/init.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "20888" } ], "symlink_target": "" }
""" Some handy utility functions used by several classes. """ import re import urllib import urllib2 import subprocess import StringIO import time import logging.handlers import boto import tempfile import smtplib import datetime from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import formatdate from email import Encoders try: import hashlib _hashfn = hashlib.sha512 except ImportError: import md5 _hashfn = md5.md5 METADATA_PREFIX = 'x-amz-meta-' AMAZON_HEADER_PREFIX = 'x-amz-' # generates the aws canonical string for the given parameters def canonical_string(method, path, headers, expires=None): interesting_headers = {} for key in headers: lk = key.lower() if lk in ['content-md5', 'content-type', 'date'] or lk.startswith(AMAZON_HEADER_PREFIX): interesting_headers[lk] = headers[key].strip() # these keys get empty strings if they don't exist if not interesting_headers.has_key('content-type'): interesting_headers['content-type'] = '' if not interesting_headers.has_key('content-md5'): interesting_headers['content-md5'] = '' # just in case someone used this. it's not necessary in this lib. if interesting_headers.has_key('x-amz-date'): interesting_headers['date'] = '' # if you're using expires for query string auth, then it trumps date # (and x-amz-date) if expires: interesting_headers['date'] = str(expires) sorted_header_keys = interesting_headers.keys() sorted_header_keys.sort() buf = "%s\n" % method for key in sorted_header_keys: val = interesting_headers[key] if key.startswith(AMAZON_HEADER_PREFIX): buf += "%s:%s\n" % (key, val) else: buf += "%s\n" % val # don't include anything after the first ? in the resource... buf += "%s" % path.split('?')[0] # ...unless there is an acl or torrent parameter if re.search("[&?]acl($|=|&)", path): buf += "?acl" elif re.search("[&?]logging($|=|&)", path): buf += "?logging" elif re.search("[&?]torrent($|=|&)", path): buf += "?torrent" elif re.search("[&?]location($|=|&)", path): buf += "?location" elif re.search("[&?]requestPayment($|=|&)", path): buf += "?requestPayment" elif re.search("[&?]versions($|=|&)", path): buf += "?versions" elif re.search("[&?]versioning($|=|&)", path): buf += "?versioning" else: m = re.search("[&?]versionId=([^&]+)($|=|&)", path) if m: buf += '?versionId=' + m.group(1) return buf def merge_meta(headers, metadata): final_headers = headers.copy() for k in metadata.keys(): if k.lower() in ['cache-control', 'content-md5', 'content-type', 'content-encoding', 'content-disposition', 'date', 'expires']: final_headers[k] = metadata[k] else: final_headers[METADATA_PREFIX + k] = metadata[k] return final_headers def get_aws_metadata(headers): metadata = {} for hkey in headers.keys(): if hkey.lower().startswith(METADATA_PREFIX): val = urllib.unquote_plus(headers[hkey]) metadata[hkey[len(METADATA_PREFIX):]] = unicode(val, 'utf-8') del headers[hkey] return metadata def retry_url(url, retry_on_404=True): for i in range(0, 10): try: req = urllib2.Request(url) resp = urllib2.urlopen(req) return resp.read() except urllib2.HTTPError, e: # in 2.6 you use getcode(), in 2.5 and earlier you use code if hasattr(e, 'getcode'): code = e.getcode() else: code = e.code if code == 404 and not retry_on_404: return '' except: pass boto.log.exception('Caught exception reading instance data') time.sleep(2**i) boto.log.error('Unable to read instance data, giving up') return '' def _get_instance_metadata(url): d = {} data = retry_url(url) if data: fields = data.split('\n') for field in fields: if field.endswith('/'): d[field[0:-1]] = _get_instance_metadata(url + field) else: p = field.find('=') if p > 0: key = field[p+1:] resource = field[0:p] + '/openssh-key' else: key = resource = field val = retry_url(url + resource) p = val.find('\n') if p > 0: val = val.split('\n') d[key] = val return d def get_instance_metadata(version='latest'): """ Returns the instance metadata as a nested Python dictionary. Simple values (e.g. local_hostname, hostname, etc.) will be stored as string values. Values such as ancestor-ami-ids will be stored in the dict as a list of string values. More complex fields such as public-keys and will be stored as nested dicts. """ url = 'http://169.254.169.254/%s/meta-data/' % version return _get_instance_metadata(url) def get_instance_userdata(version='latest', sep=None): url = 'http://169.254.169.254/%s/user-data' % version user_data = retry_url(url, retry_on_404=False) if user_data: if sep: l = user_data.split(sep) user_data = {} for nvpair in l: t = nvpair.split('=') user_data[t[0].strip()] = t[1].strip() return user_data ISO8601 = '%Y-%m-%dT%H:%M:%SZ' def get_ts(ts=None): if not ts: ts = time.gmtime() return time.strftime(ISO8601, ts) def parse_ts(ts): return datetime.datetime.strptime(ts, ISO8601) def find_class(module_name, class_name=None): if class_name: module_name = "%s.%s" % (module_name, class_name) modules = module_name.split('.') c = None try: for m in modules[1:]: if c: c = getattr(c, m) else: c = getattr(__import__(".".join(modules[0:-1])), m) return c except: return None def update_dme(username, password, dme_id, ip_address): """ Update your Dynamic DNS record with DNSMadeEasy.com """ dme_url = 'https://www.dnsmadeeasy.com/servlet/updateip' dme_url += '?username=%s&password=%s&id=%s&ip=%s' s = urllib2.urlopen(dme_url % (username, password, dme_id, ip_address)) return s.read() def fetch_file(uri, file=None, username=None, password=None): """ Fetch a file based on the URI provided. If you do not pass in a file pointer a tempfile.NamedTemporaryFile, or None if the file could not be retrieved is returned. The URI can be either an HTTP url, or "s3://bucket_name/key_name" """ boto.log.info('Fetching %s' % uri) if file == None: file = tempfile.NamedTemporaryFile() try: if uri.startswith('s3://'): bucket_name, key_name = uri[len('s3://'):].split('/', 1) c = boto.connect_s3() bucket = c.get_bucket(bucket_name) key = bucket.get_key(key_name) key.get_contents_to_file(file) else: if username and password: passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, uri, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) s = urllib2.urlopen(uri) file.write(s.read()) file.seek(0) except: raise boto.log.exception('Problem Retrieving file: %s' % uri) file = None return file class ShellCommand(object): def __init__(self, command, wait=True): self.exit_code = 0 self.command = command self.log_fp = StringIO.StringIO() self.wait = wait self.run() def run(self): boto.log.info('running:%s' % self.command) self.process = subprocess.Popen(self.command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if(self.wait): while self.process.poll() == None: time.sleep(1) t = self.process.communicate() self.log_fp.write(t[0]) self.log_fp.write(t[1]) boto.log.info(self.log_fp.getvalue()) self.exit_code = self.process.returncode return self.exit_code def setReadOnly(self, value): raise AttributeError def getStatus(self): return self.exit_code status = property(getStatus, setReadOnly, None, 'The exit code for the command') def getOutput(self): return self.log_fp.getvalue() output = property(getOutput, setReadOnly, None, 'The STDIN and STDERR output of the command') class AuthSMTPHandler(logging.handlers.SMTPHandler): """ This class extends the SMTPHandler in the standard Python logging module to accept a username and password on the constructor and to then use those credentials to authenticate with the SMTP server. To use this, you could add something like this in your boto config file: [handler_hand07] class=boto.utils.AuthSMTPHandler level=WARN formatter=form07 args=('localhost', 'username', 'password', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') """ def __init__(self, mailhost, username, password, fromaddr, toaddrs, subject): """ Initialize the handler. We have extended the constructor to accept a username/password for SMTP authentication. """ logging.handlers.SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject) self.username = username self.password = password def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. It would be really nice if I could add authorization to this class without having to resort to cut and paste inheritance but, no. """ try: port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port) smtp.login(self.username, self.password) msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, ','.join(self.toaddrs), self.getSubject(record), formatdate(), msg) smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) class LRUCache(dict): """A dictionary-like object that stores only a certain number of items, and discards its least recently used item when full. >>> cache = LRUCache(3) >>> cache['A'] = 0 >>> cache['B'] = 1 >>> cache['C'] = 2 >>> len(cache) 3 >>> cache['A'] 0 Adding new items to the cache does not increase its size. Instead, the least recently used item is dropped: >>> cache['D'] = 3 >>> len(cache) 3 >>> 'B' in cache False Iterating over the cache returns the keys, starting with the most recently used: >>> for key in cache: ... print key D A C This code is based on the LRUCache class from Genshi which is based on Mighty's LRUCache from ``myghtyutils.util``, written by Mike Bayer and released under the MIT license (Genshi uses the BSD License). See: http://svn.myghty.org/myghtyutils/trunk/lib/myghtyutils/util.py """ class _Item(object): def __init__(self, key, value): self.previous = self.next = None self.key = key self.value = value def __repr__(self): return repr(self.value) def __init__(self, capacity): self._dict = dict() self.capacity = capacity self.head = None self.tail = None def __contains__(self, key): return key in self._dict def __iter__(self): cur = self.head while cur: yield cur.key cur = cur.next def __len__(self): return len(self._dict) def __getitem__(self, key): item = self._dict[key] self._update_item(item) return item.value def __setitem__(self, key, value): item = self._dict.get(key) if item is None: item = self._Item(key, value) self._dict[key] = item self._insert_item(item) else: item.value = value self._update_item(item) self._manage_size() def __repr__(self): return repr(self._dict) def _insert_item(self, item): item.previous = None item.next = self.head if self.head is not None: self.head.previous = item else: self.tail = item self.head = item self._manage_size() def _manage_size(self): while len(self._dict) > self.capacity: del self._dict[self.tail.key] if self.tail != self.head: self.tail = self.tail.previous self.tail.next = None else: self.head = self.tail = None def _update_item(self, item): if self.head == item: return previous = item.previous previous.next = item.next if item.next is not None: item.next.previous = previous else: self.tail = previous item.previous = None item.next = self.head self.head.previous = self.head = item class Password(object): """ Password object that stores itself as SHA512 hashed. """ def __init__(self, str=None): """ Load the string from an initial value, this should be the raw SHA512 hashed password """ self.str = str def set(self, value): self.str = _hashfn(value).hexdigest() def __str__(self): return str(self.str) def __eq__(self, other): if other == None: return False return str(_hashfn(other).hexdigest()) == str(self.str) def __len__(self): if self.str: return len(self.str) else: return 0 def notify(subject, body=None, html_body=None, to_string=None, attachments=[], append_instance_id=True): if append_instance_id: subject = "[%s] %s" % (boto.config.get_value("Instance", "instance-id"), subject) if not to_string: to_string = boto.config.get_value('Notification', 'smtp_to', None) if to_string: try: from_string = boto.config.get_value('Notification', 'smtp_from', 'boto') msg = MIMEMultipart() msg['From'] = from_string msg['To'] = to_string msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject if body: msg.attach(MIMEText(body)) if html_body: part = MIMEBase('text', 'html') part.set_payload(html_body) Encoders.encode_base64(part) msg.attach(part) for part in attachments: msg.attach(part) smtp_host = boto.config.get_value('Notification', 'smtp_host', 'localhost') # Alternate port support if boto.config.get_value("Notification", "smtp_port"): server = smtplib.SMTP(smtp_host, int(boto.config.get_value("Notification", "smtp_port"))) else: server = smtplib.SMTP(smtp_host) # TLS support if boto.config.getbool("Notification", "smtp_tls"): server.ehlo() server.starttls() server.ehlo() smtp_user = boto.config.get_value('Notification', 'smtp_user', '') smtp_pass = boto.config.get_value('Notification', 'smtp_pass', '') if smtp_user: server.login(smtp_user, smtp_pass) server.sendmail(from_string, to_string, msg.as_string()) server.quit() except: boto.log.exception('notify failed')
{ "content_hash": "3aeb59d987f21da05e53231f94a1323f", "timestamp": "", "source": "github", "line_count": 527, "max_line_length": 105, "avg_line_length": 31.874762808349146, "alnum_prop": 0.5601857363971902, "repo_name": "sorenh/cc", "id": "255d42f6419b509881026ee7275bd346a318179b", "size": "18545", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/boto/boto/utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "707" }, { "name": "Python", "bytes": "398663" }, { "name": "Shell", "bytes": "12374" } ], "symlink_target": "" }
module BeerMapping class LocCity < Location def all(params={}) get('locations', params).collection end def find(id, params={}) get('location/%s' % id, params).data end end end
{ "content_hash": "4d5941f385fe97bb1fbab157aa01e3a3", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 39, "avg_line_length": 17.545454545454547, "alnum_prop": 0.6632124352331606, "repo_name": "jmiramant/beer_mapping", "id": "8614c075a5b5fe53191baa6d381a3083c6427ca8", "size": "193", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/beer_mapping/requests/locquery.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-machine-learning-encrypted-workspace/PublicLastTestDate.svg) ![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-machine-learning-encrypted-workspace/PublicDeployment.svg) ![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-machine-learning-encrypted-workspace/FairfaxLastTestDate.svg) ![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-machine-learning-encrypted-workspace/FairfaxDeployment.svg) ![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-machine-learning-encrypted-workspace/BestPracticeResult.svg) ![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-machine-learning-encrypted-workspace/CredScanResult.svg) [![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-machine-learning-encrypted-workspace%2Fazuredeploy.json) [![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-machine-learning-encrypted-workspace%2Fazuredeploy.json) This template creates an Azure Machine Learning workspace with the following configurations: * confidential_data: Enabling this turns on the following behavior in your Azure Machine Learning workspace: * Starts encrypting the local scratch disk for Azure Machine Learning compute clusters, providing you have not created any previous clusters in your subscription. If you have previously created a cluster in the subscription, open a support ticket to have encryption of the scratch disk enabled for your compute clusters. * Cleans up the local scratch disk between runs. * Securely passes credentials for the storage account, container registry, and SSH account from the execution layer to your compute clusters by using key vault. * Enables IP filtering to ensure the underlying batch pools cannot be called by any external services other than AzureMachineLearningService. For more information,, see [encryption at rest](https://docs.microsoft.com/azure/machine-learning/concept-enterprise-security#encryption-at-rest). * encryption_status: Enables you to use your own (customer-managed) key to [encrypt the Azure Cosmos DB instance](https://docs.microsoft.com/azure/machine-learning/concept-enterprise-security#azure-cosmos-db) used by the workspace. * cmk_keyvault: The Azure Resource Manager ID of an existing Azure Key Vault. This key vault must contain an encryption key, which is used to encrypt the Cosmos DB instance. * resource_cmk_uri: The URI of the encryption key stored in the key vault. When using a customer-managed key, Azure Machine Learning creates a secondary resource group which contains the Cosmos DB instance. For more information, see [encryption at rest - Cosmos DB](https://docs.microsoft.com/en-us/azure/machine-learning/concept-enterprise-security#encryption-at-rest). ## Setup Before using this template, you must meet the following requirements: * The __Azure Machine Learning__ service principal must have __contributor__ access to your Azure subscription. * You must have an existing Azure Key Vault that contains an encryption key. * The Azure Key Vault must exist in the same Azure region where you will create the Azure Machine Learning workspace. * You must have an access policy in Azure Key Vault that grants __get__, __wrap__, and __unwrap__ access to the __Azure Cosmos DB__ application. ### Add Azure Machine Learning as a contributor To add the Azure Machine Learning service principal as a contributor to your subscription, use the following steps: 1. Use the [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli) or [Azure Powershell](https://docs.microsoft.com/powershell/azure/install-az-ps) to authenticate to get your subscription ID: Azure CLI ```Bash az account list --query '[].[name,id]' --output tsv ``` PowerShell ```powershell Get-AzSubscription ``` From the list of subscriptions, select the one you want to use and copy the subscription ID. 1. To get the object ID of the `Azure Machine Learning` service principal, use one off the following commands: Azure CLI ```Bash az ad sp list --display-name "Azure Machine Learning" --query '[].[appDisplayName,objectId]' --output tsv ``` PowerShell ```powershell Get-AzADServicePrincipal --DisplayName "Azure Machine Learning" | select-object DisplayName, Id ``` Save the ID for the `Azure Machine Learning` entry. 1. To add the service principal as a contributor to your subscription, use one of the following commands. Replace the `<subscription-ID>` with your subscription ID and `<object-ID>` with the ID for the service principal: Azure CLI ```Bash az role assignment create --role 'Contributor' --assignee-object-id <object-ID> --subscription <subscription-ID> ``` PowerShell ```powershell New-AzRoleAssignment --ObjectId <object-ID> --RoleDefinitionName "Contributor" -Scope /subscriptions/<subscription-ID> ``` ### Add a key for encryption To generate a key in an existing Azure Key Vault, use the [prereq template](prereqs/prereq.azuredeploy.json) provide with this sample or one of the following commands. Replace `<keyvault-name>` with the name of the key vault. Replace `<key-name>` with the name to use for the key: Azure CLI ```Bash az keyvault key create --vault-name <keyvault-name> --name <key-name> --protection software ``` PowerShell ```powershell Add-AzKeyVaultKey -VaultName <keyvault-name> -Name <key-name> -Destination 'Software' ``` ### Enable customer-managged keys for Azure Cosmos DB See data encryption section of [Enterprise Security for Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/concept-enterprise-security#data-encryption) and [Configure customer-managed keys for your AzureCosmos account](https://docs.microsoft.com/azure/cosmos-db/how-to-setup-cmk). ### Add an access policy to the key vault To add an access policy for Azure Cosmos DB to the key vault, use the following steps: 1. To get the object ID of the `Azure Cosmos DB` service principal, use one off the following commands: Azure CLI ```Bash az ad sp list --display-name "Azure Cosmos DB" --query '[].[appDisplayName,objectId]' --output tsv ``` PowerShell ```powershell Get-AzADServicePrincipal --DisplayName "Azure Cosmos DB" | select-object DisplayName, Id ``` Save the ID for the `Azure Cosmos DB` entry. 1. To set the policy, use the following command. Replace `<keyvault-name>` with the name of the key vault. Replace `<object-ID>` with the ID for the service principal: Azure CLI ```bash az keyvault set-policy --name <keyvault-name> --object-id <object-ID> --key-permissions get unwrapKey wrapKey ``` PowerShell ```powershell Set-AzKeyVaultAccessPolicy -VaultName <keyvault-name> -ObjectId <object-ID> -PermissionsToKeys get, unwrapKey, wrapKey ``` ### Look up cmk_keyvault and resource_cmk_uri Use this command to see cmk_keyvault. Azure CLI: Id at the beginning of output is cmk_keyvault. Like this: /subscriptions/<subscripiton id>/resourceGroup/<rg name>/providers/Microsoft.KeyVault/vaults/<keyvault-name>. ```bash az keyvault show --name <keyvault-name> ``` PowerShell: Resource id is cmk_keyvault. Like this: /subscriptions/<subscripiton id>/resourceGroup/<rg name>/providers/Microsoft.KeyVault/vaults/<keyvault-name>. ```powershell Get-AzureRMKeyVault -VaultName '<keyvault-name>' ``` Use this command to see resource_cmk_uri. Azure CLI: kid is resource_cmk_uri. Like this: https://<keyvault-name>.vault.azure.net/keys/<key-name>/******. ```bash az keyvault key show --vault-name <keyvault-name> --name <key-name> ``` PowerShell: Id is resource_cmk_uri. Like this: https://<keyvault-name>.vault.azure.net/keys/<key-name>/******. ```powershell Get-AzureKeyVaultKey -VaultName '<keyvault-name>' -KeyName '<key-name>' ## More information * [Encryption at rest](https://docs.microsoft.com/azure/machine-learning/concept-enterprise-security#data-encryption) * [Configure customer-managed keys for Azure Cosmos](https://docs.microsoft.com/azure/cosmos-db/how-to-setup-cmk). `Tags: Azure Machine Learning, Machine Learning, encryption`
{ "content_hash": "43a34ec488c674b6f3a0130529963972", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 360, "avg_line_length": 49.33898305084746, "alnum_prop": 0.7740753463872667, "repo_name": "matt1883/azure-quickstart-templates", "id": "8a289ba00506d74e59db809ebfe76890da76cfbe", "size": "8790", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "201-machine-learning-encrypted-workspace/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "208" }, { "name": "Groovy", "bytes": "394" }, { "name": "JavaScript", "bytes": "18742" }, { "name": "PHP", "bytes": "1774" }, { "name": "PowerShell", "bytes": "203094" }, { "name": "Python", "bytes": "106152" }, { "name": "Shell", "bytes": "502622" } ], "symlink_target": "" }
package org.spongepowered.common.effect.particle; import com.google.common.base.MoreObjects; import org.spongepowered.api.effect.particle.ParticleOption; import org.spongepowered.common.SpongeCatalogType; import java.util.function.Function; import javax.annotation.Nullable; public class SpongeParticleOption<V> extends SpongeCatalogType implements ParticleOption<V> { private final String name; private final Class<V> valueType; @Nullable private final Function<V, IllegalArgumentException> valueValidator; public SpongeParticleOption(String id, String name, Class<V> valueType, @Nullable Function<V, IllegalArgumentException> valueValidator) { super(id); this.valueValidator = valueValidator; this.valueType = valueType; this.name = name; } public SpongeParticleOption(String id, String name, Class<V> valueType) { this(id, name, valueType, null); } @Nullable public IllegalArgumentException validateValue(V value) { if (this.valueValidator != null) { return this.valueValidator.apply(value); } return null; } @Override public Class<V> getValueType() { return this.valueType; } @Override public String getName() { return this.name; } @Override protected MoreObjects.ToStringHelper toStringHelper() { return super.toStringHelper() .omitNullValues() .add("valueType", this.valueType); } }
{ "content_hash": "59e80da5e7474387307ebafff6a92612", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 93, "avg_line_length": 27.672727272727272, "alnum_prop": 0.6826544021024967, "repo_name": "SpongePowered/SpongeCommon", "id": "9b07f3a1c5741db94ba032af5deb2fe65393213b", "size": "2769", "binary": false, "copies": "4", "ref": "refs/heads/stable-7", "path": "src/main/java/org/spongepowered/common/effect/particle/SpongeParticleOption.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "14153592" }, { "name": "Shell", "bytes": "1072" } ], "symlink_target": "" }