code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
Shoes.app width: 300, height: 300 do
fname = File.join(Shoes::DIR, 'static/shoes-icon.png')
background yellow..orange, angle: 90
border fname, strokewidth: 20, curve: 100
fill fname
nostroke
oval 100, 100, 100, 100
end
| thescientician/lightning-timer | samples/sample23.rb | Ruby | apache-2.0 | 231 |
#region License
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#endregion
using System;
namespace Cassandra.DataStax.Graph
{
/// <summary>
/// Represents an enum.
/// </summary>
public abstract class EnumWrapper : IEquatable<EnumWrapper>
{
/// <summary>
/// Gets the name of the enum.
/// </summary>
public string EnumName { get; }
/// <summary>
/// Gets the value of the enum.
/// </summary>
public string EnumValue { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EnumWrapper" /> class.
/// </summary>
/// <param name="enumName">The name of the enum.</param>
/// <param name="enumValue">The value of the enum.</param>
protected EnumWrapper(string enumName, string enumValue)
{
EnumName = enumName;
EnumValue = enumValue;
}
/// <inheritdoc />
public bool Equals(EnumWrapper other)
{
if (object.ReferenceEquals(null, other)) return false;
if (object.ReferenceEquals(this, other)) return true;
return string.Equals(EnumName, other.EnumName) && string.Equals(EnumValue, other.EnumValue);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (object.ReferenceEquals(null, obj)) return false;
if (object.ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((EnumWrapper) obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
return ((EnumName != null ? EnumName.GetHashCode() : 0) * 397) ^
(EnumValue != null ? EnumValue.GetHashCode() : 0);
}
}
}
} | maxwellb/csharp-driver | src/Cassandra/DataStax/Graph/EnumWrapper.cs | C# | apache-2.0 | 2,676 |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.machinelearning.model.transform;
import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.machinelearning.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;
/**
* DescribeBatchPredictionsRequest Marshaller
*/
public class DescribeBatchPredictionsRequestMarshaller
implements
Marshaller<Request<DescribeBatchPredictionsRequest>, DescribeBatchPredictionsRequest> {
private final SdkJsonProtocolFactory protocolFactory;
public DescribeBatchPredictionsRequestMarshaller(
SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DescribeBatchPredictionsRequest> marshall(
DescribeBatchPredictionsRequest describeBatchPredictionsRequest) {
if (describeBatchPredictionsRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<DescribeBatchPredictionsRequest> request = new DefaultRequest<DescribeBatchPredictionsRequest>(
describeBatchPredictionsRequest, "AmazonMachineLearning");
request.addHeader("X-Amz-Target",
"AmazonML_20141212.DescribeBatchPredictions");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = protocolFactory
.createGenerator();
jsonGenerator.writeStartObject();
if (describeBatchPredictionsRequest.getFilterVariable() != null) {
jsonGenerator.writeFieldName("FilterVariable").writeValue(
describeBatchPredictionsRequest.getFilterVariable());
}
if (describeBatchPredictionsRequest.getEQ() != null) {
jsonGenerator.writeFieldName("EQ").writeValue(
describeBatchPredictionsRequest.getEQ());
}
if (describeBatchPredictionsRequest.getGT() != null) {
jsonGenerator.writeFieldName("GT").writeValue(
describeBatchPredictionsRequest.getGT());
}
if (describeBatchPredictionsRequest.getLT() != null) {
jsonGenerator.writeFieldName("LT").writeValue(
describeBatchPredictionsRequest.getLT());
}
if (describeBatchPredictionsRequest.getGE() != null) {
jsonGenerator.writeFieldName("GE").writeValue(
describeBatchPredictionsRequest.getGE());
}
if (describeBatchPredictionsRequest.getLE() != null) {
jsonGenerator.writeFieldName("LE").writeValue(
describeBatchPredictionsRequest.getLE());
}
if (describeBatchPredictionsRequest.getNE() != null) {
jsonGenerator.writeFieldName("NE").writeValue(
describeBatchPredictionsRequest.getNE());
}
if (describeBatchPredictionsRequest.getPrefix() != null) {
jsonGenerator.writeFieldName("Prefix").writeValue(
describeBatchPredictionsRequest.getPrefix());
}
if (describeBatchPredictionsRequest.getSortOrder() != null) {
jsonGenerator.writeFieldName("SortOrder").writeValue(
describeBatchPredictionsRequest.getSortOrder());
}
if (describeBatchPredictionsRequest.getNextToken() != null) {
jsonGenerator.writeFieldName("NextToken").writeValue(
describeBatchPredictionsRequest.getNextToken());
}
if (describeBatchPredictionsRequest.getLimit() != null) {
jsonGenerator.writeFieldName("Limit").writeValue(
describeBatchPredictionsRequest.getLimit());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", jsonGenerator.getContentType());
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| nterry/aws-sdk-java | aws-java-sdk-machinelearning/src/main/java/com/amazonaws/services/machinelearning/model/transform/DescribeBatchPredictionsRequestMarshaller.java | Java | apache-2.0 | 5,541 |
/*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.guvnor.shared;
import org.jboss.errai.common.client.api.annotations.Portable;
@Portable
public class GeneralSettings {
private String name;
private boolean enabled;
private boolean socialLogin;
private boolean userRegistration;
private boolean resetPassword;
private boolean verifyEmail;
private boolean userAccountManagement;
private boolean cookieLoginAllowed;
private boolean requireSSL;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isSocialLogin() {
return socialLogin;
}
public void setSocialLogin(boolean socialLogin) {
this.socialLogin = socialLogin;
}
public boolean isUserRegistration() {
return userRegistration;
}
public void setUserRegistration(boolean userRegistration) {
this.userRegistration = userRegistration;
}
public boolean isResetPassword() {
return resetPassword;
}
public void setResetPassword(boolean resetPassword) {
this.resetPassword = resetPassword;
}
public boolean isVerifyEmail() {
return verifyEmail;
}
public void setVerifyEmail(boolean verifyEmail) {
this.verifyEmail = verifyEmail;
}
public boolean isUserAccountManagement() {
return userAccountManagement;
}
public void setUserAccountManagement(boolean userAccountManagement) {
this.userAccountManagement = userAccountManagement;
}
public boolean isCookieLoginAllowed() {
return cookieLoginAllowed;
}
public void setCookieLoginAllowed(boolean cookieLoginAllowed) {
this.cookieLoginAllowed = cookieLoginAllowed;
}
public boolean isRequireSSL() {
return requireSSL;
}
public void setRequireSSL(boolean requireSSL) {
this.requireSSL = requireSSL;
}
}
| hxf0801/guvnor | guvnor-webapp/src/main/java/org/guvnor/shared/GeneralSettings.java | Java | apache-2.0 | 2,624 |
package de.fau.cs.mad.fablab.android.view.fragments.projects;
import de.fau.cs.mad.fablab.android.model.entities.Cart;
public class CartClickedEvent {
private final Cart mCart;
public CartClickedEvent(Cart cart)
{
mCart = cart;
}
public Cart getCart()
{
return mCart;
}
}
| FAU-Inf2/fablab-android | app/src/main/java/de/fau/cs/mad/fablab/android/view/fragments/projects/CartClickedEvent.java | Java | apache-2.0 | 321 |
using System;
using System.IO;
using Metrics;
using Nancy.Routing;
namespace Nancy.Metrics
{
public static class NancyModuleMetricExtensions
{
public static void MetricForRequestTimeAndResponseSize(this INancyModule module, string metricName, string method, string pathPrefix)
{
module.MetricForRequestTimeAndResponseSize(metricName, module.MakePredicate(method, pathPrefix));
}
public static void MetricForRequestTimeAndResponseSize(this INancyModule module, string metricName, Predicate<RouteDescription> routePredicate)
{
module.MetricForRequestTime(metricName, routePredicate);
module.MetricForResponseSize(metricName, routePredicate);
}
public static void MetricForRequestTime(this INancyModule module, string metricName, string method, string pathPrefix)
{
module.MetricForRequestTime(metricName, module.MakePredicate(method, pathPrefix));
}
public static void MetricForRequestTime(this INancyModule module, string metricName, Predicate<RouteDescription> routePredicate)
{
var timer = NancyGlobalMetrics.NancyGlobalMetricsContext.Timer(metricName, Unit.Requests);
var key = "Metrics.Nancy.Request.Timer." + metricName;
module.Before.AddItemToStartOfPipeline(ctx =>
{
if (routePredicate(ctx.ResolvedRoute.Description))
{
ctx.Items[key] = timer.NewContext();
}
return null;
});
module.After.AddItemToEndOfPipeline(ctx =>
{
if (routePredicate(ctx.ResolvedRoute.Description))
{
using (ctx.Items[key] as IDisposable) { }
ctx.Items.Remove(key);
}
});
}
public static void MetricForResponseSize(this INancyModule module, string metricName, string method, string pathPrefix)
{
module.MetricForResponseSize(metricName, module.MakePredicate(method, pathPrefix));
}
public static void MetricForResponseSize(this INancyModule module, string metricName, Predicate<RouteDescription> routePredicate)
{
var histogram = NancyGlobalMetrics.NancyGlobalMetricsContext.Histogram(metricName, Unit.Custom("bytes"));
module.After.AddItemToEndOfPipeline(ctx =>
{
if (routePredicate(ctx.ResolvedRoute.Description))
{
string lengthHeader;
// if available use content length header
if (ctx.Response.Headers.TryGetValue("Content-Length", out lengthHeader))
{
long length;
if (long.TryParse(lengthHeader, out length))
{
histogram.Update(length);
}
}
else
{
// if no content length - get the length of the stream
// this might be suboptimal for some types of requests
using (var ns = new NullStream())
{
ctx.Response.Contents(ns);
histogram.Update(ns.Length);
}
}
}
});
}
public static void MetricForRequestSize(this INancyModule module, string metricName, string method, string pathPrefix)
{
module.MetricForRequestSize(metricName, module.MakePredicate(method, pathPrefix));
}
public static void MetricForRequestSize(this INancyModule module, string metricName, Predicate<RouteDescription> routePredicate)
{
var histogram = NancyGlobalMetrics.NancyGlobalMetricsContext.Histogram(metricName, Unit.Custom("bytes"));
module.Before.AddItemToStartOfPipeline(ctx =>
{
if (routePredicate(ctx.ResolvedRoute.Description))
{
histogram.Update(ctx.Request.Headers.ContentLength);
}
return null;
});
}
private static Predicate<RouteDescription> MakePredicate(this INancyModule module, string methodName, string pathPrefix)
{
if (string.IsNullOrEmpty(pathPrefix) || !pathPrefix.StartsWith("/"))
{
throw new ArgumentException("pathPrefix must start with / ", pathPrefix);
}
var modulePath = module.ModulePath == "/" ? string.Empty : module.ModulePath;
var path = (modulePath + pathPrefix).ToUpper();
return d => (string.IsNullOrEmpty(methodName) || methodName.ToUpper() == "ANY" || d.Method.ToUpper() == methodName.ToUpper())
&& d.Path.ToUpper().StartsWith(path);
}
/// <summary>
/// Fake stream used for getting the response size.
/// This class is stolen from NancyFx sources.
/// https://github.com/NancyFx/Nancy/blob/master/src/Nancy/HeadResponse.cs#L45
/// </summary>
private sealed class NullStream : Stream
{
private int bytesWritten;
public override long Length { get { return this.bytesWritten; } }
public override void Write(byte[] buffer, int offset, int count)
{
// We assume we can't seek and can't overwrite, but don't throw just in case.
this.bytesWritten += count;
}
public override void Flush() { }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException(); }
public override int EndRead(IAsyncResult asyncResult) { throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override int ReadByte() { throw new NotSupportedException(); }
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanTimeout { get { return false; } }
public override bool CanWrite { get { return true; } }
public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
}
}
}
| Recognos/Metrics.NET | Src/Adapters/Nancy.Metrics/NancyModuleMetricExtensions.cs | C# | apache-2.0 | 6,806 |
package broker
import (
"fmt"
"reflect"
"sync"
"github.com/koding/logging"
"github.com/koding/metrics"
"github.com/koding/rabbitmq"
)
// NewSubscriber creates a new subscriber
func (b *Broker) NewSubscriber() (Subscriber, error) {
l := &Consumer{
// tha app's name
WorkerName: b.AppName,
// which exchange will be listened
SourceExchangeName: b.config.ExchangeName,
// basic logger
Log: b.log,
// whether send or not redelivered items to the maintenance queue
EnableMaintenanceQueue: b.config.EnableMaintenanceQueue,
// gather metric into this property
Metrics: b.Metrics,
}
// create the consumer
consumer, err := l.createConsumer(b.MQ)
if err != nil {
return nil, err
}
l.Consumer = consumer
// set quality of the service
// TODO get this from config
if err := l.Consumer.QOS(b.config.QOS); err != nil {
return nil, err
}
if b.config.EnableMaintenanceQueue {
maintenanceQ, err := l.createMaintenancePublisher(b.MQ)
if err != nil {
return nil, err
}
l.MaintenancePublisher = maintenanceQ
}
return l, nil
}
// Consumer is the consumer of all messages
type Consumer struct {
// From which exhange the data will be consumed
SourceExchangeName string
// RMQ connection for consuming events
Consumer *rabbitmq.Consumer
// Maintenance Queue connection
MaintenancePublisher *rabbitmq.Producer
// Worker's name for consumer
WorkerName string
// logger
Log logging.Logger
// whether or not to send error-ed messages to the maintenance queue
EnableMaintenanceQueue bool
// Metrics about the broker
Metrics *metrics.Metrics
// context for subscriptions
context ErrHandler
contextValue reflect.Value
// all handlers which are listed
handlers map[string][]*SubscriptionHandler
// for handler registeration purposes
sync.Mutex
}
// SetContext wraps the context for calling the handlers within given context
func (c *Consumer) SetContext(context ErrHandler) error {
c.context = context
c.contextValue = reflect.ValueOf(context)
return nil
}
// Subscribe registers itself to a subscriber
func (l *Consumer) Subscribe(messageType string, handler *SubscriptionHandler) error {
if l.Consumer == nil {
return ErrSubscriberNotInitialized
}
l.Lock()
defer l.Unlock()
if l.handlers == nil {
l.handlers = make(map[string][]*SubscriptionHandler)
}
if _, ok := l.handlers[messageType]; !ok {
l.handlers[messageType] = make([]*SubscriptionHandler, 0)
}
l.handlers[messageType] = append(l.handlers[messageType], handler)
return nil
}
// Close closes the connections gracefully
func (l *Consumer) Close() error {
l.Log.Debug("Consumer is closing the connections %t", true)
var err, err2 error
if l.Consumer != nil {
l.Log.Debug("Consumer is closing the consumer connection: %t", true)
err = l.Consumer.Shutdown()
l.Log.Debug("Consumer closed the consumer connection successfully: %t", err == nil)
}
if l.MaintenancePublisher != nil {
l.Log.Debug("Consumer is closing the maintenance connection: %t", true)
err2 = l.MaintenancePublisher.Shutdown()
l.Log.Debug("Consumer closed the maintenance connection successfully: %t", err2 == nil)
}
if err == nil && err2 == nil {
return nil
}
return fmt.Errorf(
"err while closing consumer connections ConsumerErr: %s, MaintenanceErr: %s",
err.Error(),
err2.Error(),
)
}
func (l *Consumer) Listen() error {
l.Log.Debug("Consumer is starting to listen: %t ", true)
err := l.Consumer.Consume(l.Start())
l.Log.Debug("Consumer finished successfully: %t ", err == nil)
return err
}
// createConsumer creates a new amqp consumer
func (l *Consumer) createConsumer(rmq *rabbitmq.RabbitMQ) (*rabbitmq.Consumer, error) {
exchange := rabbitmq.Exchange{
Name: l.SourceExchangeName,
Type: "fanout",
Durable: true,
}
queue := rabbitmq.Queue{
Name: fmt.Sprintf("%s:WorkerQueue", l.WorkerName),
Durable: true,
}
binding := rabbitmq.BindingOptions{
RoutingKey: "",
}
consumerOptions := rabbitmq.ConsumerOptions{
Tag: fmt.Sprintf("%sWorkerConsumer", l.WorkerName),
}
consumer, err := rmq.NewConsumer(exchange, queue, binding, consumerOptions)
if err != nil {
return nil, err
}
return consumer, nil
}
// createMaintenancePublisher creates a new maintenance queue for storing
// errored messages in a queue for later processing
func (l *Consumer) createMaintenancePublisher(rmq *rabbitmq.RabbitMQ) (*rabbitmq.Producer, error) {
exchange := rabbitmq.Exchange{
Name: "",
}
publishingOptions := rabbitmq.PublishingOptions{
Tag: fmt.Sprintf("%sWorkerConsumer", l.WorkerName),
Immediate: false,
}
return rmq.NewProducer(
exchange,
rabbitmq.Queue{
Name: "BrokerMaintenanceQueue",
Durable: true,
},
publishingOptions,
)
}
| alex-ionochkin/koding | go/src/vendor/github.com/koding/broker/subscriber.go | GO | apache-2.0 | 4,757 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Animation;
using Granular.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Granular.Presentation.Tests.Media.Animation
{
[TestClass]
public class EasingFunctionTest
{
[TestMethod]
public void EasingFunctionModesTest()
{
PowerEase ease = new PowerEase { Power = 2 };
ease.EasingMode = EasingMode.EaseIn;
Assert.IsTrue(ease.Ease(0).IsClose(0));
Assert.IsTrue(ease.Ease(0.3).IsClose(0.09));
Assert.IsTrue(ease.Ease(0.7).IsClose(0.49));
Assert.IsTrue(ease.Ease(1).IsClose(1));
ease.EasingMode = EasingMode.EaseOut;
Assert.IsTrue(ease.Ease(0).IsClose(0));
Assert.IsTrue(ease.Ease(0.3).IsClose(0.51));
Assert.IsTrue(ease.Ease(0.7).IsClose(0.91));
Assert.IsTrue(ease.Ease(1).IsClose(1));
ease.EasingMode = EasingMode.EaseInOut;
Assert.IsTrue(ease.Ease(0).IsClose(0));
Assert.IsTrue(ease.Ease(0.3).IsClose(0.18));
Assert.IsTrue(ease.Ease(0.7).IsClose(0.82));
Assert.IsTrue(ease.Ease(1).IsClose(1));
}
}
}
| diab0l/Granular | Granular.Presentation.Tests/Media/Animation/EasingFunctionTest.cs | C# | apache-2.0 | 1,320 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
/**
* Access Google Cloud BigQuery service using SQL queries.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface GoogleBigQuerySQLEndpointBuilderFactory {
/**
* Builder for endpoint for the Google BigQuery Standard SQL component.
*/
public interface GoogleBigQuerySQLEndpointBuilder
extends
EndpointProducerBuilder {
/**
* ConnectionFactory to obtain connection to Bigquery Service. If not
* provided the default one will be used.
*
* The option is a:
* <code>org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory</code> type.
*
* Group: producer
*
* @param connectionFactory the value to set
* @return the dsl builder
*/
default GoogleBigQuerySQLEndpointBuilder connectionFactory(
Object connectionFactory) {
doSetProperty("connectionFactory", connectionFactory);
return this;
}
/**
* ConnectionFactory to obtain connection to Bigquery Service. If not
* provided the default one will be used.
*
* The option will be converted to a
* <code>org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory</code> type.
*
* Group: producer
*
* @param connectionFactory the value to set
* @return the dsl builder
*/
default GoogleBigQuerySQLEndpointBuilder connectionFactory(
String connectionFactory) {
doSetProperty("connectionFactory", connectionFactory);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default GoogleBigQuerySQLEndpointBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default GoogleBigQuerySQLEndpointBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
public interface GoogleBigQuerySQLBuilders {
/**
* Google BigQuery Standard SQL (camel-google-bigquery)
* Access Google Cloud BigQuery service using SQL queries.
*
* Category: cloud,messaging
* Since: 2.23
* Maven coordinates: org.apache.camel:camel-google-bigquery
*
* Syntax: <code>google-bigquery-sql:projectId:query</code>
*
* Path parameter: query (required)
* BigQuery standard SQL query
*
* Path parameter: projectId (required)
* Google Cloud Project Id
*
* @param path projectId:query
* @return the dsl builder
*/
default GoogleBigQuerySQLEndpointBuilder googleBigquerySql(String path) {
return GoogleBigQuerySQLEndpointBuilderFactory.endpointBuilder("google-bigquery-sql", path);
}
/**
* Google BigQuery Standard SQL (camel-google-bigquery)
* Access Google Cloud BigQuery service using SQL queries.
*
* Category: cloud,messaging
* Since: 2.23
* Maven coordinates: org.apache.camel:camel-google-bigquery
*
* Syntax: <code>google-bigquery-sql:projectId:query</code>
*
* Path parameter: query (required)
* BigQuery standard SQL query
*
* Path parameter: projectId (required)
* Google Cloud Project Id
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path projectId:query
* @return the dsl builder
*/
default GoogleBigQuerySQLEndpointBuilder googleBigquerySql(
String componentName,
String path) {
return GoogleBigQuerySQLEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static GoogleBigQuerySQLEndpointBuilder endpointBuilder(
String componentName,
String path) {
class GoogleBigQuerySQLEndpointBuilderImpl extends AbstractEndpointBuilder implements GoogleBigQuerySQLEndpointBuilder {
public GoogleBigQuerySQLEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new GoogleBigQuerySQLEndpointBuilderImpl(path);
}
} | gnodet/camel | core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GoogleBigQuerySQLEndpointBuilderFactory.java | Java | apache-2.0 | 7,567 |
// Copyright (c) 2018 Cisco and/or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vpp_punt
/*func TestPuntToHostKey(t *testing.T) {
tests := []struct {
name string
l3Protocol L3Protocol
l4Protocol L4Protocol
port uint32
expectedKey string
}{
{
name: "valid Punt case (IPv4/UDP)",
l3Protocol: L3Protocol_IPv4,
l4Protocol: L4Protocol_UDP,
port: 9000,
expectedKey: "vpp/config/v2/punt/tohost/l3/IPv4/l4/UDP/port/9000",
},
{
name: "valid Punt case (IPv4/TCP)",
l3Protocol: L3Protocol_IPv4,
l4Protocol: L4Protocol_TCP,
port: 9000,
expectedKey: "vpp/config/v2/punt/tohost/l3/IPv4/l4/TCP/port/9000",
},
{
name: "valid Punt case (IPv6/UDP)",
l3Protocol: L3Protocol_IPv6,
l4Protocol: L4Protocol_UDP,
port: 9000,
expectedKey: "vpp/config/v2/punt/tohost/l3/IPv6/l4/UDP/port/9000",
},
{
name: "valid Punt case (IPv6/TCP)",
l3Protocol: L3Protocol_IPv6,
l4Protocol: L4Protocol_TCP,
port: 0,
expectedKey: "vpp/config/v2/punt/tohost/l3/IPv6/l4/TCP/port/<invalid>",
},
{
name: "invalid Punt case (zero port)",
l3Protocol: L3Protocol_IPv4,
l4Protocol: L4Protocol_UDP,
port: 0,
expectedKey: "vpp/config/v2/punt/tohost/l3/IPv4/l4/UDP/port/<invalid>",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
key := ToHostKey(test.l3Protocol, test.l4Protocol, test.port)
if key != test.expectedKey {
t.Errorf("failed for: puntName=%s\n"+
"expected key:\n\t%q\ngot key:\n\t%q",
test.name, test.expectedKey, key)
}
})
}
}*/
/*func TestParsePuntToHostKey(t *testing.T) {
tests := []struct {
name string
key string
expectedL3 L3Protocol
expectedL4 L4Protocol
expectedPort uint32
isPuntToHostKey bool
}{
{
name: "valid Punt key",
key: "vpp/config/v2/punt/tohost/l3/IPv4/l4/TCP/port/9000",
expectedL3: L3Protocol(4),
expectedL4: L4Protocol(6),
expectedPort: 9000,
isPuntToHostKey: true,
},
{
name: "invalid Punt L3",
key: "vpp/config/v2/punt/tohost/l3/4/l4/TCP/port/9000",
expectedL3: L3Protocol(0),
expectedL4: L4Protocol(6),
expectedPort: 9000,
isPuntToHostKey: true,
},
{
name: "invalid Punt L3 and L4",
key: "vpp/config/v2/punt/tohost/l3/4/l4/6/port/9000",
expectedL3: L3Protocol(0),
expectedL4: L4Protocol(0),
expectedPort: 9000,
isPuntToHostKey: true,
},
{
name: "invalid Punt L4 and port",
key: "vpp/config/v2/punt/tohost/l3/IPv6/l4/17/port/port1",
expectedL3: L3Protocol(6),
expectedL4: L4Protocol(0),
expectedPort: 0,
isPuntToHostKey: true,
},
{
name: "invalid all",
key: "vpp/config/v2/punt/tohost/l3/4/l4/17/port/port1",
expectedL3: L3Protocol(0),
expectedL4: L4Protocol(0),
expectedPort: 0,
isPuntToHostKey: true,
},
{
name: "not a Punt to host key",
key: "vpp/config/v2/punt/ipredirect/l3/IPv6/tx/if1",
expectedL3: L3Protocol(0),
expectedL4: L4Protocol(0),
expectedPort: 0,
isPuntToHostKey: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
l3Proto, l4Proto, port, isPuntToHostKey := ParsePuntToHostKey(test.key)
if l3Proto != test.expectedL3 {
t.Errorf("expected l3PuntKey: %v\tgot: %v", test.expectedL3, l3Proto)
}
if l4Proto != test.expectedL4 {
t.Errorf("expected l4PuntKey: %v\tgot: %v", test.expectedL4, l4Proto)
}
if port != test.expectedPort {
t.Errorf("expected portPuntKey: %v\tgot: %v", test.expectedPort, port)
}
if isPuntToHostKey != test.isPuntToHostKey {
t.Errorf("expected isPuntKey: %v\tgot: %v", test.isPuntToHostKey, isPuntToHostKey)
}
})
}
}*/
/*func TestIPredirectKey(t *testing.T) {
tests := []struct {
name string
l3Protocol L3Protocol
txInterface string
expectedKey string
}{
{
name: "valid IP redirect case (IPv4)",
l3Protocol: L3Protocol_IPv4,
txInterface: "if1",
expectedKey: "vpp/config/v2/punt/ipredirect/l3/IPv4/tx/if1",
},
{
name: "valid IP redirect case (IPv6)",
l3Protocol: L3Protocol_IPv6,
txInterface: "if1",
expectedKey: "vpp/config/v2/punt/ipredirect/l3/IPv6/tx/if1",
},
{
name: "invalid IP redirect case (undefined interface)",
l3Protocol: L3Protocol_IPv4,
txInterface: "",
expectedKey: "vpp/config/v2/punt/ipredirect/l3/IPv4/tx/<invalid>",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
key := IPRedirectKey(test.l3Protocol, test.txInterface)
if key != test.expectedKey {
t.Errorf("failed for: puntName=%s\n"+
"expected key:\n\t%q\ngot key:\n\t%q",
test.name, test.expectedKey, key)
}
})
}
}*/
/*func TestParseIPRedirectKey(t *testing.T) {
tests := []struct {
name string
key string
expectedL3 L3Protocol
expectedIf string
isIPRedirectKey bool
}{
{
name: "valid IP redirect key (IPv4)",
key: "vpp/config/v2/punt/ipredirect/l3/IPv4/tx/if1",
expectedL3: L3Protocol(4),
expectedIf: "if1",
isIPRedirectKey: true,
},
{
name: "valid IP redirect key (IPv6)",
key: "vpp/config/v2/punt/ipredirect/l3/IPv6/tx/if1",
expectedL3: L3Protocol(6),
expectedIf: "if1",
isIPRedirectKey: true,
},
{
name: "invalid IP redirect key (invalid interface)",
key: "vpp/config/v2/punt/ipredirect/l3/IPv4/tx/<invalid>",
expectedL3: L3Protocol(4),
expectedIf: "<invalid>",
isIPRedirectKey: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
l3Proto, ifName, isIPRedirectKey := ParseIPRedirectKey(test.key)
if l3Proto != test.expectedL3 {
t.Errorf("expected l3IPRedirectKey L3: %v\tgot: %v", test.expectedL3, l3Proto)
}
if ifName != test.expectedIf {
t.Errorf("expected l3IPRedirectKey ifName: %v\tgot: %v", test.expectedIf, ifName)
}
if isIPRedirectKey != test.isIPRedirectKey {
t.Errorf("expected isIPRedirectKey: %v\tgot: %v", test.isIPRedirectKey, isIPRedirectKey)
}
})
}
}*/
| ondrej-fabry/vpp-agent | proto/ligato/vpp/punt/models_test.go | GO | apache-2.0 | 6,963 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cocoon.samples.tour.beans;
import java.util.Iterator;
/** Simple test of the DatabaseFacade */
public class DatabaseFacadeTest {
public static void main(String[] args) {
System.out.println("TaskBean objects provided by DatabaseFacade:");
final DatabaseFacade db = DatabaseFacade.getInstance();
for(Iterator it=db.getTasks().iterator(); it.hasNext(); ) {
System.out.println(it.next());
}
}
}
| apache/cocoon | blocks/cocoon-tour/cocoon-tour-impl/src/main/java/org/apache/cocoon/samples/tour/beans/DatabaseFacadeTest.java | Java | apache-2.0 | 1,269 |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.runtime;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.common.NxtMotorMode;
import com.google.appinventor.components.common.NxtMotorPort;
import com.google.appinventor.components.common.NxtRegulationMode;
import com.google.appinventor.components.common.NxtRunState;
import com.google.appinventor.components.common.NxtSensorMode;
import com.google.appinventor.components.common.NxtSensorPort;
import com.google.appinventor.components.common.NxtSensorType;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.runtime.util.ErrorMessages;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* A base class for components that can control a LEGO MINDSTORMS NXT robot.
*
* @author lizlooney@google.com (Liz Looney)
*/
@SimpleObject
public class LegoMindstormsNxtBase extends AndroidNonvisibleComponent
implements BluetoothConnectionListener, Component, Deleteable {
private static final int TOY_ROBOT = 0x0804; // from android.bluetooth.BluetoothClass.Device.
private static final Map<Integer, String> ERROR_MESSAGES;
static {
ERROR_MESSAGES = new HashMap<Integer, String>();
ERROR_MESSAGES.put(0x20, "Pending communication transaction in progress");
ERROR_MESSAGES.put(0x40, "Specified mailbox queue is empty");
ERROR_MESSAGES.put(0x81, "No more handles");
ERROR_MESSAGES.put(0x82, "No space");
ERROR_MESSAGES.put(0x83, "No more files");
ERROR_MESSAGES.put(0x84, "End of file expected");
ERROR_MESSAGES.put(0x85, "End of file");
ERROR_MESSAGES.put(0x86, "Not a linear file");
ERROR_MESSAGES.put(0x87, "File not found");
ERROR_MESSAGES.put(0x88, "Handle already closed");
ERROR_MESSAGES.put(0x89, "No linear space");
ERROR_MESSAGES.put(0x8A, "Undefined error");
ERROR_MESSAGES.put(0x8B, "File is busy");
ERROR_MESSAGES.put(0x8C, "No write buffers");
ERROR_MESSAGES.put(0x8D, "Append not possible");
ERROR_MESSAGES.put(0x8E, "File is full");
ERROR_MESSAGES.put(0x8F, "File exists");
ERROR_MESSAGES.put(0x90, "Module not found");
ERROR_MESSAGES.put(0x91, "Out of boundary");
ERROR_MESSAGES.put(0x92, "Illegal file name");
ERROR_MESSAGES.put(0x93, "Illegal handle");
ERROR_MESSAGES.put(0xBD, "Request failed (i.e. specified file not found)");
ERROR_MESSAGES.put(0xBE, "Unknown command opcode");
ERROR_MESSAGES.put(0xBF, "Insane packet");
ERROR_MESSAGES.put(0xC0, "Data contains out-of-range values");
ERROR_MESSAGES.put(0xDD, "Communication bus error");
ERROR_MESSAGES.put(0xDE, "No free memory in communication buffer");
ERROR_MESSAGES.put(0xDF, "Specified channel/connection is not valid");
ERROR_MESSAGES.put(0xE0, "Specified channel/connection not configured or busy");
ERROR_MESSAGES.put(0xEC, "No active program");
ERROR_MESSAGES.put(0xED, "Illegal size specified");
ERROR_MESSAGES.put(0xEE, "Illegal mailbox queue ID specified");
ERROR_MESSAGES.put(0xEF, "Attempted to access invalid field of a structure");
ERROR_MESSAGES.put(0xF0, "Bad input or output specified");
ERROR_MESSAGES.put(0xFB, "Insufficient memory available");
ERROR_MESSAGES.put(0xFF, "Bad arguments");
}
protected final String logTag;
// TODO(lizlooney) - allow communication via USB if possible.
protected BluetoothClient bluetooth;
/**
* Creates a new LegoMindstormsNxtBase.
*/
protected LegoMindstormsNxtBase(ComponentContainer container, String logTag) {
super(container.$form());
this.logTag = logTag;
}
/**
* This constructor is for testing purposes only.
*/
protected LegoMindstormsNxtBase() {
super(null);
logTag = null;
}
/**
* Default Initialize
*/
public final void Initialize() {
}
/**
* Returns the BluetoothClient component that should be used for communication.
*/
@SimpleProperty(
description = "The BluetoothClient component that should be used for communication.",
category = PropertyCategory.BEHAVIOR, userVisible = false)
public BluetoothClient BluetoothClient() {
return bluetooth;
}
/**
* Specifies the BluetoothClient component that should be used for communication.
* **Must be set in the Designer.**
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BLUETOOTHCLIENT,
defaultValue = "")
@SimpleProperty(userVisible = false)
public void BluetoothClient(BluetoothClient bluetoothClient) {
if (bluetooth != null) {
bluetooth.removeBluetoothConnectionListener(this);
bluetooth.detachComponent(this);
bluetooth = null;
}
if (bluetoothClient != null) {
bluetooth = bluetoothClient;
bluetooth.attachComponent(this, Collections.singleton(TOY_ROBOT));
bluetooth.addBluetoothConnectionListener(this);
if (bluetooth.IsConnected()) {
// We missed the real afterConnect event.
afterConnect(bluetooth);
}
}
}
protected final void setOutputState(String functionName, int port, int power, int mode,
int regulationMode, int turnRatio, int runState, long tachoLimit) {
power = sanitizePower(power);
turnRatio = sanitizeTurnRatio(turnRatio);
byte[] command = new byte[12];
command[0] = (byte) 0x80; // Direct command telegram, no response
command[1] = (byte) 0x04; // SETOUTPUTSTATE command
copyUBYTEValueToBytes(port, command, 2);
copySBYTEValueToBytes(power, command, 3);
copyUBYTEValueToBytes(mode, command, 4);
copyUBYTEValueToBytes(regulationMode, command, 5);
copySBYTEValueToBytes(turnRatio, command, 6);
copyUBYTEValueToBytes(runState, command, 7);
// NOTE(lizlooney) - the LEGO MINDSTORMS NXT Direct Commands documentation (AKA Appendix 2)
// says to use bytes 8-12 for the ULONG tacho limit. That's 5 bytes!
// I've tested sending a 5th byte and it is ignored. Paul Gyugyi confirmed that the code for
// the NXT firmware only uses 4 bytes. I'm pretty sure the documentation was supposed to say
// bytes 8-11.
copyULONGValueToBytes(tachoLimit, command, 8);
sendCommand(functionName, command);
}
protected final void setOutputState(
String functionName,
NxtMotorPort port,
int power,
NxtMotorMode mode,
NxtRegulationMode regulationMode,
int turnRatio,
NxtRunState runState,
long tachoLimit) {
setOutputState(
functionName,
port.toInt(),
power,
mode.toUnderlyingValue(),
regulationMode.toUnderlyingValue(),
turnRatio,
runState.toUnderlyingValue(),
tachoLimit);
}
protected final void setInputMode(String functionName, int port, int sensorType, int sensorMode) {
byte[] command = new byte[5];
command[0] = (byte) 0x80; // Direct command telegram, no response
command[1] = (byte) 0x05; // SETINPUTMODE command
copyUBYTEValueToBytes(port, command, 2);
copyUBYTEValueToBytes(sensorType, command, 3);
copyUBYTEValueToBytes(sensorMode, command, 4);
sendCommand(functionName, command);
}
protected final void setInputMode(
String functionName,
NxtSensorPort port,
NxtSensorType type,
NxtSensorMode mode) {
setInputMode(functionName, port.toInt(), type.toUnderlyingValue(), mode.toUnderlyingValue());
}
protected final byte[] getInputValues(String functionName, int port) {
byte[] command = new byte[3];
command[0] = (byte) 0x00; // Direct command telegram, response required
command[1] = (byte) 0x07; // GETINPUTVALUES command
copyUBYTEValueToBytes(port, command, 2);
byte[] returnPackage = sendCommandAndReceiveReturnPackage(functionName, command);
if (evaluateStatus(functionName, returnPackage, command[1])) {
if (returnPackage.length == 16) {
return returnPackage;
} else {
Log.w(logTag, functionName + ": unexpected return package length " +
returnPackage.length + " (expected 16)");
}
}
return null;
}
protected final byte[] getInputValues(String functionName, NxtSensorPort port) {
return getInputValues(functionName, port.toInt());
}
protected final void resetInputScaledValue(String functionName, int port) {
byte[] command = new byte[3];
command[0] = (byte) 0x80; // Direct command telegram, no response
command[1] = (byte) 0x08; // RESETINPUTSCALEDVALUE command
copyUBYTEValueToBytes(port, command, 2);
sendCommand(functionName, command);
}
protected final void resetInputScaledValue(String functionName, NxtSensorPort port) {
resetInputScaledValue(functionName, port.toInt());
}
protected final int lsGetStatus(String functionName, int port) {
byte[] command = new byte[3];
command[0] = (byte) 0x00; // Direct command telegram, response required
command[1] = (byte) 0x0E; // LSGETSTATUS command
copyUBYTEValueToBytes(port, command, 2);
byte[] returnPackage = sendCommandAndReceiveReturnPackage(functionName, command);
if (evaluateStatus(functionName, returnPackage, command[1])) {
if (returnPackage.length == 4) {
return getUBYTEValueFromBytes(returnPackage, 3);
} else {
Log.w(logTag, functionName + ": unexpected return package length " +
returnPackage.length + " (expected 4)");
}
}
return 0;
}
protected final int lsGetStatus(String functionName, NxtSensorPort port) {
return lsGetStatus(functionName, port.toInt());
}
protected final void lsWrite(String functionName, int port, byte[] data, int rxDataLength) {
if (data.length > 16) {
throw new IllegalArgumentException("length must be <= 16");
}
byte[] command = new byte[5 + data.length];
command[0] = (byte) 0x00; // Direct command telegram, response required
command[1] = (byte) 0x0F; // LSWRITE command
copyUBYTEValueToBytes(port, command, 2);
copyUBYTEValueToBytes(data.length, command, 3);
copyUBYTEValueToBytes(rxDataLength, command, 4);
System.arraycopy(data, 0, command, 5, data.length);
byte[] returnPackage = sendCommandAndReceiveReturnPackage(functionName, command);
evaluateStatus(functionName, returnPackage, command[1]);
}
protected final void lsWrite(String functionName, NxtSensorPort port, byte[] data,
int rxDataLength) {
lsWrite(functionName, port.toInt(), data, rxDataLength);
}
protected final byte[] lsRead(String functionName, int port) {
byte[] command = new byte[3];
command[0] = (byte) 0x00; // Direct command telegram, response required
command[1] = (byte) 0x10; // LSREAD command
copyUBYTEValueToBytes(port, command, 2);
byte[] returnPackage = sendCommandAndReceiveReturnPackage(functionName, command);
if (evaluateStatus(functionName, returnPackage, command[1])) {
if (returnPackage.length == 20) {
return returnPackage;
} else {
Log.w(logTag, functionName + ": unexpected return package length " +
returnPackage.length + " (expected 20)");
}
}
return null;
}
protected final byte[] lsRead(String functionName, NxtSensorPort port) {
return lsRead(functionName, port.toInt());
}
/*
* Checks whether the bluetooth property has been set or whether this
* component is connected to a robot and, if necessary, dispatches the
* appropriate error.
*
* Returns true if everything is ok, false if there was an error.
*/
protected final boolean checkBluetooth(String functionName) {
if (bluetooth == null) {
form.dispatchErrorOccurredEvent(this, functionName,
ErrorMessages.ERROR_NXT_BLUETOOTH_NOT_SET);
return false;
}
if (!bluetooth.IsConnected()) {
form.dispatchErrorOccurredEvent(this, functionName,
ErrorMessages.ERROR_NXT_NOT_CONNECTED_TO_ROBOT);
return false;
}
return true;
}
protected final byte[] sendCommandAndReceiveReturnPackage(String functionName, byte[] command) {
sendCommand(functionName, command);
return receiveReturnPackage(functionName);
}
protected final void sendCommand(String functionName, byte[] command) {
byte[] header = new byte[2];
copyUWORDValueToBytes(command.length, header, 0);
bluetooth.write(functionName, header);
bluetooth.write(functionName, command);
}
private byte[] receiveReturnPackage(String functionName) {
byte[] header = bluetooth.read(functionName, 2);
if (header.length == 2) {
int length = getUWORDValueFromBytes(header, 0);
byte[] returnPackage = bluetooth.read(functionName, length);
if (returnPackage.length >= 3) {
return returnPackage;
}
}
form.dispatchErrorOccurredEvent(this, functionName,
ErrorMessages.ERROR_NXT_INVALID_RETURN_PACKAGE);
return new byte[0];
}
protected final boolean evaluateStatus(String functionName, byte[] returnPackage, byte command) {
int status = getStatus(functionName, returnPackage, command);
if (status == 0) {
return true;
} else {
handleError(functionName, status);
return false;
}
}
protected final int getStatus(String functionName, byte[] returnPackage, byte command) {
if (returnPackage.length >= 3) {
if (returnPackage[0] != (byte) 0x02) {
Log.w(logTag, functionName + ": unexpected return package byte 0: 0x" +
Integer.toHexString(returnPackage[0] & 0xFF) + " (expected 0x02)");
}
if (returnPackage[1] != command) {
Log.w(logTag, functionName + ": unexpected return package byte 1: 0x" +
Integer.toHexString(returnPackage[1] & 0xFF) + " (expected 0x" +
Integer.toHexString(command & 0xFF) + ")");
}
return getUBYTEValueFromBytes(returnPackage, 2);
} else {
Log.w(logTag, functionName + ": unexpected return package length " +
returnPackage.length + " (expected >= 3)");
}
return -1;
}
private void handleError(String functionName, int status) {
if (status < 0) {
// Real status bytes received from the NXT are unsigned.
// -1 is returned from getStatus when the returnPackage is not even big enough to contain a
// status byte. In that case, we've already called form.dispatchErrorOccurredEvent from
// receiveReturnPackage.
} else {
String errorMessage = ERROR_MESSAGES.get(status);
if (errorMessage != null) {
form.dispatchErrorOccurredEvent(this, functionName,
ErrorMessages.ERROR_NXT_ERROR_CODE_RECEIVED, errorMessage);
} else {
form.dispatchErrorOccurredEvent(this, functionName,
ErrorMessages.ERROR_NXT_ERROR_CODE_RECEIVED,
"Error code 0x" + Integer.toHexString(status & 0xFF));
}
}
}
protected final void copyBooleanValueToBytes(boolean value, byte[] bytes, int offset) {
bytes[offset] = value ? (byte) 1 : (byte) 0;
}
protected final void copySBYTEValueToBytes(int value, byte[] bytes, int offset) {
bytes[offset] = (byte) value;
}
protected final void copyUBYTEValueToBytes(int value, byte[] bytes, int offset) {
bytes[offset] = (byte) value;
}
protected final void copySWORDValueToBytes(int value, byte[] bytes, int offset) {
bytes[offset] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 1] = (byte) (value & 0xff);
}
protected final void copyUWORDValueToBytes(int value, byte[] bytes, int offset) {
bytes[offset] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 1] = (byte) (value & 0xff);
}
protected final void copySLONGValueToBytes(int value, byte[] bytes, int offset) {
bytes[offset] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 1] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 2] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 3] = (byte) (value & 0xff);
}
protected final void copyULONGValueToBytes(long value, byte[] bytes, int offset) {
bytes[offset] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 1] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 2] = (byte) (value & 0xff);
value = value >> 8;
bytes[offset + 3] = (byte) (value & 0xff);
}
protected final void copyStringValueToBytes(String value, byte[] bytes, int offset,
int maxCount) {
if (value.length() > maxCount) {
value = value.substring(0, maxCount);
}
byte[] valueBytes;
try {
valueBytes = value.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
Log.w(logTag, "UnsupportedEncodingException: " + e.getMessage());
valueBytes = value.getBytes();
}
int lengthToCopy = Math.min(maxCount, valueBytes.length);
System.arraycopy(valueBytes, 0, bytes, offset, lengthToCopy);
}
protected final boolean getBooleanValueFromBytes(byte[] bytes, int offset) {
return bytes[offset] != 0;
}
protected final int getSBYTEValueFromBytes(byte[] bytes, int offset) {
return bytes[offset];
}
protected final int getUBYTEValueFromBytes(byte[] bytes, int offset) {
return bytes[offset] & 0xFF;
}
protected final int getSWORDValueFromBytes(byte[] bytes, int offset) {
return (bytes[offset] & 0xFF) |
(bytes[offset + 1] << 8);
}
protected final int getUWORDValueFromBytes(byte[] bytes, int offset) {
return (bytes[offset] & 0xFF) |
((bytes[offset + 1] & 0xFF) << 8);
}
protected final int getSLONGValueFromBytes(byte[] bytes, int offset) {
return (bytes[offset] & 0xFF) |
((bytes[offset + 1] & 0xFF) << 8) |
((bytes[offset + 2] & 0xFF) << 16) |
(bytes[offset + 3] << 24);
}
protected final long getULONGValueFromBytes(byte[] bytes, int offset) {
return (bytes[offset] & 0xFFL) |
((bytes[offset + 1] & 0xFFL) << 8) |
((bytes[offset + 2] & 0xFFL) << 16) |
((bytes[offset + 3] & 0xFFL) << 24);
}
protected final String getStringValueFromBytes(byte[] bytes, int offset) {
// Determine length by looking for the null termination byte.
int length = 0;
for (int i = offset; i < bytes.length; i++) {
if (bytes[i] == 0) {
length = i - offset;
break;
}
}
return getStringValueFromBytes(bytes, offset, length);
}
protected final String getStringValueFromBytes(byte[] bytes, int offset, int count) {
try {
return new String(bytes, offset, count, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
Log.w(logTag, "UnsupportedEncodingException: " + e.getMessage());
return new String(bytes, offset, count);
}
}
protected final int convertMotorPortLetterToNumber(String motorPortLetter) {
if (motorPortLetter.length() == 1) {
return convertMotorPortLetterToNumber(motorPortLetter.charAt(0));
}
throw new IllegalArgumentException("Illegal motor port letter " + motorPortLetter);
}
protected final int convertMotorPortLetterToNumber(char motorPortLetter) {
if (motorPortLetter == 'A' || motorPortLetter == 'a') {
return 0;
} else if (motorPortLetter == 'B' || motorPortLetter == 'b') {
return 1;
} else if (motorPortLetter == 'C' || motorPortLetter == 'c') {
return 2;
}
throw new IllegalArgumentException("Illegal motor port letter " + motorPortLetter);
}
protected final int convertSensorPortLetterToNumber(String sensorPortLetter) {
if (sensorPortLetter.length() == 1) {
return convertSensorPortLetterToNumber(sensorPortLetter.charAt(0));
}
throw new IllegalArgumentException("Illegal sensor port letter " + sensorPortLetter);
}
protected final int convertSensorPortLetterToNumber(char sensorPortLetter) {
if (sensorPortLetter == '1') {
return 0;
} else if (sensorPortLetter == '2') {
return 1;
} else if (sensorPortLetter == '3') {
return 2;
} else if (sensorPortLetter == '4') {
return 3;
}
throw new IllegalArgumentException("Illegal sensor port letter " + sensorPortLetter);
}
protected final int sanitizePower(int power) {
if (power < -100) {
Log.w(logTag, "power " + power + " is invalid, using -100.");
power = -100;
}
if (power > 100) {
Log.w(logTag, "power " + power + " is invalid, using 100.");
power = 100;
}
return power;
}
protected final int sanitizeTurnRatio(int turnRatio) {
if (turnRatio < -100) {
Log.w(logTag, "turnRatio " + turnRatio + " is invalid, using -100.");
turnRatio = -100;
}
if (turnRatio > 100) {
Log.w(logTag, "turnRatio " + turnRatio + " is invalid, using 100.");
turnRatio = 100;
}
return turnRatio;
}
// BluetoothConnectionListener implementation
@Override
public void afterConnect(BluetoothConnectionBase bluetoothConnection) {
// Subclasses may wish to do something.
}
@Override
public void beforeDisconnect(BluetoothConnectionBase bluetoothConnection) {
// Subclasses may wish to do something.
}
// Deleteable implementation
@Override
public void onDelete() {
if (bluetooth != null) {
bluetooth.removeBluetoothConnectionListener(this);
bluetooth.detachComponent(this);
bluetooth = null;
}
}
}
| jisqyv/appinventor-sources | appinventor/components/src/com/google/appinventor/components/runtime/LegoMindstormsNxtBase.java | Java | apache-2.0 | 21,905 |
/**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts.impl;
// Start of user code for imports
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.SWTUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbDiagramPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;
// End of user code
/**
*
*
*/
public class EsbDiagramPropertiesEditionPartImpl extends CompositePropertiesEditionPart implements ISWTPropertiesEditionPart, EsbDiagramPropertiesEditionPart {
protected Text test;
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public EsbDiagramPropertiesEditionPartImpl(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite)
*
*/
public Composite createFigure(final Composite parent) {
view = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(view);
return view;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createControls(org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(Composite view) {
CompositionSequence esbDiagramStep = new BindingCompositionSequence(propertiesEditionComponent);
esbDiagramStep
.addStep(EsbViewsRepository.EsbDiagram.Properties.class)
.addStep(EsbViewsRepository.EsbDiagram.Properties.test);
composer = new PartComposer(esbDiagramStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EsbViewsRepository.EsbDiagram.Properties.class) {
return createPropertiesGroup(parent);
}
if (key == EsbViewsRepository.EsbDiagram.Properties.test) {
return createTestText(parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(Composite parent) {
Group propertiesGroup = new Group(parent, SWT.NONE);
propertiesGroup.setText(EsbMessages.EsbDiagramPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesGroupData = new GridData(GridData.FILL_HORIZONTAL);
propertiesGroupData.horizontalSpan = 3;
propertiesGroup.setLayoutData(propertiesGroupData);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
return propertiesGroup;
}
protected Composite createTestText(Composite parent) {
createDescription(parent, EsbViewsRepository.EsbDiagram.Properties.test, EsbMessages.EsbDiagramPropertiesEditionPart_TestLabel);
test = SWTUtils.createScrollableText(parent, SWT.BORDER);
GridData testData = new GridData(GridData.FILL_HORIZONTAL);
test.setLayoutData(testData);
test.addFocusListener(new FocusAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(EsbDiagramPropertiesEditionPartImpl.this, EsbViewsRepository.EsbDiagram.Properties.test, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, test.getText()));
}
});
test.addKeyListener(new KeyAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(EsbDiagramPropertiesEditionPartImpl.this, EsbViewsRepository.EsbDiagram.Properties.test, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, test.getText()));
}
}
});
EditingUtils.setID(test, EsbViewsRepository.EsbDiagram.Properties.test);
EditingUtils.setEEFtype(test, "eef::Text"); //$NON-NLS-1$
SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.EsbDiagram.Properties.test, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createTestText
// End of user code
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbDiagramPropertiesEditionPart#getTest()
*
*/
public String getTest() {
return test.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbDiagramPropertiesEditionPart#setTest(String newValue)
*
*/
public void setTest(String newValue) {
if (newValue != null) {
test.setText(newValue);
} else {
test.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.EsbDiagram.Properties.test);
if (eefElementEditorReadOnlyState && test.isEnabled()) {
test.setEnabled(false);
test.setToolTipText(EsbMessages.EsbDiagram_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !test.isEnabled()) {
test.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EsbMessages.EsbDiagram_Part_Title;
}
// Start of user code additional methods
// End of user code
}
| prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/impl/EsbDiagramPropertiesEditionPartImpl.java | Java | apache-2.0 | 7,180 |
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
import os
import tempfile
import json
import unittest
import shutil
from openstack_plugin_common import Config
from test_utils.utils import get_task
class TestOpenstackNovaNetManagerBlueprint(unittest.TestCase):
def test_openstack_configuration_copy_to_manager(self):
script_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
'scripts',
'configure.py')
task = get_task(script_path,
'_copy_openstack_configuration_to_manager')
config_output_file_path = tempfile.mkstemp()[1]
def mock_put(file_path, *args, **kwargs):
shutil.copyfile(file_path, config_output_file_path)
task.func_globals['fabric'].api.put = mock_put
inputs_config = {
'username': 'inputs-username',
'region': 'inputs-region'
}
file_config = {
'username': 'file-username',
'password': 'file-password',
'auth_url': 'file-auth-url'
}
conf_file_path = tempfile.mkstemp()[1]
os.environ[Config.OPENSTACK_CONFIG_PATH_ENV_VAR] = conf_file_path
with open(conf_file_path, 'w') as f:
json.dump(file_config, f)
os.environ['OS_USERNAME'] = 'envar-username'
os.environ['OS_PASSWORD'] = 'envar-password'
os.environ['OS_TENANT_NAME'] = 'envar-tenant-name'
task(inputs_config)
with open(config_output_file_path) as f:
config = json.load(f)
self.assertEquals('inputs-username', config.get('username'))
self.assertEquals('inputs-region', config.get('region'))
self.assertEquals('file-password', config.get('password'))
self.assertEquals('file-auth-url', config.get('auth_url'))
self.assertEquals('envar-tenant-name', config.get('tenant_name'))
| szpotona/cloudify-manager-blueprints | openstack-nova-net/tests/test_openstack_nova_net_blueprint.py | Python | apache-2.0 | 2,514 |
/*
* Copyright (c) 2016, Peter Abeles. All Rights Reserved.
*
* This file is part of DeepBoof
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package deepboof.visualization;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
/**
* Displays controls for adjusting what is shown in plots and how it is shown as well as displaying
* summary statistics.
*
* @author Peter Abeles
*/
public class PlotControlPanel extends JPanel
implements ItemListener, ActionListener
{
JCheckBox cScatterLog;
JComboBox<String> cSelectX;
JComboBox<String> cSelectY;
// which thing parameters are shown in scatter plot
public int scatterX=0,scatterY=1;
// show the scatter plot with a log scale
public boolean scatterLog=false;
Listener listener;
public PlotControlPanel(Listener listener ) {
this.listener = listener;
setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
cScatterLog = new JCheckBox("Log Plot");
cScatterLog.setMnemonic(KeyEvent.VK_L);
cScatterLog.setSelected(scatterLog);
cScatterLog.addItemListener(this);
cSelectX = new JComboBox<>();
cSelectY = new JComboBox<>();
add(cScatterLog);
add(Box.createHorizontalGlue());
add(new JLabel("X: "));
add(cSelectX);
add(Box.createRigidArea(new Dimension(5,0)));
add(new JLabel("Y: "));
add(cSelectY);
}
public void setParameters( final List<String> parameters ) {
if( parameters.size() < 1 )
throw new IllegalArgumentException("There needs to be at least one parameter");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
DefaultComboBoxModel<String> modelX = (DefaultComboBoxModel<String>)cSelectX.getModel();
modelX.removeAllElements();
for( String p : parameters ) {
modelX.addElement(p);
}
modelX = (DefaultComboBoxModel<String>)cSelectY.getModel();
modelX.removeAllElements();
for( String p : parameters ) {
modelX.addElement(p);
}
scatterX = 0;
scatterY = Math.min(parameters.size(),1);
cSelectX.invalidate();
cSelectY.invalidate();
cSelectX.setPreferredSize(cSelectX.getMinimumSize());
cSelectX.setMaximumSize(cSelectX.getMinimumSize());
cSelectY.setPreferredSize(cSelectY.getMinimumSize());
cSelectY.setMaximumSize(cSelectY.getMinimumSize());
// prevent it from sending out an event for a change in selected index
cSelectX.removeActionListener(PlotControlPanel.this);
cSelectY.removeActionListener(PlotControlPanel.this);
cSelectX.setSelectedIndex(scatterX);
cSelectY.setSelectedIndex(scatterY);
cSelectX.addActionListener(PlotControlPanel.this);
cSelectY.addActionListener(PlotControlPanel.this);
}});
}
@Override
public void itemStateChanged(ItemEvent e) {
if( e.getSource() == cScatterLog ) {
scatterLog = cScatterLog.isSelected();
listener.uiScatterLog(scatterLog);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() == cSelectX ) {
scatterX = cSelectX.getSelectedIndex();
listener.uiScatterSelected(scatterX,scatterY);
} else if( e.getSource() == cSelectY ) {
scatterY = cSelectY.getSelectedIndex();
listener.uiScatterSelected(scatterX,scatterY);
}
}
public interface Listener {
void uiScatterLog( boolean showLog );
void uiScatterSelected( int labelX , int labelY );
}
}
| lessthanoptimal/DeepBoof | modules/visualization/src/main/java/deepboof/visualization/PlotControlPanel.java | Java | apache-2.0 | 3,860 |
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.tasks;
import com.netflix.genie.test.categories.UnitTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Calendar;
/**
* Unit tests for the utility methods for task.
*
* @author tgianos
* @since 3.0.0
*/
@Category(UnitTest.class)
public class TaskUtilsUnitTests {
/**
* Make sure that since we're in the same package we can construct.
*/
@Test
public void canConstruct() {
Assert.assertNotNull(new TaskUtils());
}
/**
* Make sure we can get exactly midnight UTC.
*/
@Test
public void canGetMidnightUtc() {
final Calendar cal = TaskUtils.getMidnightUTC();
Assert.assertThat(cal.get(Calendar.MILLISECOND), Matchers.is(0));
Assert.assertThat(cal.get(Calendar.SECOND), Matchers.is(0));
Assert.assertThat(cal.get(Calendar.MINUTE), Matchers.is(0));
Assert.assertThat(cal.get(Calendar.HOUR_OF_DAY), Matchers.is(0));
}
/**
* Make sure we can subtract the number of desired days from a calendar date properly.
*/
@Test
public void canSubtractDaysFromDate() {
final int currentDay = 25;
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_YEAR, currentDay);
final int retention = 5;
TaskUtils.subtractDaysFromDate(cal, retention);
Assert.assertThat(cal.get(Calendar.DAY_OF_YEAR), Matchers.is(20));
TaskUtils.subtractDaysFromDate(cal, -1 * retention);
Assert.assertThat(cal.get(Calendar.DAY_OF_YEAR), Matchers.is(15));
}
}
| ajoymajumdar/genie | genie-web/src/test/java/com/netflix/genie/web/tasks/TaskUtilsUnitTests.java | Java | apache-2.0 | 2,299 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.config;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.graphhopper.util.Helper;
import com.graphhopper.util.PMap;
/**
* Corresponds to an entry of the `profiles` section in `config.yml` and specifies the properties of a routing profile.
* The name used here needs to be used when setting up CH/LM preparations. See also the documentation in
* `config-example.yml'
*
* @see CHProfile
* @see LMProfile
*/
public class Profile {
private String name = "car";
private String vehicle = "car";
private String weighting = "fastest";
private boolean turnCosts = false;
private PMap hints = new PMap();
public static void validateProfileName(String profileName) {
if (!profileName.matches("^[a-z0-9_\\-]+$")) {
throw new IllegalArgumentException("Profile names may only contain lower case letters, numbers and underscores, given: " + profileName);
}
}
private Profile() {
// default constructor needed for jackson
}
public Profile(String name) {
setName(name);
}
public String getName() {
return name;
}
public Profile setName(String name) {
validateProfileName(name);
this.name = name;
return this;
}
public String getVehicle() {
return vehicle;
}
public Profile setVehicle(String vehicle) {
this.vehicle = vehicle;
return this;
}
public String getWeighting() {
return weighting;
}
public Profile setWeighting(String weighting) {
this.weighting = weighting;
return this;
}
public boolean isTurnCosts() {
return turnCosts;
}
public Profile setTurnCosts(boolean turnCosts) {
this.turnCosts = turnCosts;
return this;
}
@JsonIgnore
public PMap getHints() {
return hints;
}
@JsonAnySetter
public Profile putHint(String key, Object value) {
this.hints.putObject(key, value);
return this;
}
@Override
public String toString() {
return createContentString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Profile profile = (Profile) o;
return name.equals(profile.name);
}
private String createContentString() {
// used to check against stored custom models, see #2026
return "name=" + name + "|vehicle=" + vehicle + "|weighting=" + weighting + "|turnCosts=" + turnCosts + "|hints=" + hints;
}
@Override
public int hashCode() {
return name.hashCode();
}
public int getVersion() {
return Helper.staticHashCode(createContentString());
}
}
| boldtrn/graphhopper | core/src/main/java/com/graphhopper/config/Profile.java | Java | apache-2.0 | 3,662 |
/*
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.hal.dmr;
import jsinterop.annotations.JsMethod;
import static jsinterop.annotations.JsPackage.GLOBAL;
/** Encodes and decodes to and from Base64 notation. */
public class Base64 {
@JsMethod(namespace = GLOBAL, name = "btoa")
public static native String encode(String decoded);
@JsMethod(namespace = GLOBAL, name = "atob")
public static native String decode(String encoded);
/** Defeats instantiation. */
private Base64() {
}
} | hal/hal.next | dmr/src/main/java/org/jboss/hal/dmr/Base64.java | Java | apache-2.0 | 1,106 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.EOFException;
import org.junit.jupiter.api.Test;
/**
* Tests {@link IOIndexedException}.
*
* @since 2.7
*/
public class IOIndexedExceptionTest {
@Test
public void testEdge() {
final IOIndexedException exception = new IOIndexedException(-1, null);
assertEquals(-1, exception.getIndex());
assertNull(exception.getCause());
assertNotNull(exception.getMessage());
}
@Test
public void testPlain() {
final EOFException e = new EOFException("end");
final IOIndexedException exception = new IOIndexedException(0, e);
assertEquals(0, exception.getIndex());
assertEquals(e, exception.getCause());
assertNotNull(exception.getMessage());
}
}
| apache/commons-io | src/test/java/org/apache/commons/io/IOIndexedExceptionTest.java | Java | apache-2.0 | 1,768 |
class TreeBuilder
include CompressedIds
include TreeKids
attr_reader :name, :type, :tree_nodes
def node_builder
TreeNodeBuilder
end
def self.class_for_type(type)
case type
when :filter then raise('Obsolete tree type.')
# Catalog explorer trees
when :configuration_manager_providers then TreeBuilderConfigurationManager
when :cs_filter then TreeBuilderConfigurationManagerConfiguredSystems
when :configuration_scripts then TreeBuilderConfigurationManagerConfigurationScripts
# Catalog explorer trees
when :ot then TreeBuilderOrchestrationTemplates
when :sandt then TreeBuilderCatalogItems
when :stcat then TreeBuilderCatalogs
when :svccat then TreeBuilderServiceCatalog
# Chargeback explorer trees
when :cb_assignments then TreeBuilderChargebackAssignments
when :cb_rates then TreeBuilderChargebackRates
when :cb_reports then TreeBuilderChargebackReports
when :vandt then TreeBuilderVandt
when :vms_filter then TreeBuilderVmsFilter
when :templates_filter then TreeBuilderTemplateFilter
when :instances then TreeBuilderInstances
when :images then TreeBuilderImages
when :instances_filter then TreeBuilderInstancesFilter
when :images_filter then TreeBuilderImagesFilter
when :vms_instances_filter then TreeBuilderVmsInstancesFilter
when :templates_images_filter then TreeBuilderTemplatesImagesFilter
when :policy_simulation then TreeBuilderPolicySimulation
when :policy_profile then TreeBuilderPolicyProfile
when :policy then TreeBuilderPolicy
when :event then TreeBuilderEvent
when :condition then TreeBuilderCondition
when :action then TreeBuilderAction
when :alert_profile then TreeBuilderAlertProfile
when :alert then TreeBuilderAlert
# reports explorer trees
when :db then TreeBuilderReportDashboards
when :export then TreeBuilderReportExport
when :reports then TreeBuilderReportReports
when :roles then TreeBuilderReportRoles
when :savedreports then TreeBuilderReportSavedReports
when :schedules then TreeBuilderReportSchedules
when :widgets then TreeBuilderReportWidgets
# containers explorer tree
when :containers then TreeBuilderContainers
when :containers_filter then TreeBuilderContainersFilter
# automate explorer tree
when :ae then TreeBuilderAeClass
# miq_ae_customization explorer trees
when :ab then TreeBuilderButtons
when :dialogs then TreeBuilderServiceDialogs
when :dialog_import_export then TreeBuilderAeCustomization
when :old_dialogs then TreeBuilderProvisioningDialogs
# OPS explorer trees
when :diagnostics then TreeBuilderOpsDiagnostics
when :rbac then TreeBuilderOpsRbac
when :servers_by_role then TreeBuilderServersByRole
when :roles_by_server then TreeBuilderRolesByServer
when :settings then TreeBuilderOpsSettings
when :vmdb then TreeBuilderOpsVmdb
# PXE explorer trees
when :customization_templates then TreeBuilderPxeCustomizationTemplates
when :iso_datastores then TreeBuilderIsoDatastores
when :pxe_image_types then TreeBuilderPxeImageTypes
when :pxe_servers then TreeBuilderPxeServers
# Services explorer tree
when :svcs then TreeBuilderServices
when :sa then TreeBuilderStorageAdapters
# Datastores explorer trees
when :storage then TreeBuilderStorage
when :storage_pod then TreeBuilderStoragePod
when :datacenter then TreeBuilderDatacenter
when :vat then TreeBuilderVat
when :network then TreeBuilderNetwork
when :df then TreeBuilderDefaultFilters
end
end
def initialize(name, type, sandbox, build = true)
@tree_state = TreeState.new(sandbox)
@sb = sandbox # FIXME: some subclasses still access @sb
@locals_for_render = {}
@name = name.to_sym # includes _tree
@options = tree_init_options(name.to_sym)
@tree_nodes = {}.to_json
# FIXME: remove @name or @tree, unify
@type = type.to_sym # *usually* same as @name but w/o _tree
add_to_sandbox
build_tree if build
end
def node_by_tree_id(id)
model, rec_id, prefix = self.class.extract_node_model_and_id(id)
if model == "Hash"
{:type => prefix, :id => rec_id, :full_id => id}
elsif model.nil? && [:sandt, :svccat, :stcat].include?(@type)
# Creating empty record to show items under unassigned catalog node
ServiceTemplateCatalog.new
elsif model.nil? && [:configuration_manager_providers_tree].include?(@name)
# Creating empty record to show items under unassigned catalog node
ConfigurationProfile.new
else
model.constantize.find(from_cid(rec_id))
end
end
# Get the children of a dynatree node that is being expanded (autoloaded)
def x_get_child_nodes(id)
parents = [] # FIXME: parent ids should be provided on autoload as well
object = node_by_tree_id(id)
# Save node as open
open_node(id)
x_get_tree_objects(object, @tree_state.x_tree(@name), false, parents).map do |o|
x_build_node_dynatree(o, id, @tree_state.x_tree(@name))
end
end
def tree_init_options(_tree_name)
$log.warn "MIQ(#{self.class.name}) - TreeBuilder descendants should have their own tree_init_options"
{}
end
# Get nodes model (folder, Vm, Cluster, etc)
def self.get_model_for_prefix(node_prefix)
X_TREE_NODE_PREFIXES[node_prefix]
end
def self.get_prefix_for_model(model)
model = model.to_s unless model.kind_of?(String)
X_TREE_NODE_PREFIXES_INVERTED[model]
end
def self.build_node_id(record)
prefix = get_prefix_for_model(record.class.base_model)
"#{prefix}-#{record.id}"
end
# return this nodes model and record id
def self.extract_node_model_and_id(node_id)
prefix, record_id = node_id.split("_").last.split('-')
model = get_model_for_prefix(prefix)
[model, record_id, prefix]
end
def locals_for_render
@locals_for_render.update(:select_node => "#{@tree_state.x_node(@name)}")
end
def reload!
build_tree
end
private
def build_tree
# FIXME: we have the options -- no need to reload from @sb
tree_nodes = x_build_dynatree(@tree_state.x_tree(@name))
active_node_set(tree_nodes)
set_nodes(tree_nodes)
end
# Set active node to root if not set.
# Subclass this method if active node on initial load is different than root node.
def active_node_set(tree_nodes)
@tree_state.x_node_set(tree_nodes.first[:key], @name) unless @tree_state.x_node(@name)
end
def set_nodes(nodes)
# Add the root node even if it is not set
add_root_node(nodes) if @options.fetch(:add_root, :true)
@tree_nodes = nodes.to_json
@locals_for_render = set_locals_for_render
end
def add_to_sandbox
@tree_state.add_tree(
@options.reverse_merge(
:tree => @name,
:type => type,
:klass_name => self.class.name,
:leaf => @options[:leaf],
:add_root => true,
:open_nodes => [],
:lazy => true
)
)
end
def add_root_node(nodes)
root = nodes.first
root[:title], root[:tooltip], icon, options = root_options
root[:icon] = ActionController::Base.helpers.image_path("100/#{icon || 'folder'}.png")
root[:cfmeNoClick] = options[:cfmeNoClick] if options.present? && options.key?(:cfmeNoClick)
end
def set_locals_for_render
{
:tree_id => "#{@name}box",
:tree_name => @name.to_s,
:json_tree => @tree_nodes,
:onclick => "miqOnClickSelectTreeNode",
:id_prefix => "#{@name}_",
:base_id => "root",
:no_base_exp => true,
:exp_tree => false,
:highlighting => true,
:tree_state => true,
:multi_lines => true,
:checkboxes => false,
}
end
# Build an explorer tree, from scratch
# Options:
# :type # Type of tree, i.e. :handc, :vandt, :filtered, etc
# :leaf # Model name of leaf nodes, i.e. "Vm"
# :open_nodes # Tree node ids of currently open nodes
# :add_root # If true, put a root node at the top
# :full_ids # stack parent id on top of each node id
# :lazy # set if tree is lazy
def x_build_dynatree(options)
children = x_get_tree_objects(nil, options, false, [])
child_nodes = children.map do |child|
# already a node? FIXME: make a class for node
if child.kind_of?(Hash) && child.key?(:title) && child.key?(:key) && child.key?(:icon)
child
else
x_build_node_dynatree(child, nil, options)
end
end
return child_nodes unless options[:add_root]
[{:key => 'root', :children => child_nodes, :expand => true}]
end
def x_get_tree_objects(parent, options, count_only, parents)
children_or_count = parent.nil? ? x_get_tree_roots(count_only, options) : x_get_tree_kids(parent, count_only, options, parents)
children_or_count || (count_only ? 0 : [])
end
# Return a tree node for the passed in object
def x_build_node(object, pid, options) # Called with object, tree node parent id, tree options
parents = pid.to_s.split('_')
options[:is_current] =
((object.kind_of?(MiqServer) && MiqServer.my_server(true).id == object.id) ||
(object.kind_of?(Zone) && MiqServer.my_server(true).my_zone == object.name))
node = x_build_single_node(object, pid, options)
# Process the node's children
node[:expand] = Array(@tree_state.x_tree(@name)[:open_nodes]).include?(node[:key]) || !!options[:open_all] || node[:expand]
if object[:load_children] ||
node[:expand] ||
@options[:lazy] == false
kids = x_get_tree_objects(object, options, false, parents).map do |o|
x_build_node(o, node[:key], options)
end
node[:children] = kids unless kids.empty?
else
if x_get_tree_objects(object, options, true, parents) > 0
node[:isLazy] = true # set child flag if children exist
end
end
node
end
def x_build_single_node(object, pid, options)
node_builder.build(object, pid, options)
end
# Called with object, tree node parent id, tree options
def x_build_node_dynatree(object, pid, options)
x_build_node(object, pid, options)
end
# Handle custom tree nodes (object is a Hash)
def x_get_tree_custom_kids(_object, count_only, _options)
count_only ? 0 : []
end
def count_only_or_objects(count_only, objects, sort_by = nil)
if count_only
objects.size
elsif sort_by.kind_of?(Proc)
objects.sort_by(&sort_by)
elsif sort_by
objects.sort_by { |o| Array(sort_by).collect { |sb| o.deep_send(sb).to_s.downcase } }
else
objects
end
end
def assert_type(actual, expected)
raise "#{self.class}: expected #{expected.inspect}, got #{actual.inspect}" unless actual == expected
end
def open_node(id)
open_nodes = @tree_state.x_tree(@name)[:open_nodes]
open_nodes.push(id) unless open_nodes.include?(id)
end
def get_vmdb_config
@vmdb_config ||= VMDB::Config.new("vmdb").config
end
# Add child nodes to the active tree below node 'id'
def self.tree_add_child_nodes(sandbox, klass_name, id)
tree = klass_name.constantize.new(sandbox[:active_tree].to_s,
sandbox[:active_tree].to_s.sub(/_tree$/, ''),
sandbox, false)
tree.x_get_child_nodes(id)
end
# Tree node prefixes for generic explorers
X_TREE_NODE_PREFIXES = {
"a" => "MiqAction",
"aec" => "MiqAeClass",
"aei" => "MiqAeInstance",
"aem" => "MiqAeMethod",
"aen" => "MiqAeNamespace",
"al" => "MiqAlert",
"ap" => "MiqAlertSet",
"asr" => "AssignedServerRole",
"az" => "AvailabilityZone",
"azu" => "OrchestrationTemplateAzure",
"at" => "ManageIQ::Providers::AnsibleTower::ConfigurationManager",
"cf " => "ConfigurationScript",
"cnt" => "Container",
"co" => "Condition",
"cbg" => "CustomButtonSet",
"cb" => "CustomButton",
"cfn" => "OrchestrationTemplateCfn",
"cm" => "Compliance",
"cd" => "ComplianceDetail",
"cp" => "ConfigurationProfile",
"cr" => "ChargebackRate",
"cs" => "ConfiguredSystem",
"ct" => "CustomizationTemplate",
"dc" => "Datacenter",
"dg" => "Dialog",
"ds" => "Storage",
"dsc" => "StorageCluster",
"e" => "ExtManagementSystem",
"ev" => "MiqEventDefinition",
"c" => "EmsCluster",
"csf" => "ManageIQ::Providers::Foreman::ConfigurationManager::ConfiguredSystem",
"csa" => "ManageIQ::Providers::AnsibleTower::ConfigurationManager::ConfiguredSystem",
"f" => "EmsFolder",
"fr" => "ManageIQ::Providers::Foreman::ConfigurationManager",
"g" => "MiqGroup",
"gd" => "GuestDevice",
"h" => "Host",
"hot" => "OrchestrationTemplateHot",
"isd" => "IsoDatastore",
"isi" => "IsoImage",
"l" => "Lan",
"ld" => "LdapDomain",
"lr" => "LdapRegion",
"me" => "MiqEnterprise",
"mr" => "MiqRegion",
"msc" => "MiqSchedule",
"ms" => "MiqSearch",
"odg" => "MiqDialog",
"ot" => "OrchestrationTemplate",
"pi" => "PxeImage",
"pit" => "PxeImageType",
"ps" => "PxeServer",
"pp" => "MiqPolicySet",
"p" => "MiqPolicy",
"rep" => "MiqReport",
"rr" => "MiqReportResult",
"svr" => "MiqServer",
"ur" => "MiqUserRole",
"r" => "ResourcePool",
"s" => "Service",
"sa" => "StorageAdapter",
'sn' => 'Snapshot',
"sl" => "MiqScsiLun",
"sg" => "MiqScsiTarget",
"sis" => "ScanItemSet",
"role" => "ServerRole",
"st" => "ServiceTemplate",
"stc" => "ServiceTemplateCatalog",
"sr" => "ServiceResource",
"sw" => "Switch",
"t" => "MiqTemplate",
"tb" => "VmdbTable",
"ti" => "VmdbIndex",
"tn" => "Tenant",
"u" => "User",
"v" => "Vm",
"vnf" => "OrchestrationTemplateVnfd",
"wi" => "WindowsImage",
"xx" => "Hash", # For custom (non-CI) nodes, specific to each tree
"z" => "Zone"
}
X_TREE_NODE_PREFIXES_INVERTED = X_TREE_NODE_PREFIXES.invert
end
| KevinLoiseau/manageiq | app/presenters/tree_builder.rb | Ruby | apache-2.0 | 14,802 |
'use strict';
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var bootbox = require('bootbox');
var ko = require('knockout');
var oop = require('js/oop');
var Raven = require('raven-js');
var ChangeMessageMixin = require('js/changeMessage');
require('knockout.punches');
ko.punches.enableAll();
var UserEmail = oop.defclass({
constructor: function(params) {
params = params || {};
this.address = ko.observable(params.address);
this.isConfirmed = ko.observable(params.isConfirmed || false);
this.isPrimary = ko.observable(params.isPrimary || false);
}
});
var UserProfile = oop.defclass({
constructor: function () {
this.id = ko.observable();
this.emails = ko.observableArray();
this.primaryEmail = ko.pureComputed(function () {
var emails = this.emails();
for (var i = 0; i < this.emails().length; i++) {
if(emails[i].isPrimary()) {
return emails[i];
}
}
return new UserEmail();
}.bind(this));
this.alternateEmails = ko.pureComputed(function () {
var emails = this.emails();
var retval = [];
for (var i = 0; i < this.emails().length; i++) {
if (emails[i].isConfirmed() && !emails[i].isPrimary()) {
retval.push(emails[i]);
}
}
return retval;
}.bind(this));
this.unconfirmedEmails = ko.pureComputed(function () {
var emails = this.emails();
var retval = [];
for (var i = 0; i < this.emails().length; i++) {
if(!emails[i].isConfirmed()) {
retval.push(emails[i]);
}
}
return retval;
}.bind(this));
}
});
var UserProfileClient = oop.defclass({
constructor: function () {},
urls: {
fetch: '/api/v1/profile/',
update: '/api/v1/profile/',
resend: '/api/v1/resend/'
},
fetch: function () {
var ret = $.Deferred();
var request = $.get(this.urls.fetch);
request.done(function(data) {
ret.resolve(this.unserialize(data));
}.bind(this));
request.fail(function(xhr, status, error) {
$osf.growl('Error', 'Could not fetch user profile.', 'danger');
Raven.captureMessage('Error fetching user profile', {
url: this.urls.fetch,
status: status,
error: error
});
ret.reject(xhr, status, error);
}.bind(this));
return ret.promise();
},
update: function (profile, email) {
var url = this.urls.update;
if(email) {
url = this.urls.resend;
}
var ret = $.Deferred();
var request = $osf.putJSON(
url,
this.serialize(profile, email)
).done(function (data) {
ret.resolve(this.unserialize(data, profile));
}.bind(this)).fail(function(xhr, status, error) {
$osf.growl('Error', 'User profile not updated. Please refresh the page and try ' +
'again or contact <a href="mailto: support@cos.io">support@cos.io</a> ' +
'if the problem persists.', 'danger');
Raven.captureMessage('Error fetching user profile', {
url: this.urls.update,
status: status,
error: error
});
ret.reject(xhr, status, error);
}.bind(this));
return ret;
},
serialize: function (profile, email) {
if(email){
return {
id: profile.id(),
email: {
address: email.address(),
primary: email.isPrimary(),
confirmed: email.isConfirmed()
}
};
}
return {
id: profile.id(),
emails: ko.utils.arrayMap(profile.emails(), function(email) {
return {
address: email.address(),
primary: email.isPrimary(),
confirmed: email.isConfirmed()
};
})
};
},
unserialize: function (data, profile) {
if (typeof(profile) === 'undefined') {
profile = new UserProfile();
}
profile.id(data.profile.id);
profile.emails(
ko.utils.arrayMap(data.profile.emails, function (emailData){
var email = new UserEmail({
address: emailData.address,
isPrimary: emailData.primary,
isConfirmed: emailData.confirmed
});
return email;
})
);
return profile;
}
});
var UserProfileViewModel = oop.extend(ChangeMessageMixin, {
constructor: function() {
this.super.constructor.call(this);
this.client = new UserProfileClient();
this.profile = ko.observable(new UserProfile());
this.emailInput = ko.observable();
},
init: function () {
this.client.fetch().done(
function(profile) { this.profile(profile); }.bind(this)
);
},
addEmail: function () {
this.changeMessage('', 'text-info');
var newEmail = this.emailInput().toLowerCase().trim();
if(newEmail){
var email = new UserEmail({
address: newEmail
});
// ensure email isn't already in the list
for (var i=0; i<this.profile().emails().length; i++) {
if (this.profile().emails()[i].address() === email.address()) {
this.changeMessage('Duplicate Email', 'text-warning');
this.emailInput('');
return;
}
}
this.profile().emails.push(email);
this.client.update(this.profile()).done(function (profile) {
this.profile(profile);
var emails = profile.emails();
for (var i=0; i<emails.length; i++) {
if (emails[i].address() === email.address()) {
this.emailInput('');
$osf.growl('<em>' + email.address() + '<em> added to your account.','You will receive a confirmation email at <em>' + email.address() + '<em>. Please check your email and confirm.', 'success');
return;
}
}
this.changeMessage('Invalid Email.', 'text-danger');
}.bind(this));
} else {
this.changeMessage('Email cannot be empty.', 'text-danger');
}
},
resendConfirmation: function(email){
var self = this;
self.changeMessage('', 'text-info');
bootbox.confirm({
title: 'Resend Email Confirmation?',
message: 'Are you sure that you want to resend email confirmation at ' + '<em><b>' + email.address() + '</b></em>',
callback: function (confirmed) {
if (confirmed) {
self.client.update(self.profile(), email).done(function () {
$osf.growl(
'Email confirmation resent to <em>' + email.address() + '<em>',
'You will receive a new confirmation email at <em>' + email.address() + '<em>. Please check your email and confirm.',
'success');
});
}
}
});
},
removeEmail: function (email) {
var self = this;
self.changeMessage('', 'text-info');
if (self.profile().emails().indexOf(email) !== -1) {
bootbox.confirm({
title: 'Remove Email?',
message: 'Are you sure that you want to remove ' + '<em><b>' + email.address() + '</b></em>' + ' from your email list?',
callback: function (confirmed) {
if (confirmed) {
self.profile().emails.remove(email);
self.client.update(self.profile()).done(function () {
$osf.growl('Email Removed', '<em>' + email.address() + '<em>', 'success');
});
}
}
});
} else {
$osf.growl('Error', 'Please refresh the page and try again.', 'danger');
}
},
makeEmailPrimary: function (email) {
this.changeMessage('', 'text-info');
if (this.profile().emails().indexOf(email) !== -1) {
this.profile().primaryEmail().isPrimary(false);
email.isPrimary(true);
this.client.update(this.profile()).done(function () {
$osf.growl('Made Primary', '<em>' + email.address() + '<em>', 'success');
});
} else {
$osf.growl('Error', 'Please refresh the page and try again.', 'danger');
}
}
});
var DeactivateAccountViewModel = oop.defclass({
constructor: function () {
this.success = ko.observable(false);
},
urls: {
'update': '/api/v1/profile/deactivate/'
},
_requestDeactivation: function() {
var request = $osf.postJSON(this.urls.update, {});
request.done(function() {
$osf.growl('Success', 'An OSF administrator will contact you shortly to confirm your deactivation request.', 'success');
this.success(true);
}.bind(this));
request.fail(function(xhr, status, error) {
$osf.growl('Error',
'Deactivation request failed. Please contact <a href="mailto: support@cos.io">support@cos.io</a> if the problem persists.',
'danger'
);
Raven.captureMessage('Error requesting account deactivation', {
url: this.urls.update,
status: status,
error: error
});
}.bind(this));
return request;
},
submit: function () {
var self = this;
bootbox.confirm({
title: 'Request account deactivation?',
message: 'Are you sure you want to request account deactivation? An OSF administrator will review your request. If accepted, you ' +
'will <strong>NOT</strong> be able to reactivate your account.',
callback: function(confirmed) {
if (confirmed) {
return self._requestDeactivation();
}
}
});
}
});
var ExportAccountViewModel = oop.defclass({
constructor: function () {
this.success = ko.observable(false);
},
urls: {
'update': '/api/v1/profile/export/'
},
_requestExport: function() {
var request = $osf.postJSON(this.urls.update, {});
request.done(function() {
$osf.growl('Success', 'An OSF administrator will contact you shortly to confirm your export request.', 'success');
this.success(true);
}.bind(this));
request.fail(function(xhr, status, error) {
$osf.growl('Error',
'Export request failed. Please contact <a href="mailto: support@cos.io">support@cos.io</a> if the problem persists.',
'danger'
);
Raven.captureMessage('Error requesting account export', {
url: this.urls.update,
status: status,
error: error
});
}.bind(this));
return request;
},
submit: function () {
var self = this;
bootbox.confirm({
title: 'Request account export?',
message: 'Are you sure you want to request account export?',
callback: function(confirmed) {
if (confirmed) {
return self._requestExport();
}
}
});
}
});
module.exports = {
UserProfileViewModel: UserProfileViewModel,
DeactivateAccountViewModel: DeactivateAccountViewModel,
ExportAccountViewModel: ExportAccountViewModel
};
| barbour-em/osf.io | website/static/js/accountSettings.js | JavaScript | apache-2.0 | 12,254 |
#! /bin/env python
def mainFunc():
xml_file = open('new.xml', 'r')
out_file = open('newnew.xml', 'w')
for i, line in enumerate(xml_file.readlines()):
print 'processing line %d' % i
line = line.replace(';', '')
line = line.replace('>', '')
line = line.replace('<', '')
line = line.replace('&', '')
out_file.write(line)
if __name__ == '__main__':
mainFunc() | igemsoftware/HFUT-China_2015 | processXML.py | Python | apache-2.0 | 425 |
package org.jboss.weld.tests.producer.method;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.BeanArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.test.util.Utils;
import org.jboss.weld.util.reflection.Reflections;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class InstanceCleanupTest {
@Deployment
public static Archive<?> deployment() {
return ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(InstanceCleanupTest.class))
.addPackage(InstanceCleanupTest.class.getPackage())
.addClass(Utils.class);
}
@Test
public void testInstanceCleansUpDependents(BeanManagerImpl beanManager) {
Kitchen.reset();
Bean<Cafe> bean = Reflections.cast(beanManager.resolve(beanManager.getBeans(Cafe.class)));
CreationalContext<Cafe> cc = beanManager.createCreationalContext(bean);
Cafe instance = bean.create(cc);
Food food = instance.getSalad();
bean.destroy(instance, cc);
assertNotNull(food);
assertNotNull(Kitchen.getCompostedFood());
assertTrue(Kitchen.getCompostedFood().isMade());
}
}
| antoinesd/weld-core | tests-arquillian/src/test/java/org/jboss/weld/tests/producer/method/InstanceCleanupTest.java | Java | apache-2.0 | 1,571 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.parse.spark;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.DriverContext;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.io.orc.OrcInputFormat;
import org.apache.hadoop.hive.ql.io.rcfile.stats.PartialScanWork;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.NodeProcessor;
import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.optimizer.GenMapRedUtils;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.parse.PrunedPartitionList;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.SparkWork;
import org.apache.hadoop.hive.ql.plan.StatsNoJobWork;
import org.apache.hadoop.hive.ql.plan.StatsWork;
import org.apache.hadoop.mapred.InputFormat;
import com.google.common.base.Preconditions;
/**
* ProcessAnalyzeTable sets up work for the several variants of analyze table
* (normal, no scan, partial scan.) The plan at this point will be a single
* table scan operator.
*
* Cloned from Tez ProcessAnalyzeTable.
*/
public class SparkProcessAnalyzeTable implements NodeProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(SparkProcessAnalyzeTable.class.getName());
// shared plan utils for spark
private GenSparkUtils utils = null;
/**
* Injecting the utils in the constructor facilitates testing.
*/
public SparkProcessAnalyzeTable(GenSparkUtils utils) {
this.utils = utils;
}
@SuppressWarnings("unchecked")
@Override
public Object process(Node nd, Stack<Node> stack,
NodeProcessorCtx procContext, Object... nodeOutputs) throws SemanticException {
GenSparkProcContext context = (GenSparkProcContext) procContext;
TableScanOperator tableScan = (TableScanOperator) nd;
ParseContext parseContext = context.parseContext;
@SuppressWarnings("rawtypes")
Class<? extends InputFormat> inputFormat = tableScan.getConf().getTableMetadata()
.getInputFormatClass();
if (parseContext.getQueryProperties().isAnalyzeCommand()) {
Preconditions.checkArgument(tableScan.getChildOperators() == null
|| tableScan.getChildOperators().size() == 0,
"AssertionError: expected tableScan.getChildOperators() to be null, "
+ "or tableScan.getChildOperators().size() to be 0");
String alias = null;
for (String a: parseContext.getTopOps().keySet()) {
if (tableScan == parseContext.getTopOps().get(a)) {
alias = a;
}
}
Preconditions.checkArgument(alias != null, "AssertionError: expected alias to be not null");
SparkWork sparkWork = context.currentTask.getWork();
boolean partialScan = parseContext.getQueryProperties().isPartialScanAnalyzeCommand();
boolean noScan = parseContext.getQueryProperties().isNoScanAnalyzeCommand();
if (inputFormat.equals(OrcInputFormat.class) && (noScan || partialScan)) {
// ANALYZE TABLE T [PARTITION (...)] COMPUTE STATISTICS partialscan;
// ANALYZE TABLE T [PARTITION (...)] COMPUTE STATISTICS noscan;
// There will not be any Spark job above this task
StatsNoJobWork snjWork = new StatsNoJobWork(tableScan.getConf().getTableMetadata().getTableSpec());
snjWork.setStatsReliable(parseContext.getConf().getBoolVar(
HiveConf.ConfVars.HIVE_STATS_RELIABLE));
Task<StatsNoJobWork> snjTask = TaskFactory.get(snjWork, parseContext.getConf());
snjTask.setParentTasks(null);
context.rootTasks.remove(context.currentTask);
context.rootTasks.add(snjTask);
return true;
} else {
// ANALYZE TABLE T [PARTITION (...)] COMPUTE STATISTICS;
// The plan consists of a simple SparkTask followed by a StatsTask.
// The Spark task is just a simple TableScanOperator
StatsWork statsWork = new StatsWork(tableScan.getConf().getTableMetadata().getTableSpec());
statsWork.setAggKey(tableScan.getConf().getStatsAggPrefix());
statsWork.setStatsTmpDir(tableScan.getConf().getTmpStatsDir());
statsWork.setSourceTask(context.currentTask);
statsWork.setStatsReliable(parseContext.getConf().getBoolVar(HiveConf.ConfVars.HIVE_STATS_RELIABLE));
Task<StatsWork> statsTask = TaskFactory.get(statsWork, parseContext.getConf());
context.currentTask.addDependentTask(statsTask);
// ANALYZE TABLE T [PARTITION (...)] COMPUTE STATISTICS noscan;
// The plan consists of a StatsTask only.
if (parseContext.getQueryProperties().isNoScanAnalyzeCommand()) {
statsTask.setParentTasks(null);
statsWork.setNoScanAnalyzeCommand(true);
context.rootTasks.remove(context.currentTask);
context.rootTasks.add(statsTask);
}
// ANALYZE TABLE T [PARTITION (...)] COMPUTE STATISTICS partialscan;
if (parseContext.getQueryProperties().isPartialScanAnalyzeCommand()) {
handlePartialScanCommand(tableScan, parseContext, statsWork, context, statsTask);
}
// NOTE: here we should use the new partition predicate pushdown API to get a list of pruned list,
// and pass it to setTaskPlan as the last parameter
Set<Partition> confirmedPartns = GenMapRedUtils.getConfirmedPartitionsForScan(tableScan);
PrunedPartitionList partitions = null;
if (confirmedPartns.size() > 0) {
Table source = tableScan.getConf().getTableMetadata();
List<String> partCols = GenMapRedUtils.getPartitionColumns(tableScan);
partitions = new PrunedPartitionList(source, confirmedPartns, partCols, false);
}
MapWork w = utils.createMapWork(context, tableScan, sparkWork, partitions);
w.setGatheringStats(true);
return true;
}
}
return null;
}
/**
* handle partial scan command.
*
* It is composed of PartialScanTask followed by StatsTask.
*/
private void handlePartialScanCommand(TableScanOperator tableScan, ParseContext parseContext,
StatsWork statsWork, GenSparkProcContext context, Task<StatsWork> statsTask)
throws SemanticException {
String aggregationKey = tableScan.getConf().getStatsAggPrefix();
StringBuilder aggregationKeyBuffer = new StringBuilder(aggregationKey);
List<Path> inputPaths = GenMapRedUtils.getInputPathsForPartialScan(tableScan, aggregationKeyBuffer);
aggregationKey = aggregationKeyBuffer.toString();
// scan work
PartialScanWork scanWork = new PartialScanWork(inputPaths);
scanWork.setMapperCannotSpanPartns(true);
scanWork.setAggKey(aggregationKey);
scanWork.setStatsTmpDir(tableScan.getConf().getTmpStatsDir(), parseContext.getConf());
// stats work
statsWork.setPartialScanAnalyzeCommand(true);
// partial scan task
DriverContext driverCxt = new DriverContext();
@SuppressWarnings("unchecked")
Task<PartialScanWork> partialScanTask = TaskFactory.get(scanWork, parseContext.getConf());
partialScanTask.initialize(parseContext.getQueryState(), null, driverCxt,
tableScan.getCompilationOpContext());
partialScanTask.setWork(scanWork);
statsWork.setSourceTask(partialScanTask);
// task dependency
context.rootTasks.remove(context.currentTask);
context.rootTasks.add(partialScanTask);
partialScanTask.addDependentTask(statsTask);
}
}
| vergilchiu/hive | ql/src/java/org/apache/hadoop/hive/ql/parse/spark/SparkProcessAnalyzeTable.java | Java | apache-2.0 | 8,691 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* File comment
*/
package org.apache.geode.internal.cache;
import java.util.Collection;
import java.util.Set;
import org.apache.geode.cache.EntryNotFoundException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.Region.Entry;
import org.apache.geode.cache.UnsupportedOperationInTransactionException;
import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;
import org.apache.geode.internal.cache.tier.sockets.VersionedObjectList;
import org.apache.geode.internal.offheap.annotations.Retained;
/**
* @since GemFire 6.0tx
*/
public interface InternalDataView {
/**
* @param clientEvent TODO
* @param returnTombstones TODO
* @param retainResult if true then the result may be a retained off-heap reference
* @return the object associated with the key
*/
@Retained
Object getDeserializedValue(KeyInfo keyInfo, LocalRegion localRegion, boolean updateStats,
boolean disableCopyOnRead, boolean preferCD, EntryEventImpl clientEvent,
boolean returnTombstones, boolean retainResult);
/**
* @param expectedOldValue TODO
* @throws EntryNotFoundException if the entry is not found in the view
*/
void destroyExistingEntry(EntryEventImpl event, boolean cacheWrite, Object expectedOldValue)
throws EntryNotFoundException;
/**
* Invalidate the entry
*
* @see Region#invalidate(Object)
*/
void invalidateExistingEntry(EntryEventImpl event, boolean invokeCallbacks,
boolean forceNewEntry);
/**
* get the entry count
*
* @return the entry count
*/
int entryCount(LocalRegion localRegion);
Object getValueInVM(KeyInfo keyInfo, LocalRegion localRegion, boolean rememberRead);
/**
* @return true if key exists, false otherwise
*/
boolean containsKey(KeyInfo keyInfo, LocalRegion localRegion);
boolean containsValueForKey(KeyInfo keyInfo, LocalRegion localRegion);
Entry getEntry(KeyInfo keyInfo, LocalRegion localRegion, boolean allowTombstones);
/**
* get entry for the key. Called only on farside.
*
* @return the entry on the remote data store
*/
Entry getEntryOnRemote(KeyInfo key, LocalRegion localRegion, boolean allowTombstones)
throws DataLocationException;
/**
* Put or create an entry in the data view.
*
* @param event specifies the new or updated value
* @return true if operation updated existing data, otherwise false
*/
boolean putEntry(EntryEventImpl event, boolean ifNew, boolean ifOld, Object expectedOldValue,
boolean requireOldValue, long lastModified, boolean overwriteDestroyed);
/**
* Put or create an entry in the data view. Called only on the farside.
*
* @param event specifies the new or updated value
* @return true if operation updated existing data, otherwise false
*/
boolean putEntryOnRemote(EntryEventImpl event, boolean ifNew, boolean ifOld,
Object expectedOldValue, boolean requireOldValue, long lastModified,
boolean overwriteDestroyed) throws DataLocationException;
/**
* Destroy an entry in the data view. Called only on the farside.
*
* @param cacheWrite TODO
* @throws DataLocationException TODO
*/
void destroyOnRemote(EntryEventImpl event, boolean cacheWrite, Object expectedOldValue)
throws DataLocationException;
/**
* Invalidate an entry in the data view. Called only on farside.
*
*/
void invalidateOnRemote(EntryEventImpl event, boolean invokeCallbacks, boolean forceNewEntry)
throws DataLocationException;
/**
* @return true if statistics should be updated later in a batch (such as a tx commit)
*/
boolean isDeferredStats();
/**
* @param disableCopyOnRead if true then copy on read is disabled for this call
* @param preferCD true if the preferred result form is CachedDeserializable
* @param requestingClient the client making the request, or null if from a server
* @param clientEvent the client's event, if any
* @param returnTombstones TODO
* @return the Object associated with the key
*/
Object findObject(KeyInfo key, LocalRegion r, boolean isCreate, boolean generateCallbacks,
Object value, boolean disableCopyOnRead, boolean preferCD,
ClientProxyMembershipID requestingClient, EntryEventImpl clientEvent,
boolean returnTombstones);
/**
*
* @return an Entry for the key
*/
Object getEntryForIterator(KeyInfo key, LocalRegion currRgn, boolean rememberReads,
boolean allowTombstones);
/**
*
* @return the key for the provided key
*/
Object getKeyForIterator(KeyInfo keyInfo, LocalRegion currRgn, boolean rememberReads,
boolean allowTombstones);
Set getAdditionalKeysForIterator(LocalRegion currRgn);
/**
*
* @return set of keys in the region
*/
Collection<?> getRegionKeysForIteration(LocalRegion currRegion);
/**
*
* @param requestingClient the client that made the request, or null if not from a client
* @param clientEvent the client event, if any
* @param returnTombstones TODO
* @return the serialized value from the cache
*/
Object getSerializedValue(LocalRegion localRegion, KeyInfo key, boolean doNotLockEntry,
ClientProxyMembershipID requestingClient, EntryEventImpl clientEvent,
boolean returnTombstones) throws DataLocationException;
void checkSupportsRegionDestroy() throws UnsupportedOperationInTransactionException;
void checkSupportsRegionInvalidate() throws UnsupportedOperationInTransactionException;
void checkSupportsRegionClear() throws UnsupportedOperationInTransactionException;
/**
* @param allowTombstones whether to include destroyed entries in the result
* @return Set of keys in the given bucket
*/
Set getBucketKeys(LocalRegion localRegion, int bucketId, boolean allowTombstones);
void postPutAll(DistributedPutAllOperation putallOp, VersionedObjectList successfulPuts,
InternalRegion reg);
void postRemoveAll(DistributedRemoveAllOperation op, VersionedObjectList successfulOps,
InternalRegion reg);
Entry accessEntry(KeyInfo keyInfo, LocalRegion localRegion);
void updateEntryVersion(EntryEventImpl event) throws EntryNotFoundException;
}
| pdxrunner/geode | geode-core/src/main/java/org/apache/geode/internal/cache/InternalDataView.java | Java | apache-2.0 | 6,979 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.search;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.xpack.core.search.action.GetAsyncSearchAction;
import org.elasticsearch.xpack.core.search.action.GetAsyncStatusAction;
import org.elasticsearch.xpack.core.search.action.SubmitAsyncSearchAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import static org.elasticsearch.xpack.core.async.AsyncTaskMaintenanceService.ASYNC_SEARCH_CLEANUP_INTERVAL_SETTING;
public final class AsyncSearch extends Plugin implements ActionPlugin {
@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
return Arrays.asList(
new ActionHandler<>(SubmitAsyncSearchAction.INSTANCE, TransportSubmitAsyncSearchAction.class),
new ActionHandler<>(GetAsyncSearchAction.INSTANCE, TransportGetAsyncSearchAction.class),
new ActionHandler<>(GetAsyncStatusAction.INSTANCE, TransportGetAsyncStatusAction.class)
);
}
@Override
public List<RestHandler> getRestHandlers(Settings settings, RestController restController, ClusterSettings clusterSettings,
IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter,
IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<DiscoveryNodes> nodesInCluster) {
return Arrays.asList(
new RestSubmitAsyncSearchAction(),
new RestGetAsyncSearchAction(),
new RestGetAsyncStatusAction(),
new RestDeleteAsyncSearchAction()
);
}
@Override
public List<Setting<?>> getSettings() {
return Collections.singletonList(ASYNC_SEARCH_CLEANUP_INTERVAL_SETTING);
}
}
| nknize/elasticsearch | x-pack/plugin/async-search/src/main/java/org/elasticsearch/xpack/search/AsyncSearch.java | Java | apache-2.0 | 2,775 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.orchestration.core.common.listener;
import org.apache.shardingsphere.orchestration.center.CenterRepository;
import org.apache.shardingsphere.orchestration.center.listener.DataChangedEvent;
import org.apache.shardingsphere.orchestration.core.common.event.ShardingOrchestrationEvent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public final class PostShardingCenterRepositoryEventListenerTest {
@Mock
private CenterRepository centerRepository;
@Test
public void assertWatch() {
PostShardingCenterRepositoryEventListener postShardingCenterRepositoryEventListener = new PostShardingCenterRepositoryEventListener(centerRepository, Arrays.asList("test")) {
@Override
protected ShardingOrchestrationEvent createShardingOrchestrationEvent(final DataChangedEvent event) {
return mock(ShardingOrchestrationEvent.class);
}
};
postShardingCenterRepositoryEventListener.watch();
verify(centerRepository).watch(eq("test"), ArgumentMatchers.any());
}
@Test
public void assertWatchMultipleKey() {
PostShardingCenterRepositoryEventListener postShardingCenterRepositoryEventListener = new PostShardingCenterRepositoryEventListener(centerRepository, Arrays.asList("test", "dev")) {
@Override
protected ShardingOrchestrationEvent createShardingOrchestrationEvent(final DataChangedEvent event) {
return mock(ShardingOrchestrationEvent.class);
}
};
postShardingCenterRepositoryEventListener.watch();
verify(centerRepository).watch(eq("test"), ArgumentMatchers.any());
verify(centerRepository).watch(eq("dev"), ArgumentMatchers.any());
}
}
| shardingjdbc/sharding-jdbc | sharding-orchestration/sharding-orchestration-core/sharding-orchestration-core-common/src/test/java/org/apache/shardingsphere/orchestration/core/common/listener/PostShardingCenterRepositoryEventListenerTest.java | Java | apache-2.0 | 2,915 |
package me.chanjar.weixin.common.bean.result;
import lombok.Builder;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
/**
* 微信错误码说明,请阅读: <a href="http://mp.weixin.qq.com/wiki/10/6380dc743053a91c544ffd2b7c959166.html">全局返回码说明</a>.
*
* @author Daniel Qian
*/
@Data
@Builder
public class WxError implements Serializable {
private static final long serialVersionUID = 7869786563361406291L;
private int errorCode;
private String errorMsg;
private String json;
public static WxError fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxError.class);
}
@Override
public String toString() {
if (this.json != null) {
return this.json;
}
return "错误: Code=" + this.errorCode + ", Msg=" + this.errorMsg;
}
}
| chunwei/weixin-java-tools | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java | Java | apache-2.0 | 867 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace NuGet.ShimV3
{
internal class ShimWebResponse : WebResponse
{
private Stream _stream;
private Uri _uri;
private string _contentType;
private WebHeaderCollection _headers;
private HttpStatusCode _statusCode;
public ShimWebResponse(Stream stream, Uri uri, string contentType, HttpStatusCode statusCode)
: base()
{
_stream = stream;
_uri = uri;
_contentType = contentType;
_headers = new WebHeaderCollection();
_statusCode = statusCode;
_headers.Add("content-type", _contentType);
}
public override Stream GetResponseStream()
{
return _stream;
}
public override Uri ResponseUri
{
get
{
return _uri;
}
}
public HttpStatusCode StatusCode
{
get
{
return _statusCode;
}
}
public override long ContentLength
{
get
{
return _stream.Length;
}
set
{
throw new NotImplementedException();
}
}
public override string ContentType
{
get
{
return _contentType;
}
set
{
throw new NotImplementedException();
}
}
public override WebHeaderCollection Headers
{
get
{
return _headers;
}
}
}
}
| pratikkagda/nuget | src/ShimV3/ShimWebResponse.cs | C# | apache-2.0 | 1,832 |
<?php
/**
* Copyright (c) 2014 ScientiaMobile, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Refer to the COPYING.txt file distributed with this package.
*
*
* @category WURFL
* @package WURFL_Handlers
* @copyright ScientiaMobile, Inc.
* @license GNU Affero General Public License
* @version $id$
*/
/**
* PhilipsUserAgentHandler
*
*
* @category WURFL
* @package WURFL_Handlers
* @copyright ScientiaMobile, Inc.
* @license GNU Affero General Public License
* @version $id$
*/
class WURFL_Handlers_PhilipsHandler extends WURFL_Handlers_Handler {
protected $prefix = "PHILIPS";
public function canHandle($userAgent) {
if (WURFL_Handlers_Utils::isDesktopBrowser($userAgent)) return false;
return (WURFL_Handlers_Utils::checkIfStartsWith($userAgent, "Philips") || WURFL_Handlers_Utils::checkIfStartsWith($userAgent, "PHILIPS"));
}
}
| ahoken/phptest | src/zend_test/library/wurfl-php/WURFL/Handlers/PhilipsHandler.php | PHP | apache-2.0 | 1,093 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.lookup;
import com.google.common.collect.Maps;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.apache.lucene.index.LeafReaderContext;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
*
*/
public class DocLookup implements Map {
private final Map<String, ScriptDocValues> localCacheFieldData = Maps.newHashMapWithExpectedSize(4);
private final MapperService mapperService;
private final IndexFieldDataService fieldDataService;
@Nullable
private final String[] types;
private LeafReaderContext reader;
private int docId = -1;
DocLookup(MapperService mapperService, IndexFieldDataService fieldDataService, @Nullable String[] types) {
this.mapperService = mapperService;
this.fieldDataService = fieldDataService;
this.types = types;
}
public MapperService mapperService() {
return this.mapperService;
}
public IndexFieldDataService fieldDataService() {
return this.fieldDataService;
}
public void setNextReader(LeafReaderContext context) {
if (this.reader == context) { // if we are called with the same reader, don't invalidate source
return;
}
this.reader = context;
this.docId = -1;
localCacheFieldData.clear();
}
public void setNextDocId(int docId) {
this.docId = docId;
}
@Override
public Object get(Object key) {
// assume its a string...
String fieldName = key.toString();
ScriptDocValues scriptValues = localCacheFieldData.get(fieldName);
if (scriptValues == null) {
FieldMapper mapper = mapperService.smartNameFieldMapper(fieldName, types);
if (mapper == null) {
throw new ElasticsearchIllegalArgumentException("No field found for [" + fieldName + "] in mapping with types " + Arrays.toString(types) + "");
}
scriptValues = fieldDataService.getForField(mapper).load(reader).getScriptValues();
localCacheFieldData.put(fieldName, scriptValues);
}
scriptValues.setNextDocId(docId);
return scriptValues;
}
@Override
public boolean containsKey(Object key) {
// assume its a string...
String fieldName = key.toString();
ScriptDocValues scriptValues = localCacheFieldData.get(fieldName);
if (scriptValues == null) {
FieldMapper mapper = mapperService.smartNameFieldMapper(fieldName, types);
if (mapper == null) {
return false;
}
}
return true;
}
@Override
public int size() {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
@Override
public Object put(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map m) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Set keySet() {
throw new UnsupportedOperationException();
}
@Override
public Collection values() {
throw new UnsupportedOperationException();
}
@Override
public Set entrySet() {
throw new UnsupportedOperationException();
}
}
| kkirsche/elasticsearch | src/main/java/org/elasticsearch/search/lookup/DocLookup.java | Java | apache-2.0 | 4,815 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.Common.Authentication
{
/// <summary>
/// Wire representation of MSI token
/// </summary>
public class ManagedServiceTokenInfo
{
[JsonProperty(PropertyName ="access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty(PropertyName = "expires_on")]
public int ExpiresOn { get; set; }
[JsonProperty(PropertyName = "not_before")]
public int NotBefore { get; set; }
[JsonProperty(PropertyName = "resource")]
public string Resource { get; set; }
[JsonProperty(PropertyName = "token_type")]
public string TokenType { get; set; }
public override string ToString()
{
return $"(AccessToken: {AccessToken}, ExpiresIn: {ExpiresIn}, ExpiresOn: {ExpiresOn}, Resource:{Resource})";
}
}
}
| devigned/azure-powershell | src/Common/Commands.Common.Authentication/Authentication/ManagedServiceTokenInfo.cs | C# | apache-2.0 | 1,848 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from decorator_helper import prog_scope
import unittest
import paddle.fluid as fluid
import numpy as np
import paddle
import warnings
class TestBackwardInferVarDataTypeShape(unittest.TestCase):
def test_backward_infer_var_data_type_shape(self):
paddle.enable_static()
program = fluid.default_main_program()
dy = program.global_block().create_var(
name="Tmp@GRAD", shape=[1, 1], dtype=np.float32, persistable=True)
# invoke warning
fluid.backward._infer_var_data_type_shape_("Tmp@GRAD",
program.global_block())
res = False
with warnings.catch_warnings():
res = True
self.assertTrue(res)
if __name__ == '__main__':
unittest.main()
| luotao1/Paddle | python/paddle/fluid/tests/unittests/test_backward_infer_var_data_type_shape.py | Python | apache-2.0 | 1,432 |
// HOM.cpp: implementation of the CHOM class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "HOM.h"
#include "occRasterizer.h"
#include "../GameFont.h"
float psOSSR = .001f;
void __stdcall CHOM::MT_RENDER()
{
MT.Enter ();
if (MT_frame_rendered!=Device.dwFrame) {
CFrustum ViewBase;
ViewBase.CreateFromMatrix (Device.mFullTransform, FRUSTUM_P_LRTB + FRUSTUM_P_FAR);
Enable ();
Render (ViewBase);
}
MT.Leave ();
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHOM::CHOM()
{
bEnabled = FALSE;
m_pModel = 0;
m_pTris = 0;
#ifdef DEBUG
Device.seqRender.Add(this,REG_PRIORITY_LOW-1000);
#endif
}
CHOM::~CHOM()
{
#ifdef DEBUG
Device.seqRender.Remove(this);
#endif
}
#pragma pack(push,4)
struct HOM_poly
{
Fvector v1,v2,v3;
u32 flags;
};
#pragma pack(pop)
IC float Area (Fvector& v0, Fvector& v1, Fvector& v2)
{
float e1 = v0.distance_to(v1);
float e2 = v0.distance_to(v2);
float e3 = v1.distance_to(v2);
float p = (e1+e2+e3)/2.f;
return _sqrt( p*(p-e1)*(p-e2)*(p-e3) );
}
void CHOM::Load ()
{
// Find and open file
string256 fName;
FS.update_path (fName,"$level$","level.hom");
if (!FS.exist(fName))
{
Msg (" WARNING: Occlusion map '%s' not found.",fName);
return;
}
Msg ("* Loading HOM: %s",fName);
IReader* fs = FS.r_open(fName);
IReader* S = fs->open_chunk(1);
// Load tris and merge them
CDB::Collector CL;
while (!S->eof())
{
HOM_poly P;
S->r (&P,sizeof(P));
CL.add_face_packed_D (P.v1,P.v2,P.v3,P.flags,0.01f);
}
// Determine adjacency
xr_vector<u32> adjacency;
CL.calc_adjacency (adjacency);
// Create RASTER-triangles
m_pTris = xr_alloc<occTri> (u32(CL.getTS()));
for (u32 it=0; it<CL.getTS(); it++)
{
CDB::TRI& clT = CL.getT()[it];
occTri& rT = m_pTris[it];
Fvector& v0 = CL.getV()[clT.verts[0]];
Fvector& v1 = CL.getV()[clT.verts[1]];
Fvector& v2 = CL.getV()[clT.verts[2]];
rT.adjacent[0] = (0xffffffff==adjacency[3*it+0])?((occTri*) (-1)):(m_pTris+adjacency[3*it+0]);
rT.adjacent[1] = (0xffffffff==adjacency[3*it+1])?((occTri*) (-1)):(m_pTris+adjacency[3*it+1]);
rT.adjacent[2] = (0xffffffff==adjacency[3*it+2])?((occTri*) (-1)):(m_pTris+adjacency[3*it+2]);
rT.flags = clT.dummy;
rT.area = Area (v0,v1,v2);
if (rT.area<EPS_L) {
Msg ("! Invalid HOM triangle (%f,%f,%f)-(%f,%f,%f)-(%f,%f,%f)",VPUSH(v0),VPUSH(v1),VPUSH(v2));
}
rT.plane.build (v0,v1,v2);
rT.skip = 0;
rT.center.add(v0,v1).add(v2).div(3.f);
}
// Create AABB-tree
m_pModel = xr_new<CDB::MODEL> ();
m_pModel->build (CL.getV(),int(CL.getVS()),CL.getT(),int(CL.getTS()));
bEnabled = TRUE;
S->close ();
FS.r_close (fs);
}
void CHOM::Unload ()
{
xr_delete (m_pModel);
xr_free (m_pTris);
bEnabled = FALSE;
}
class pred_fb {
public:
occTri* m_pTris ;
Fvector camera ;
public:
pred_fb (occTri* _t) : m_pTris(_t) {}
pred_fb (occTri* _t, Fvector& _c) : m_pTris(_t), camera(_c) {}
ICF bool operator() (CDB::RESULT& _1, CDB::RESULT& _2) {
occTri& t0 = m_pTris [_1.id];
occTri& t1 = m_pTris [_2.id];
return camera.distance_to_sqr(t0.center) < camera.distance_to_sqr(t1.center);
}
ICF bool operator() (CDB::RESULT& _1) {
occTri& T = m_pTris [_1.id];
return T.skip>Device.dwFrame;
}
};
void CHOM::Render_DB (CFrustum& base)
{
// Query DB
xrc.frustum_options (0);
xrc.frustum_query (m_pModel,base);
if (0==xrc.r_count()) return;
// Prepare
CDB::RESULT* it = xrc.r_begin ();
CDB::RESULT* end = xrc.r_end ();
Fvector COP = Device.vCameraPosition;
end = std::remove_if (it,end,pred_fb(m_pTris));
std::sort (it,end,pred_fb(m_pTris,COP));
float view_dim = occ_dim_0;
Fmatrix m_viewport = {
view_dim/2.f, 0.0f, 0.0f, 0.0f,
0.0f, -view_dim/2.f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
view_dim/2.f + 0 + 0, view_dim/2.f + 0 + 0, 0.0f, 1.0f
};
Fmatrix m_viewport_01 = {
1.f/2.f, 0.0f, 0.0f, 0.0f,
0.0f, -1.f/2.f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
1.f/2.f + 0 + 0, 1.f/2.f + 0 + 0, 0.0f, 1.0f
};
m_xform.mul (m_viewport, Device.mFullTransform);
m_xform_01.mul (m_viewport_01, Device.mFullTransform);
// Build frustum with near plane only
CFrustum clip;
clip.CreateFromMatrix (Device.mFullTransform,FRUSTUM_P_NEAR);
sPoly src,dst;
u32 _frame = Device.dwFrame ;
#ifdef DEBUG
tris_in_frame = xrc.r_count();
tris_in_frame_visible = 0;
#endif
// Perfrom selection, sorting, culling
for (; it!=end; it++)
{
// Control skipping
occTri& T = m_pTris [it->id];
u32 next = _frame + ::Random.randI(3,10);
// Test for good occluder - should be improved :)
if (!(T.flags || (T.plane.classify(COP)>0)))
{ T.skip=next; continue; }
// Access to triangle vertices
CDB::TRI& t = m_pModel->get_tris() [it->id];
Fvector* v = m_pModel->get_verts();
src.clear (); dst.clear ();
src.push_back (v[t.verts[0]]);
src.push_back (v[t.verts[1]]);
src.push_back (v[t.verts[2]]);
sPoly* P = clip.ClipPoly (src,dst);
if (0==P) { T.skip=next; continue; }
// XForm and Rasterize
#ifdef DEBUG
tris_in_frame_visible ++;
#endif
u32 pixels = 0;
int limit = int(P->size())-1;
for (int v=1; v<limit; v++) {
m_xform.transform (T.raster[0],(*P)[0]);
m_xform.transform (T.raster[1],(*P)[v+0]);
m_xform.transform (T.raster[2],(*P)[v+1]);
pixels += Raster.rasterize(&T);
}
if (0==pixels) { T.skip=next; continue; }
}
}
void CHOM::Render (CFrustum& base)
{
if (!bEnabled) return;
Device.Statistic->RenderCALC_HOM.Begin ();
Raster.clear ();
Render_DB (base);
Raster.propagade ();
MT_frame_rendered = Device.dwFrame;
Device.Statistic->RenderCALC_HOM.End ();
}
ICF BOOL xform_b0 (Fvector2& min, Fvector2& max, float& minz, Fmatrix& X, float _x, float _y, float _z)
{
float z = _x*X._13 + _y*X._23 + _z*X._33 + X._43; if (z<EPS) return TRUE;
float iw = 1.f/(_x*X._14 + _y*X._24 + _z*X._34 + X._44);
min.x=max.x = (_x*X._11 + _y*X._21 + _z*X._31 + X._41)*iw;
min.y=max.y = (_x*X._12 + _y*X._22 + _z*X._32 + X._42)*iw;
minz = 0.f+z*iw;
return FALSE;
}
ICF BOOL xform_b1 (Fvector2& min, Fvector2& max, float& minz, Fmatrix& X, float _x, float _y, float _z)
{
float t;
float z = _x*X._13 + _y*X._23 + _z*X._33 + X._43; if (z<EPS) return TRUE;
float iw = 1.f/(_x*X._14 + _y*X._24 + _z*X._34 + X._44);
t = (_x*X._11 + _y*X._21 + _z*X._31 + X._41)*iw; if (t<min.x) min.x=t; else if (t>max.x) max.x=t;
t = (_x*X._12 + _y*X._22 + _z*X._32 + X._42)*iw; if (t<min.y) min.y=t; else if (t>max.y) max.y=t;
t = 0.f+z*iw; if (t<minz) minz =t;
return FALSE;
}
IC BOOL _visible (Fbox& B, Fmatrix& m_xform_01)
{
// Find min/max points of xformed-box
Fvector2 min,max;
float z;
if (xform_b0(min,max,z,m_xform_01,B.min.x, B.min.y, B.min.z)) return TRUE;
if (xform_b1(min,max,z,m_xform_01,B.min.x, B.min.y, B.max.z)) return TRUE;
if (xform_b1(min,max,z,m_xform_01,B.max.x, B.min.y, B.max.z)) return TRUE;
if (xform_b1(min,max,z,m_xform_01,B.max.x, B.min.y, B.min.z)) return TRUE;
if (xform_b1(min,max,z,m_xform_01,B.min.x, B.max.y, B.min.z)) return TRUE;
if (xform_b1(min,max,z,m_xform_01,B.min.x, B.max.y, B.max.z)) return TRUE;
if (xform_b1(min,max,z,m_xform_01,B.max.x, B.max.y, B.max.z)) return TRUE;
if (xform_b1(min,max,z,m_xform_01,B.max.x, B.max.y, B.min.z)) return TRUE;
return Raster.test (min.x,min.y,max.x,max.y,z);
}
BOOL CHOM::visible (Fbox3& B)
{
if (!bEnabled) return TRUE;
if (B.contains(Device.vCameraPosition)) return TRUE;
return _visible (B,m_xform_01) ;
}
BOOL CHOM::visible (Fbox2& B, float depth)
{
if (!bEnabled) return TRUE;
return Raster.test (B.min.x,B.min.y,B.max.x,B.max.y,depth);
}
BOOL CHOM::visible (vis_data& vis)
{
if (Device.dwFrame<vis.hom_frame) return TRUE; // not at this time :)
if (!bEnabled) return TRUE; // return - everything visible
// Now, the test time comes
// 0. The object was hidden, and we must prove that each frame - test | frame-old, tested-new, hom_res = false;
// 1. The object was visible, but we must to re-check it - test | frame-new, tested-???, hom_res = true;
// 2. New object slides into view - delay test| frame-old, tested-old, hom_res = ???;
u32 frame_current = Device.dwFrame;
// u32 frame_prev = frame_current-1;
#ifdef DEBUG
Device.Statistic->RenderCALC_HOM.Begin ();
#endif
BOOL result = _visible (vis.box,m_xform_01);
u32 delay = 1;
if (result)
{
// visible - delay next test
delay = ::Random.randI (5*2,5*5);
} else {
// hidden - shedule to next frame
}
vis.hom_frame = frame_current + delay;
vis.hom_tested = frame_current ;
#ifdef DEBUG
Device.Statistic->RenderCALC_HOM.End ();
#endif
return result;
}
BOOL CHOM::visible (sPoly& P)
{
if (!bEnabled) return TRUE;
// Find min/max points of xformed-box
Fvector2 min,max;
float z;
if (xform_b0(min,max,z,m_xform_01,P.front().x,P.front().y,P.front().z)) return TRUE;
for (u32 it=1; it<P.size(); it++)
if (xform_b1(min,max,z,m_xform_01,P[it].x,P[it].y,P[it].z)) return TRUE;
return Raster.test (min.x,min.y,max.x,max.y,z);
}
void CHOM::Disable ()
{
bEnabled = FALSE;
}
void CHOM::Enable ()
{
bEnabled = m_pModel?TRUE:FALSE;
}
#ifdef DEBUG
void CHOM::OnRender ()
{
if (psDeviceFlags.is(rsOcclusionDraw)){
if (m_pModel){
DEFINE_VECTOR (FVF::L,LVec,LVecIt);
static LVec poly; poly.resize(m_pModel->get_tris_count()*3);
static LVec line; line.resize(m_pModel->get_tris_count()*6);
for (int it=0; it<m_pModel->get_tris_count(); it++){
CDB::TRI* T = m_pModel->get_tris()+it;
Fvector* verts = m_pModel->get_verts();
poly[it*3+0].set(*(verts+T->verts[0]),0x80FFFFFF);
poly[it*3+1].set(*(verts+T->verts[1]),0x80FFFFFF);
poly[it*3+2].set(*(verts+T->verts[2]),0x80FFFFFF);
line[it*6+0].set(*(verts+T->verts[0]),0xFFFFFFFF);
line[it*6+1].set(*(verts+T->verts[1]),0xFFFFFFFF);
line[it*6+2].set(*(verts+T->verts[1]),0xFFFFFFFF);
line[it*6+3].set(*(verts+T->verts[2]),0xFFFFFFFF);
line[it*6+4].set(*(verts+T->verts[2]),0xFFFFFFFF);
line[it*6+5].set(*(verts+T->verts[0]),0xFFFFFFFF);
}
RCache.set_xform_world(Fidentity);
// draw solid
Device.SetNearer(TRUE);
RCache.set_Shader (Device.m_SelectionShader);
RCache.dbg_Draw (D3DPT_TRIANGLELIST,&*poly.begin(),poly.size()/3);
Device.SetNearer(FALSE);
// draw wire
if (bDebug){
RImplementation.rmNear();
}else{
Device.SetNearer(TRUE);
}
RCache.set_Shader (Device.m_SelectionShader);
RCache.dbg_Draw (D3DPT_LINELIST,&*line.begin(),line.size()/2);
if (bDebug){
RImplementation.rmNormal();
}else{
Device.SetNearer(FALSE);
}
}
}
}
void CHOM::stats()
{
if (m_pModel){
CGameFont& F = *Device.Statistic->Font();
F.OutNext (" **** HOM-occ ****");
F.OutNext (" visible: %2d", tris_in_frame_visible);
F.OutNext (" frustum: %2d", tris_in_frame);
F.OutNext (" total: %2d", m_pModel->get_tris_count());
}
}
#endif | OLR-xray/XRay-NEW | XRay/xr_3da/xrRender_R2/HOM.cpp | C++ | apache-2.0 | 11,180 |
<?php
/**
* This file is part of the OpenPNE package.
* (c) OpenPNE Project (http://www.openpne.jp/)
*
* For the full copyright and license information, please view the LICENSE
* file and the NOTICE file that were distributed with this source code.
*/
/**
* opUtilHelper provides basic utility helper functions.
*
* @package OpenPNE
* @subpackage helper
* @author Kousuke Ebihara <ebihara@tejimaya.com>
* @author Rimpei Ogawa <ogawa@tejimaya.com>
*/
/**
* Creates a <a> link tag for the pager link
*
* @param string $name
* @param string $internal_uri
* @param integer $page_no
* @param options $options
* @return string
*/
function op_link_to_for_pager($name, $internal_uri, $page_no, $options)
{
$html_options = _parse_attributes($options);
$html_options = _convert_options_to_javascript($html_options);
$absolute = false;
if (isset($html_options['absolute_url']))
{
$absolute = (boolean) $html_options['absolute'];
unset($html_options['absolute_url']);
}
$internal_uri = sprintf($internal_uri, $page_no);
$html_options['href'] = url_for($internal_uri, $absolute);
if (isset($html_options['query_string']))
{
if (false !== strpos($html_options['href'], '?'))
{
$html_options['href'] .= '&'.$html_options['query_string'];
}
else
{
$html_options['href'] .= '?'.$html_options['query_string'];
}
unset($html_options['query_string']);
}
if (!strlen($name))
{
$name = $html_options['href'];
}
return content_tag('a', $name, $html_options);
}
/**
* Includes a navigation for paginated list
*
* @param sfPager $pager
* @param string $internal_uri
* @param array $options
*/
function op_include_pager_navigation($pager, $internal_uri, $options = array())
{
$uri = url_for($internal_uri);
if (isset($options['use_current_query_string']) && $options['use_current_query_string'])
{
$options['query_string'] = sfContext::getInstance()->getRequest()->getCurrentQueryString();
$pageFieldName = isset($options['page_field_name']) ? $options['page_field_name'] : 'page';
$options['query_string'] = preg_replace('/'.$pageFieldName.'=\d\&*/', '', $options['query_string']);
unset($options['page_field_name']);
unset($options['use_current_query_string']);
}
if (isset($options['query_string']))
{
$options['link_options']['query_string'] = $options['query_string'];
unset($options['query_string']);
}
$params = array(
'pager' => $pager,
'internalUri' => $internal_uri,
'options' => new opPartsOptionHolder($options)
);
$pager = sfOutputEscaper::unescape($pager);
if ($pager instanceof sfReversibleDoctrinePager)
{
include_partial('global/pagerReversibleNavigation', $params);
}
else
{
include_partial('global/pagerNavigation', $params);
}
}
/**
* Includes pager total
*
* @param sfPager $pager
*/
function op_include_pager_total($pager)
{
include_partial('global/pagerTotal', array('pager' => $pager));
}
/**
* Returns a navigation for paginated list.
*
* @deprecated since 3.0.3
* @param sfPager $pager
* @param string $link_to A path to go to next/previous page.
"%d" will be converted to number of page.
* @return string A navigation for paginated list.
*/
function pager_navigation($pager, $link_to, $is_total = true, $query_string = '')
{
use_helper('Debug');
log_message('pager_navigation() is deprecated.', 'err');
$params = array(
'pager' => $pager,
'link_to' => $link_to,
'options' => new opPartsOptionHolder(array(
'is_total' => $is_total,
'query_string' => $query_string
)
));
return get_partial('global/pagerNavigation', $params);
}
/**
* Returns a pager total
*
* @deprecated since 3.0.3
* @param sfPager $pager
* @return string
*/
function pager_total($pager)
{
use_helper('Debug');
log_message('pager_total() is deprecated.', 'err');
return get_partial('global/pagerTotal', array('pager' => $pager));
}
function cycle_vars($name, $items, $delimiter = ',')
{
static $cycles = array();
if (!isset($cycles[$name]))
{
$cycles[$name] = array(
'count' => 0,
'items' => explode($delimiter, $items),
);
}
$items = $cycles[$name]['items'];
$result = $items[$cycles[$name]['count']];
$cycles[$name]['count']++;
if ($cycles[$name]['count'] >= count($items))
{
$cycles[$name]['count'] = 0;
}
return $result;
}
/**
* Returns a project URL is over an application.
*
* @see url_for()
*
* @param string $application
*
* @return string
*/
function app_url_for()
{
$arguments = func_get_args();
if (is_array($arguments[1]) || '@' == substr($arguments[1], 0, 1) || false !== strpos($arguments[1], '/'))
{
return call_user_func_array('_app_url_for_internal_uri', $arguments);
}
else
{
return call_user_func_array('_app_url_for_route', $arguments);
}
}
function _app_url_for_route($application, $routeName, $params = array(), $absolute = false)
{
$params = array_merge(array('sf_route' => $routeName), is_object($params) ? array('sf_subject' => $params) : $params);
return _app_url_for_internal_uri($application, $params, $absolute);
}
function _app_url_for_internal_uri($application, $internal_uri, $absolute = false)
{
return sfContext::getInstance()->getConfiguration()->generateAppUrl($application, $internal_uri, $absolute);
}
function _create_script_name($application, $environment)
{
$script_name = $application;
if ('prod' !== $environment)
{
$script_name .= '_'.$environment;
}
$script_name .= '.php';
return $script_name;
}
function op_format_date($date, $format = 'd', $culture = null, $charset = null)
{
use_helper('Date');
if (!$culture)
{
$culture = sfContext::getInstance()->getUser()->getCulture();
}
switch ($format)
{
case 'XShortDate':
switch ($culture)
{
case 'ja_JP':
$format = 'MM/dd';
break;
default:
$format = 'm';
break;
}
break;
case 'XShortDateJa':
switch ($culture)
{
case 'ja_JP':
$format = 'MM月dd日';
break;
default:
$format = 'm';
break;
}
break;
case 'XDateTime':
switch ($culture)
{
case 'ja_JP':
$format = 'yyyy/MM/dd HH:mm';
break;
default:
$format = 'f';
break;
}
break;
case 'XDateTimeJa':
switch ($culture)
{
case 'ja_JP':
$format = 'yyyy年MM月dd日 HH:mm';
break;
default:
$format = 'f';
break;
}
break;
case 'XDateTimeJaBr':
switch ($culture)
{
case 'ja_JP':
$format = "yyyy年\nMM月dd日\nHH:mm";
break;
default:
$format = 'f';
break;
}
break;
case 'XCalendarMonth':
switch ($culture)
{
case 'ja_JP':
$format = 'yyyy年M月';
break;
default:
$format = 'MMMM yyyy';
break;
}
break;
}
return format_date($date, $format, $culture, $charset);
}
if (!defined('SF_AUTO_LINK_RE'))
{
define('SF_AUTO_LINK_RE', '~
( # leading text
<\w+.*?>| # leading HTML tag, or
[^=!:\'"/]| # leading punctuation, or
^| # beginning of line, or
\s? # leading whitespaces
)
(
(?:https?://)| # protocol spec, or
(?:www\.) # www.*
)
(
[-\w]+ # subdomain or domain
(?:\.[-\w]+)* # remaining subdomains or domain
(?::\d+)? # port
\/?
[a-zA-Z0-9_\-\/.,:;\~\?@&=+$%#!()]*
)
([^a-zA-Z0-9_\-\/.,:;\~\?@&=+$%#!()]|\s|<|$) # trailing text
~xu');
}
function op_url_cmd($text)
{
return preg_replace_callback(SF_AUTO_LINK_RE, '_op_url_cmd', $text);
}
function _op_url_cmd($matches)
{
$url = $matches[2].$matches[3];
$cmd = '';
if ('www.' == $matches[2])
{
$cmd .= 'www.';
$url = 'http://www.'.$url;
}
if (preg_match('/([a-zA-Z0-9\-.]+)\/?(?:[a-zA-Z0-9_\-\/.,:;\~\?@&=+$%#!()])*/', $matches[3], $pmatch))
{
$cmd .= $pmatch[1];
}
$file = $cmd.'.js';
$path = './cmd/'.$file;
if (preg_match('/<a/', $matches[1]) || !is_readable($path))
{
return op_auto_link_text($matches[0]);
}
sfContext::getInstance()->getResponse()->addJavascript('util');
$googlemapsUrl = url_for('@google_maps');
$public_path = _compute_public_path($file, 'cmd', 'js');
$result = <<<EOD
<script type="text/javascript" src="{$public_path}"></script>
<script type="text/javascript">
<!--
url2cmd('{$url}', '{$googlemapsUrl}');
//-->
</script>
EOD;
return $result.$matches[4];
}
/**
* @see auto_link_text
*/
function op_auto_link_text($text, $link = 'urls', $href_options = array('target' => '_blank'), $truncate = true, $truncate_len = 57, $pad = '...')
{
use_helper('Text');
return auto_link_text($text, $link, $href_options, $truncate, $truncate_len, $pad);
}
/**
* op_auto_link_text_for_mobile
*
* @param string $text
* @param mixed $link Types of text that is linked. (all|urls|email_addresses|phone_numbers)
* @param boolean $truncate
* @param integer $truncate_len
* @param string $pad
* @param boolean $is_allow_outer_url
*/
function op_auto_link_text_for_mobile($text, $link = null, $href_options = array(), $truncate = true, $truncate_len = 37, $pad = '...', $is_allow_outer_url = null)
{
use_helper('Text');
if (is_null($link))
{
$link = sfConfig::get('op_default_mobile_auto_link_type', 'urls');
}
if (!$link)
{
return $text;
}
if (!is_array($link))
{
$link = array($link);
}
if (in_array('all', $link))
{
$link = array('urls', 'email_addresses', 'phone_numbers');
}
if (is_null($is_allow_outer_url))
{
$is_allow_outer_url = sfConfig::get('op_default_mobile_auto_link_is_allow_outer_url', true);
}
$result = $text;
if (in_array('email_addresses', $link))
{
$result = _auto_link_email_addresses($result);
}
if (in_array('phone_numbers', $link))
{
$result = _op_auto_links_phone_number($result);
}
if (in_array('urls', $link))
{
$result = _op_auto_links_urls($result, $href_options, $truncate, $truncate_len, $pad);
if ($is_allow_outer_url)
{
$result = _op_auto_links_outer_urls($result, $href_options, $truncate, $truncate_len, $pad);
}
}
return $result;
}
function _op_auto_links_urls($text, $href_options = array(), $truncate = false, $truncate_len = 40, $pad = '...')
{
$request = sfContext::getInstance()->getRequest();
$pathArray = $request->getPathInfoArray();
$host = explode(':', $request->getHost());
$script_name = basename($request->getScriptName());
if ('index.php' === $script_name)
{
$script_name = '';
}
elseif ($script_name)
{
$script_name = '/'.$script_name;
}
if (1 == count($host))
{
$host[] = isset($pathArray['SERVER_PORT']) ? $pathArray['SERVER_PORT'] : '';
}
if (80 == $host[1] || 443 == $host[1] || empty($host[1]))
{
unset($host[1]);
}
$pattern = '/
(
<\w+.*?>| # leading HTML tag, or
[^=!:\'"\/]| # leading punctuation, or
^ # beginning of line
)
(
(?:https?:\/\/) # protocol spec, or
)
(
'.preg_quote(implode(':', $host), '/').'
)
(
'.preg_quote($request->getRelativeUrlRoot() ? $request->getRelativeUrlRoot() : '', '/').'
)
(?:\/[^\/]+?\.php)?
(
[a-zA-Z0-9_\-\/.,:;\~\?@&=+$%#!()]*
)
([[:punct:]]|\s|<|$) # trailing text
/x';
$href_options = _tag_options($href_options);
$callback_function = '
if (preg_match("/<a\s/i", $matches[1]))
{
return $matches[0];
}
';
if ($truncate)
{
$callback_function .= '
else if (strlen($matches[5]) > '.$truncate_len.')
{
return $matches[1].\'<a href="\'.$matches[4].\''.$script_name.'\'.$matches[5].\'"'.$href_options.'>\'.substr($matches[5], 0, '.$truncate_len.').\''.$pad.'</a>\'.$matches[6];
}
';
}
$callback_function .= '
else
{
return $matches[1].\'<a href="\'.$matches[4].\''.$script_name.'\'.$matches[5].\'"'.$href_options.'>\'.$matches[5].\'</a>\'.$matches[6];
}
';
return preg_replace_callback(
$pattern,
create_function('$matches', $callback_function),
$text
);
}
function _op_auto_links_outer_urls($text, $href_options = array(), $truncate = false, $truncate_len = 40, $pad = '...')
{
$request = sfContext::getInstance()->getRequest();
$href_options = _tag_options($href_options);
$proxyAction = $request->getUriPrefix().$request->getRelativeUrlRoot().'/proxy';
$callback_function = '
if (preg_match("/<a\s/i", $matches[1]))
{
return $matches[0];
}
';
if ($truncate)
{
$callback_function .= '
else if (strlen($matches[2].$matches[3]) > '.$truncate_len.')
{
return $matches[1].\'<a href="'.$proxyAction.'?url=\'.urlencode(($matches[2] == "www." ? "http://www." : $matches[2]).$matches[3]).\'"'.$href_options.'>\'.substr($matches[2].$matches[3], 0, '.$truncate_len.').\''.$pad.'</a>\'.$matches[4];
}
';
}
$callback_function .= '
else
{
return $matches[1].\'<a href="'.$proxyAction.'?url=\'.urlencode(($matches[2] == "www." ? "http://www." : $matches[2]).$matches[3]).\'"'.$href_options.'>\'.$matches[2].$matches[3].\'</a>\'.$matches[4];
}
';
return preg_replace_callback(
SF_AUTO_LINK_RE,
create_function('$matches', $callback_function),
$text
);
}
function _op_auto_links_phone_number($text)
{
return preg_replace('/\b((0\d{1,3})-?(\d{2,4})-?(\d{4}))\b/', '<a href="tel:\\2\\3\\4">\\1</a>', $text);
}
/**
* truncates a string
*
* @param string $string
* @param int $width
* @param string $etc
* @param int $rows
* @param bool $is_html
*
* @return string
*/
function op_truncate($string, $width = 80, $etc = '', $rows = 1, $is_html = true)
{
$rows = (int)$rows;
if (!($rows > 0))
{
$rows = 1;
}
// converts special chars
$trans = array(
"\r\n" => ' ',
"\r" => ' ',
"\n" => ' ',
);
// converts special chars (for HTML)
if ($is_html)
{
$trans += array(
// for htmlspecialchars
'&' => '&',
'<' => '<',
'>' => '>',
'"' => '"',
''' => "'",
// for IE's bug
' ' => ' ',
);
}
$string = strtr($string, $trans);
$result = array();
$p_string = $string;
for ($i = 1; $i <= $rows; $i++)
{
if ($i === $rows)
{
$p_etc = $etc;
}
else
{
$p_etc = '';
}
if ($i > 0)
{
// strips the string of pre-line
if (isset($result[$i - 1]))
{
$p_string = substr($p_string, strlen($result[$i - 1]));
}
if (!$p_string && ($p_string !== '0'))
{
break;
}
}
$result[$i] = op_truncate_callback($p_string, $width, $p_etc);
}
$string = implode("\n", $result);
if ($is_html)
{
$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
return nl2br($string);
}
function op_truncate_callback($string, $width, $etc = '')
{
$width = $width - mb_strwidth($etc);
if (mb_strwidth($string) > $width)
{
// for Emoji
$offset = 0;
$tmp_string = $string;
while (preg_match('/\[[ies]:[0-9]{1,3}\]/', $tmp_string, $matches, PREG_OFFSET_CAPTURE))
{
$emoji_str = $matches[0][0];
$emoji_pos = $matches[0][1] + $offset;
$emoji_len = strlen($emoji_str);
$emoji_width = $emoji_len;
// a width by Emoji
$substr_width = mb_strwidth(substr($string, 0, $emoji_pos));
if ($substr_width >= $width) // Emoji position is after a width
{
break;
}
if ($substr_width + 2 == $width) // substr_width + Emoji width is equal to a width
{
$width = $substr_width + $emoji_width;
break;
}
if ($substr_width + 2 > $width) // substr_width + Emoji width is rather than a width
{
$width = $substr_width;
break;
}
// less than a width
$offset = $emoji_pos + $emoji_len;
$width = $width + $emoji_width - 2;
$tmp_string = substr($string, $offset);
}
$string = mb_strimwidth($string, 0, $width, '', 'UTF-8').$etc;
}
return $string;
}
function op_within_page_link($marker = '▼')
{
static $n = 0;
$options = array();
if ($n)
{
$options['name'] = sprintf('a%d', $n);
}
if ($marker)
{
$options['href'] = sprintf('#a%d', $n+1);
}
$n++;
return content_tag('a', $marker, $options);
}
function op_mail_to($route, $params = array(), $name = '', $options = array(), $default_value = array())
{
$configuration = sfContext::getInstance()->getConfiguration();
$configPath = '/mobile_mail_frontend/config/routing.yml';
$files = array_merge(array(sfConfig::get('sf_apps_dir').$configPath), $configuration->globEnablePlugin('/apps'.$configPath));
$user = sfContext::getInstance()->getUser();
if (sfConfig::get('op_is_mail_address_contain_hash') && $user->hasCredential('SNSMember'))
{
$params['hash'] = $user->getMember()->getMailAddressHash();
}
$routing = new opMailRouting(new sfEventDispatcher());
$config = new sfRoutingConfigHandler();
$routes = $config->evaluate($files);
$routing->setRoutes(array_merge(sfContext::getInstance()->getRouting()->getRoutes(), $routes));
return mail_to($routing->generate($route, $params), $name, $options, $default_value);
}
function op_banner($name)
{
$banner = Doctrine::getTable('Banner')->findByName($name);
if (!$banner)
{
return false;
}
if ($banner->getIsUseHtml())
{
return $banner->getHtml();
}
$bannerImage = $banner->getRandomImage();
if (!$bannerImage)
{
return false;
}
$imgHtml = image_tag_sf_image($bannerImage->getFile(), array('alt' => $bannerImage->getName()));
if ($bannerImage->getUrl() != '')
{
return link_to($imgHtml, $bannerImage->getUrl(), array('target' => '_blank'));
}
return $imgHtml;
}
function op_have_privilege($privilege, $member_id = null, $route = null)
{
if (!$member_id)
{
$member_id = sfContext::getInstance()->getUser()->getMemberId();
}
if (!$route)
{
$route = sfContext::getInstance()->getRequest()->getAttribute('sf_route');
}
return $route->getAcl()->isAllowed($member_id, null, $privilege);
}
function op_have_privilege_by_uri($uri, $params = array(), $member_id = null)
{
$routing = sfContext::getInstance()->getRouting();
$routes = $routing->getRoutes();
if (empty($routes[$uri]))
{
return true;
}
$route = clone $routes[$uri];
if ($route instanceof opDynamicAclRoute)
{
$route->bind(sfContext::getInstance(), $params);
try
{
$route->getObject();
}
catch (sfError404Exception $e)
{
// do nothing
}
$options = $route->getOptions();
return op_have_privilege($options['privilege'], $member_id, $route);
}
return true;
}
function op_decoration($string, $is_strip = false, $is_use_stylesheet = null, $is_html_tag_followup = true)
{
if (is_null($is_use_stylesheet))
{
$is_use_stylesheet = true;
if ('mobile_frontend' == sfConfig::get('sf_app'))
{
$is_use_stylesheet = false;
}
}
return opWidgetFormRichTextareaOpenPNE::toHtml($string, $is_strip, $is_use_stylesheet, $is_html_tag_followup);
}
function op_is_accessible_url($uri)
{
if ('/' === $uri[0] || preg_match('#^[a-z][a-z0-9\+.\-]*\://#i', $uri))
{
return true;
}
$info = sfContext::getInstance()->getController()->convertUrlStringToParameters($uri);
if (!empty($info[0]))
{
return sfContext::getInstance()->getRouting()->hasRouteName($info[0]);
}
elseif (!empty($info[1]))
{
return sfContext::getInstance()->getController()->actionExists($info[1]['module'], $info[1]['action']);
}
}
/**
* just for BC
*/
function op_is_accessable_url($uri)
{
return op_is_accessible_url($uri);
}
function op_distance_of_time_in_words($from_time, $to_time, $include_seconds = false, $format = '%s ago')
{
$to_time = $to_time ? $to_time: time();
$distance_in_minutes = floor(abs($to_time - $from_time) / 60);
$distance_in_seconds = floor(abs($to_time - $from_time));
$string = '';
$parameters = array();
if ($distance_in_minutes <= 1)
{
if (!$include_seconds)
{
$string = $distance_in_minutes == 0 ? 'less than a minute' : '1 minute';
}
else
{
if ($distance_in_seconds <= 5)
{
$string = 'less than 5 seconds';
}
else if ($distance_in_seconds >= 6 && $distance_in_seconds <= 10)
{
$string = 'less than 10 seconds';
}
else if ($distance_in_seconds >= 11 && $distance_in_seconds <= 20)
{
$string = 'less than 20 seconds';
}
else if ($distance_in_seconds >= 21 && $distance_in_seconds <= 40)
{
$string = 'half a minute';
}
else if ($distance_in_seconds >= 41 && $distance_in_seconds <= 59)
{
$string = 'less than a minute';
}
else
{
$string = '1 minute';
}
}
}
else if ($distance_in_minutes >= 2 && $distance_in_minutes <= 44)
{
$string = '%minutes% minutes';
$parameters['%minutes%'] = $distance_in_minutes;
}
else if ($distance_in_minutes >= 45 && $distance_in_minutes <= 89)
{
$string = 'about 1 hour';
}
else if ($distance_in_minutes >= 90 && $distance_in_minutes <= 1439)
{
$string = 'about %hours% hours';
$parameters['%hours%'] = round($distance_in_minutes / 60);
}
else if ($distance_in_minutes >= 1440 && $distance_in_minutes <= 2879)
{
$string = '1 day';
}
else if ($distance_in_minutes >= 2880 && $distance_in_minutes <= 43199)
{
$string = '%days% days';
$parameters['%days%'] = round($distance_in_minutes / 1440);
}
else if ($distance_in_minutes >= 43200 && $distance_in_minutes <= 86399)
{
$string = 'about 1 month';
}
else if ($distance_in_minutes >= 86400 && $distance_in_minutes <= 525959)
{
$string = '%months% months';
$parameters['%months%'] = round($distance_in_minutes / 43200);
}
else if ($distance_in_minutes >= 525960 && $distance_in_minutes <= 1051919)
{
$string = 'about 1 year';
}
else
{
$string = 'over %years% years';
$parameters['%years%'] = floor($distance_in_minutes / 525960);
}
$string = sprintf($format, $string);
if (sfConfig::get('sf_i18n'))
{
use_helper('I18N');
return __($string, $parameters);
}
else
{
return strtr($string, $parameters);
}
}
function op_format_activity_time($from_time, $to_time = null)
{
use_helper('Date');
$to_time = $to_time ? $to_time: time();
$distance_in_minutes = floor(abs($to_time - $from_time) / 60);
if ($distance_in_minutes >= 1440)
{
return op_format_date($from_time, 'XDateTime');
}
else
{
return op_distance_of_time_in_words($from_time, $to_time, true);
}
}
function op_format_last_login_time($from_time, $to_time = null)
{
if (!$from_time)
{
$string = 'not login yet';
if (sfConfig::get('sf_i18n'))
{
use_helper('I18N');
return __($string);
}
else
{
return $string;
}
}
else
{
return op_distance_of_time_in_words($from_time, $to_time);
}
}
function op_url_to_id($uri)
{
return str_replace(array('/', ',', ';', '~', '?', '@', '&', '=', '+', '$', '%', '#', '!', '(', ')'), '_', $uri);
}
function op_replace_sns_term($string)
{
$config = (array)include(sfContext::getInstance()->getConfigCache()->checkConfig('config/sns_term.yml'));
foreach ($config as $k => $v)
{
$string = str_replace('%'.$k.'%', $v['caption']['en'], $string);
}
return $string;
}
/**
* Creates a <a> link tag for the member nickname
*
* @value mixed $value (string or Member object)
* @param string $options
* @param string $routeName
* @return string
*/
function op_link_to_member($value, $options = array(), $routeName = '@obj_member_profile')
{
$member = null;
if ($value instanceof sfOutputEscaper || $value instanceof Member)
{
$member = $value;
}
elseif ($value)
{
$member = Doctrine::getTable('Member')->find($value);
}
if ($member && $member->id)
{
if (!($member instanceof sfOutputEscaper))
{
$member = sfOutputEscaper::escape(sfConfig::get('sf_escaping_method'), $member);
}
$link_target = $member->name;
if (isset($options['link_target']))
{
$link_target = $options['link_target'];
unset($options['link_target']);
}
return link_to($link_target, sprintf('%s?id=%d', $routeName, $member->id), $options);
}
return sfOutputEscaper::escape(
sfConfig::get('sf_escaping_method'),
opConfig::get('nickname_of_member_who_does_not_have_credentials', '-')
);
}
/**
* Generate a gadget type name
*
* @param string $type1
* @param string $type2
* @return string
*/
function op_get_gadget_type($type1, $type2)
{
if ('gadget' == $type1)
{
return $type2;
}
$type = sfInflector::camelize($type1.'_'.$type2);
$type = strtolower(substr($type, 0, 1)).substr($type, 1);
return $type;
}
/**
* Returns a image tag
*
* @param string $source
* @param array $options
*
* @return string An image tag.
* @see image_tag_sf_image
*/
function op_image_tag_sf_image($source, $options = array())
{
if (!isset($options['no_image']))
{
$options['no_image'] = op_image_path('no_image.gif');
}
return image_tag_sf_image($source, $options);
}
/**
* Returns a image tag
*
* @param string $source
* @param array $options
*
* @return string An image tag.
* @see image_tag
*/
function op_image_tag($source, $options = array())
{
if (!isset($options['raw_name']))
{
$absolute = false;
if (isset($options['absolute']))
{
unset($options['absolute']);
$absolute = true;
}
$options['raw_name'] = true;
$source = op_image_path($source, $absolute);
}
return image_tag($source, $options);
}
/**
* Returns a image path
*
* @param string $source
* @param boolean $absolute
*
* @return string An image path.
* @see image_path
*/
function op_image_path($source, $absolute = false)
{
static $skinPlugin = null;
if (strpos($source, '://'))
{
return $source;
}
if (0 !== strpos($source, '/'))
{
if (is_null($skinPlugin))
{
$plugins = sfContext::getInstance()->getConfiguration()->getPlugins();
foreach ($plugins as $plugin)
{
if (0 === strpos($plugin, 'opSkin'))
{
$skinPlugin = $plugin;
break;
}
$skinPlugin = false;
}
}
if ($skinPlugin)
{
$file = sfConfig::get('sf_web_dir').'/'.$skinPlugin.'/images/'.$source;
if (false === strpos(basename($source), '.'))
{
$file .= '.png';
}
if (file_exists($file))
{
$source = '/'.$skinPlugin.'/images/'.$source;
}
}
}
return image_path($source, $absolute);
}
| tejima/OP3PKG | lib/helper/opUtilHelper.php | PHP | apache-2.0 | 27,373 |
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// This code was generated by google-apis-code-generator 1.5.1
// C++ generator version: 0.1.3
// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
// YouTube Data API (youtube/v3)
// Description:
// Programmatic access to YouTube features.
// Classes:
// ChannelSectionLocalization
// Documentation:
// https://developers.google.com/youtube/v3
#include "google/youtube_api/channel_section_localization.h"
#include <string>
#include "googleapis/client/data/jsoncpp_data.h"
#include "googleapis/strings/stringpiece.h"
#include <string>
#include "googleapis/strings/strcat.h"
namespace google_youtube_api {
using namespace googleapis;
// Object factory method (static).
ChannelSectionLocalization* ChannelSectionLocalization::New() {
return new client::JsonCppCapsule<ChannelSectionLocalization>;
}
// Standard immutable constructor.
ChannelSectionLocalization::ChannelSectionLocalization(const Json::Value& storage)
: client::JsonCppData(storage) {
}
// Standard mutable constructor.
ChannelSectionLocalization::ChannelSectionLocalization(Json::Value* storage)
: client::JsonCppData(storage) {
}
// Standard destructor.
ChannelSectionLocalization::~ChannelSectionLocalization() {
}
} // namespace google_youtube_api
| rcari/google-api-cpp-client | service_apis/youtube/google/youtube_api/channel_section_localization.cc | C++ | apache-2.0 | 1,934 |
// Copyright (C) 2010 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.query.change;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.server.index.RegexPredicate;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
import dk.brics.automaton.RegExp;
import dk.brics.automaton.RunAutomaton;
class RegexRefPredicate extends RegexPredicate<ChangeData> {
private final RunAutomaton pattern;
RegexRefPredicate(String re) {
super(ChangeField.REF, re);
if (re.startsWith("^")) {
re = re.substring(1);
}
if (re.endsWith("$") && !re.endsWith("\\$")) {
re = re.substring(0, re.length() - 1);
}
this.pattern = new RunAutomaton(new RegExp(re).toAutomaton());
}
@Override
public boolean match(final ChangeData object) throws OrmException {
Change change = object.change();
if (change == null) {
return false;
}
return pattern.run(change.getDest().get());
}
@Override
public int getCost() {
return 1;
}
}
| MerritCR/merrit | gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexRefPredicate.java | Java | apache-2.0 | 1,627 |
// Python Tools for Visual Studio
// 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.
using System;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools {
public static class PythonConstants {
//Language name
public const string LanguageName = "Python";
internal const string TextEditorSettingsRegistryKey = LanguageName;
internal const string FileExtension = ".py";
internal const string ProjectFileFilter = "Python Project File (*.pyproj)\n*.pyproj\nAll Files (*.*)\n*.*\n";
/// <summary>
/// The extension for Python files which represent Windows applications.
/// </summary>
internal const string WindowsFileExtension = ".pyw";
internal const string ProjectImageList = "Microsoft.PythonImageList.png";
internal const string IssueTrackerUrl = "http://go.microsoft.com/fwlink/?LinkId=402428";
internal const string LibraryManagerGuid = "888888e5-b976-4366-9e98-e7bc01f1842c";
internal const string LibraryManagerServiceGuid = "88888859-2f95-416e-9e2b-cac4678e5af7";
public const string ProjectFactoryGuid = "888888a0-9f3d-457c-b088-3a5042f75d52";
internal const string WebProjectFactoryGuid = "1b580a1a-fdb3-4b32-83e1-6407eb2722e6";
internal const string EditorFactoryGuid = "888888c4-36f9-4453-90aa-29fa4d2e5706";
internal const string ProjectNodeGuid = "8888881a-afb8-42b1-8398-e60d69ee864d";
public const string GeneralPropertyPageGuid = "888888fd-3c4a-40da-aefb-5ac10f5e8b30";
public const string DebugPropertyPageGuid = "9A46BC86-34CB-4597-83E5-498E3BDBA20A";
public const string PublishPropertyPageGuid = "63DF0877-CF53-4975-B200-2B11D669AB00";
internal const string WebPropertyPageGuid = "76EED3B5-14B1-413B-937A-F6F79AC1F8C8";
internal const string EditorFactoryPromptForEncodingGuid = "CA887E0B-55C6-4AE9-B5CF-A2EEFBA90A3E";
internal const string InterpreterItemType = "32235F49-CF87-4F2C-A986-B38D229976A3";
internal const string InterpretersPackageItemType = "64D8C685-F085-4E04-B759-3DF715EBA3FA";
internal static readonly Guid InterpreterItemTypeGuid = new Guid(InterpreterItemType);
internal static readonly Guid InterpretersPackageItemTypeGuid = new Guid(InterpretersPackageItemType);
internal const string InterpretersPropertiesGuid = "45D3DC23-F419-4744-B55B-B897FAC1F4A2";
internal const string InterpretersWithBaseInterpreterPropertiesGuid = "F86C3C5B-CF94-4184-91F8-29687D3B9227";
internal const string InterpretersPackagePropertiesGuid = "BBF56A45-B037-4CC2-B710-F2CE304CCF32";
internal const string InterpreterListToolWindowGuid = "75504045-D02F-44E5-BF60-5F60DF380E8B";
// Do not change below info without re-requesting PLK:
internal const string ProjectSystemPackageGuid = "15490272-3C6B-4129-8E1D-795C8B6D8E9F"; //matches PLK
// IDs of the icons for product registration (see Resources.resx)
internal const int IconIfForSplashScreen = 300;
internal const int IconIdForAboutBox = 400;
// Command IDs
internal const int AddEnvironment = 0x4006;
internal const int AddVirtualEnv = 0x4007;
internal const int AddExistingVirtualEnv = 0x4008;
internal const int ActivateEnvironment = 0x4009;
internal const int InstallPythonPackage = 0x400A;
internal const int InstallRequirementsTxt = 0x4033;
internal const int GenerateRequirementsTxt = 0x4034;
internal const int OpenInteractiveForEnvironment = 0x4031;
internal const int ViewAllEnvironments = 0x400B;
internal const int AddSearchPathCommandId = 0x4002;
internal const int AddSearchPathZipCommandId = 0x4003;
internal const int AddPythonPathToSearchPathCommandId = 0x4030;
// Context menu IDs
internal const int EnvironmentsContainerMenuId = 0x2006;
internal const int EnvironmentMenuId = 0x2007;
internal const int EnvironmentPackageMenuId = 0x2008;
internal const int SearchPathContainerMenuId = 0x2009;
internal const int SearchPathMenuId = 0x200A;
// Custom (per-project) commands
internal const int FirstCustomCmdId = 0x4010;
internal const int LastCustomCmdId = 0x402F;
internal const int CustomProjectCommandsMenu = 0x2005;
// Shows up before references
internal const int InterpretersContainerNodeSortPriority = 200;
// Appears after references
internal const int SearchPathContainerNodeSortPriority = 400;
// Maximal sort priority for Search Path nodes
internal const int SearchPathNodeMaxSortPriority = 110;
internal const string InterpreterId = "InterpreterId";
internal const string InterpreterVersion = "InterpreterVersion";
internal const string LaunchProvider = "LaunchProvider";
internal const string PythonExtension = "PythonExtension";
public const string SearchPathSetting = "SearchPath";
public const string InterpreterPathSetting = "InterpreterPath";
public const string InterpreterArgumentsSetting = "InterpreterArguments";
public const string CommandLineArgumentsSetting = "CommandLineArguments";
public const string StartupFileSetting = "StartupFile";
public const string IsWindowsApplicationSetting = "IsWindowsApplication";
public const string EnvironmentSetting = "Environment";
/// <summary>
/// Specifies port to which to open web browser on launch.
/// </summary>
public const string WebBrowserPortSetting = "WebBrowserPort";
/// <summary>
/// Specifies URL to which to open web browser on launch.
/// </summary>
public const string WebBrowserUrlSetting = "WebBrowserUrl";
/// <summary>
/// Specifies local address for the web server to listen on.
/// </summary>
public const string WebServerHostSetting = "WebServerHost";
// Mixed-mode debugging project property
public const string EnableNativeCodeDebugging = "EnableNativeCodeDebugging";
public const string WorkingDirectorySetting = "WorkingDirectory";
public const string ProjectHomeSetting = "ProjectHome";
/// <summary>
/// The canonical name of the debug launcher for web projects.
/// </summary>
public const string WebLauncherName = "Web launcher";
/// <summary>
/// The settings collection where "Suppress{dialog}" settings are stored
/// </summary>
public const string DontShowUpgradeDialogAgainCollection = "PythonTools\\Dialogs";
internal const string PythonToolsProcessIdEnvironmentVariable = "_PTVS_PID";
}
}
| DinoV/PTVS | Python/Product/PythonTools/PythonConstants.cs | C# | apache-2.0 | 7,462 |
/*
* Copyright (C) 2016 Jared Rummler <jared.rummler@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jrummy.busybox.installer.activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import com.anjlab.android.iab.v3.BillingProcessor;
import com.anjlab.android.iab.v3.TransactionDetails;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.jrummy.busybox.installer.dialogs.RootCheckDialog;
import com.jrummy.busybox.installer.utils.DeviceNameHelper;
import com.jrummy.busybox.installer.utils.RootChecker;
import com.jrummyapps.android.analytics.Analytics;
import com.jrummyapps.android.animations.Technique;
import com.jrummyapps.android.app.App;
import com.jrummyapps.android.prefs.Prefs;
import com.jrummyapps.android.roottools.checks.RootCheck;
import com.jrummyapps.android.util.DeviceUtils;
import com.jrummyapps.android.util.Jot;
import com.jrummyapps.busybox.R;
import com.jrummyapps.busybox.activities.SettingsActivity;
import com.jrummyapps.busybox.utils.Monetize;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class MainActivity extends com.jrummyapps.busybox.activities.MainActivity
implements BillingProcessor.IBillingHandler {
private static final String EXTRA_ROOT_DIALOG_SHOWN = "extraRootDialogShown";
public static Intent linkIntent(Context context, String link) {
return new Intent(context, MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(EXTRA_URI_KEY, link);
}
BillingProcessor bp;
private AdView[] adViewTiers;
private int currentAdViewIndex;
private boolean rootDialogShown;
private RelativeLayout adContainer;
private InterstitialAd[] interstitialsTabAd;
private InterstitialAd[] interstitialsSettingsAd;
private InterstitialAd[] interstitialsInstallAd;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
rootDialogShown = savedInstanceState.getBoolean(EXTRA_ROOT_DIALOG_SHOWN);
}
if (!rootDialogShown) {
RootChecker.execute();
}
EventBus.getDefault().register(this);
adContainer = (RelativeLayout) findViewById(R.id.ad_view);
bp = new BillingProcessor(this, Monetize.decrypt(Monetize.ENCRYPTED_LICENSE_KEY), this);
if (Prefs.getInstance().get("loaded_purchases_from_google", true)) {
Prefs.getInstance().save("loaded_purchases_from_google", false);
bp.loadOwnedPurchasesFromGoogle();
}
if (!Monetize.isAdsRemoved()) {
currentAdViewIndex = 0;
adViewTiers = new AdView[getResources().getStringArray(R.array.banners_id).length];
setupBanners();
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override public void onPageSelected(int position) {
showTabInterstitials();
}
@Override public void onPageScrollStateChanged(int state) {
}
});
interstitialsTabAd = new InterstitialAd[getResources()
.getStringArray(R.array.tabs_interstitials_id).length];
interstitialsSettingsAd = new InterstitialAd[getResources()
.getStringArray(R.array.settings_interstitials_id).length];
interstitialsInstallAd = new InterstitialAd[getResources()
.getStringArray(R.array.install_interstitials_id).length];
setupTabInterstitialsAd();
setupSettingsInterstitialsAd();
setupInstallInterstitialsAd();
} else {
adContainer.setVisibility(View.GONE);
}
}
@Override
protected void onPause() {
if (!Monetize.isAdsRemoved()) {
for (AdView adView : adViewTiers) {
if (adView != null) {
adView.pause();
}
}
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (!Monetize.isAdsRemoved()) {
for (AdView adView : adViewTiers) {
if (adView != null) {
adView.resume();
}
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
if (bp != null) {
bp.release();
}
if (!Monetize.isAdsRemoved()) {
for (AdView adView : adViewTiers) {
if (adView != null) {
adView.destroy();
}
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(EXTRA_ROOT_DIALOG_SHOWN, rootDialogShown);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (bp.handleActivityResult(requestCode, resultCode, data)) {
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_remove_ads).setVisible(!Monetize.isAdsRemoved());
return super.onPrepareOptionsMenu(menu);
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_settings) {
showSettingsInterstitials();
return true;
} else if (itemId == R.id.action_remove_ads) {
Analytics.newEvent("remove ads menu item").log();
onEventMainThread(new Monetize.Event.RequestRemoveAds());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onProductPurchased(String productId, TransactionDetails details) {
// Called when requested PRODUCT ID was successfully purchased
Analytics.newEvent("in-app purchase").put("product_id", productId).log();
if (productId.equals(Monetize.decrypt(Monetize.ENCRYPTED_REMOVE_ADS_PRODUCT_ID))) {
Monetize.removeAds();
EventBus.getDefault().post(new Monetize.Event.OnAdsRemovedEvent());
}
}
@Override
public void onPurchaseHistoryRestored() {
// Called when requested PRODUCT ID was successfully purchased
Jot.d("Restored purchases");
}
@Override
public void onBillingError(int errorCode, Throwable error) {
// Called when some error occurred. See Constants class for more details
Analytics.newEvent("billing error").put("error_code", errorCode).log();
Crashlytics.logException(error);
}
@Override
public void onBillingInitialized() {
// Called when BillingProcessor was initialized and it's ready to purchase
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(Monetize.Event.RequestInterstitialAd event) {
showInstallInterstitials();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(Monetize.Event.OnAdsRemovedEvent event) {
Technique.SLIDE_OUT_DOWN.getComposer().hideOnFinished().playOn(findViewById(R.id.ad_view));
interstitialsTabAd = null;
interstitialsSettingsAd = null;
interstitialsInstallAd = null;
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(Monetize.Event.RequestRemoveAds event) {
bp.purchase(this, Monetize.decrypt(Monetize.ENCRYPTED_REMOVE_ADS_PRODUCT_ID));
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventRootCheck(RootCheck rootCheck) {
if (!rootCheck.accessGranted) {
RootCheckDialog.show(this, DeviceNameHelper.getSingleton().getName());
rootDialogShown = true;
}
}
private void showTabInterstitials() {
if (interstitialsTabAd != null) {
for (InterstitialAd interstitialAd : interstitialsTabAd) {
if (interstitialIsReady(interstitialAd)) {
interstitialAd.show();
return;
}
}
}
}
private void showSettingsInterstitials() {
if (interstitialsSettingsAd != null) {
for (InterstitialAd interstitialAd : interstitialsSettingsAd) {
if (interstitialIsReady(interstitialAd)) {
interstitialAd.show();
return;
}
}
startActivity(new Intent(this, SettingsActivity.class));
}
}
private void showInstallInterstitials() {
if (interstitialsInstallAd != null) {
for (InterstitialAd interstitialAd : interstitialsInstallAd) {
if (interstitialIsReady(interstitialAd)) {
interstitialAd.show();
Analytics.newEvent("interstitial_ad").put("id", interstitialAd.getAdUnitId()).log();
return;
}
}
}
}
private void setupBanners() {
AdRequest.Builder builder = new AdRequest.Builder();
if (App.isDebuggable()) {
builder.addTestDevice(DeviceUtils.getDeviceId());
}
adViewTiers[currentAdViewIndex] = new AdView(this);
adViewTiers[currentAdViewIndex].setAdSize(AdSize.SMART_BANNER);
adViewTiers[currentAdViewIndex]
.setAdUnitId(getResources().getStringArray(R.array.banners_id)[currentAdViewIndex]);
adViewTiers[currentAdViewIndex].setAdListener(new AdListener() {
@Override public void onAdFailedToLoad(int errorCode) {
if (currentAdViewIndex != (adViewTiers.length - 1)) {
currentAdViewIndex++;
setupBanners();
} else if (adContainer.getVisibility() == View.VISIBLE) {
Technique.SLIDE_OUT_DOWN.getComposer().hideOnFinished().playOn(adContainer);
}
}
@Override public void onAdLoaded() {
adContainer.setVisibility(View.VISIBLE);
if (adContainer.getChildCount() != 0) {
adContainer.removeAllViews();
}
adContainer.addView(adViewTiers[currentAdViewIndex]);
Analytics.newEvent("on_ad_loaded")
.put("id", adViewTiers[currentAdViewIndex].getAdUnitId()).log();
}
});
adViewTiers[currentAdViewIndex].loadAd(builder.build());
}
private void setupTabInterstitialsAd() {
String[] ids = getResources().getStringArray(R.array.tabs_interstitials_id);
for (int i = 0; i < interstitialsTabAd.length; i++) {
if (!interstitialIsReady(interstitialsTabAd[i])) {
final int finalI = i;
AdListener adListener = new AdListener() {
@Override public void onAdClosed() {
super.onAdClosed();
interstitialsTabAd[finalI] = null;
setupTabInterstitialsAd();
}
};
interstitialsTabAd[i] = newInterstitialAd(ids[i], adListener);
}
}
}
private void setupSettingsInterstitialsAd() {
String[] ids = getResources().getStringArray(R.array.settings_interstitials_id);
for (int i = 0; i < interstitialsSettingsAd.length; i++) {
if (!interstitialIsReady(interstitialsSettingsAd[i])) {
final int finalI = i;
AdListener adListener = new AdListener() {
@Override public void onAdClosed() {
super.onAdClosed();
interstitialsSettingsAd[finalI] = null;
setupSettingsInterstitialsAd();
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
};
interstitialsSettingsAd[i] = newInterstitialAd(ids[i], adListener);
}
}
}
private void setupInstallInterstitialsAd() {
String[] ids = getResources().getStringArray(R.array.install_interstitials_id);
for (int i = 0; i < interstitialsInstallAd.length; i++) {
if (!interstitialIsReady(interstitialsInstallAd[i])) {
final int finalI = i;
AdListener adListener = new AdListener() {
@Override public void onAdClosed() {
super.onAdClosed();
interstitialsInstallAd[finalI] = null;
setupInstallInterstitialsAd();
}
};
interstitialsInstallAd[i] = newInterstitialAd(ids[i], adListener);
}
}
}
private InterstitialAd newInterstitialAd(String placementId, AdListener listener) {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdListener(listener);
interstitialAd.setAdUnitId(placementId);
interstitialAd.loadAd(getAdRequest());
return interstitialAd;
}
private boolean interstitialIsReady(InterstitialAd interstitialAd) {
return interstitialAd != null && interstitialAd.isLoaded();
}
private AdRequest getAdRequest() {
AdRequest adRequest;
if (App.isDebuggable()) {
adRequest = new AdRequest.Builder().addTestDevice(DeviceUtils.getDeviceId()).build();
} else {
adRequest = new AdRequest.Builder().build();
}
return adRequest;
}
}
| jrummyapps/BusyBox | app/src/free/java/com/jrummy/busybox/installer/activities/MainActivity.java | Java | apache-2.0 | 14,942 |
/* Copyright 2018 Telstra Open Source
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openkilda.messaging.nbtopology.request;
import org.openkilda.messaging.StringSerializer;
import org.openkilda.messaging.command.CommandMessage;
import org.openkilda.messaging.model.LinkPropsDto;
import org.openkilda.messaging.model.NetworkEndpoint;
import org.openkilda.model.SwitchId;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
public class LinkPropsPutTest {
StringSerializer serializer = new StringSerializer();
@Test
public void serializeLoop() throws Exception {
LinkPropsPut origin = makeRequest();
CommandMessage wrapper = new CommandMessage(origin, System.currentTimeMillis(), getClass().getCanonicalName());
serializer.serialize(wrapper);
CommandMessage result = (CommandMessage) serializer.deserialize();
LinkPropsPut reconstructed = (LinkPropsPut) result.getData();
Assert.assertEquals(origin, reconstructed);
}
/**
* Produce {@link LinkPropsPut} request with predefined data.
*/
public static LinkPropsPut makeRequest() {
HashMap<String, String> keyValuePairs = new HashMap<>();
keyValuePairs.put("cost", "10000");
LinkPropsDto linkProps = new LinkPropsDto(
new NetworkEndpoint(new SwitchId("ff:fe:00:00:00:00:00:01"), 8),
new NetworkEndpoint(new SwitchId("ff:fe:00:00:00:00:00:02"), 8),
keyValuePairs);
return new LinkPropsPut(linkProps);
}
}
| jonvestal/open-kilda | src-java/nbworker-topology/nbworker-messaging/src/test/java/org/openkilda/messaging/nbtopology/request/LinkPropsPutTest.java | Java | apache-2.0 | 2,094 |
/*
Copyright 2016 Fixstars Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http ://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <chrono>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cuda_runtime.h>
#include <libsgm.h>
#define ASSERT_MSG(expr, msg) \
if (!(expr)) { \
std::cerr << msg << std::endl; \
std::exit(EXIT_FAILURE); \
} \
struct device_buffer
{
device_buffer() : data(nullptr) {}
device_buffer(size_t count) { allocate(count); }
void allocate(size_t count) { cudaMalloc(&data, count); }
~device_buffer() { cudaFree(data); }
void* data;
};
// Camera Parameters
struct CameraParameters
{
float fu; //!< focal length x (pixel)
float fv; //!< focal length y (pixel)
float u0; //!< principal point x (pixel)
float v0; //!< principal point y (pixel)
float baseline; //!< baseline (meter)
float height; //!< height position (meter), ignored when ROAD_ESTIMATION_AUTO
float tilt; //!< tilt angle (radian), ignored when ROAD_ESTIMATION_AUTO
};
// Transformation between pixel coordinate and world coordinate
struct CoordinateTransform
{
CoordinateTransform(const CameraParameters& camera) : camera(camera)
{
sinTilt = (sinf(camera.tilt));
cosTilt = (cosf(camera.tilt));
bf = camera.baseline * camera.fu;
invfu = 1.f / camera.fu;
invfv = 1.f / camera.fv;
}
inline cv::Point3f imageToWorld(const cv::Point2f& pt, float d) const
{
const float u = pt.x;
const float v = pt.y;
const float Zc = bf / d;
const float Xc = invfu * (u - camera.u0) * Zc;
const float Yc = invfv * (v - camera.v0) * Zc;
const float Xw = Xc;
const float Yw = Yc * cosTilt + Zc * sinTilt;
const float Zw = Zc * cosTilt - Yc * sinTilt;
return cv::Point3f(Xw, Yw, Zw);
}
CameraParameters camera;
float sinTilt, cosTilt, bf, invfu, invfv;
};
template <class... Args>
static std::string format_string(const char* fmt, Args... args)
{
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
std::snprintf(buf, BUF_SIZE, fmt, args...);
return std::string(buf);
}
static cv::Scalar computeColor(float val)
{
const float hscale = 6.f;
float h = 0.6f * (1.f - val), s = 1.f, v = 1.f;
float r, g, b;
static const int sector_data[][3] =
{ { 1,3,0 },{ 1,0,2 },{ 3,0,1 },{ 0,2,1 },{ 0,1,3 },{ 2,1,0 } };
float tab[4];
int sector;
h *= hscale;
if (h < 0)
do h += 6; while (h < 0);
else if (h >= 6)
do h -= 6; while (h >= 6);
sector = cvFloor(h);
h -= sector;
if ((unsigned)sector >= 6u)
{
sector = 0;
h = 0.f;
}
tab[0] = v;
tab[1] = v*(1.f - s);
tab[2] = v*(1.f - s*h);
tab[3] = v*(1.f - s*(1.f - h));
b = tab[sector_data[sector][0]];
g = tab[sector_data[sector][1]];
r = tab[sector_data[sector][2]];
return 255 * cv::Scalar(b, g, r);
}
void reprojectPointsTo3D(const cv::Mat& disparity, const CameraParameters& camera, std::vector<cv::Point3f>& points, bool subpixeled)
{
CV_Assert(disparity.type() == CV_32F);
CoordinateTransform tf(camera);
points.clear();
points.reserve(disparity.rows * disparity.cols);
for (int y = 0; y < disparity.rows; y++)
{
for (int x = 0; x < disparity.cols; x++)
{
const float d = disparity.at<float>(y, x);
if (d > 0)
points.push_back(tf.imageToWorld(cv::Point(x, y), d));
}
}
}
void drawPoints3D(const std::vector<cv::Point3f>& points, cv::Mat& draw)
{
const int SIZE_X = 512;
const int SIZE_Z = 1024;
const int maxz = 20; // [meter]
const double pixelsPerMeter = 1. * SIZE_Z / maxz;
draw = cv::Mat::zeros(SIZE_Z, SIZE_X, CV_8UC3);
for (const cv::Point3f& pt : points)
{
const float X = pt.x;
const float Z = pt.z;
const int u = cvRound(pixelsPerMeter * X) + SIZE_X / 2;
const int v = SIZE_Z - cvRound(pixelsPerMeter * Z);
const cv::Scalar color = computeColor(std::min(Z, 1.f * maxz) / maxz);
cv::circle(draw, cv::Point(u, v), 1, color);
}
}
int main(int argc, char* argv[])
{
if (argc < 4) {
std::cout << "usage: " << argv[0] << " left-image-format right-image-format camera.xml [disp_size] [subpixel_enable(0: false, 1:true)]" << std::endl;
std::exit(EXIT_FAILURE);
}
const int first_frame = 1;
cv::Mat I1 = cv::imread(format_string(argv[1], first_frame), -1);
cv::Mat I2 = cv::imread(format_string(argv[2], first_frame), -1);
const cv::FileStorage fs(argv[3], cv::FileStorage::READ);
const int disp_size = argc >= 5 ? std::stoi(argv[4]) : 128;
const bool subpixel = argc >= 6 ? std::stoi(argv[5]) != 0 : true;
const int output_depth = 16;
ASSERT_MSG(!I1.empty() && !I2.empty(), "imread failed.");
ASSERT_MSG(fs.isOpened(), "camera.xml read failed.");
ASSERT_MSG(I1.size() == I2.size() && I1.type() == I2.type(), "input images must be same size and type.");
ASSERT_MSG(I1.type() == CV_8U || I1.type() == CV_16U, "input image format must be CV_8U or CV_16U.");
ASSERT_MSG(disp_size == 64 || disp_size == 128 || disp_size == 256, "disparity size must be 64, 128 or 256.");
// read camera parameters
CameraParameters camera;
camera.fu = fs["FocalLengthX"];
camera.fv = fs["FocalLengthY"];
camera.u0 = fs["CenterX"];
camera.v0 = fs["CenterY"];
camera.baseline = fs["BaseLine"];
camera.tilt = fs["Tilt"];
const int width = I1.cols;
const int height = I1.rows;
const int input_depth = I1.type() == CV_8U ? 8 : 16;
const int input_bytes = input_depth * width * height / 8;
const int output_bytes = output_depth * width * height / 8;
const sgm::StereoSGM::Parameters params{10, 120, 0.95f, subpixel};
sgm::StereoSGM sgm(width, height, disp_size, input_depth, output_depth, sgm::EXECUTE_INOUT_CUDA2CUDA, params);
cv::Mat disparity(height, width, CV_16S);
cv::Mat disparity_8u, disparity_32f, disparity_color, draw;
std::vector<cv::Point3f> points;
device_buffer d_I1(input_bytes), d_I2(input_bytes), d_disparity(output_bytes);
for (int frame_no = first_frame;; frame_no++) {
I1 = cv::imread(format_string(argv[1], frame_no), -1);
I2 = cv::imread(format_string(argv[2], frame_no), -1);
if (I1.empty() || I2.empty()) {
frame_no = first_frame;
continue;
}
cudaMemcpy(d_I1.data, I1.data, input_bytes, cudaMemcpyHostToDevice);
cudaMemcpy(d_I2.data, I2.data, input_bytes, cudaMemcpyHostToDevice);
const auto t1 = std::chrono::system_clock::now();
sgm.execute(d_I1.data, d_I2.data, d_disparity.data);
cudaDeviceSynchronize();
const auto t2 = std::chrono::system_clock::now();
const auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
const double fps = 1e6 / duration;
cudaMemcpy(disparity.data, d_disparity.data, output_bytes, cudaMemcpyDeviceToHost);
// draw results
if (I1.type() != CV_8U) {
cv::normalize(I1, I1, 0, 255, cv::NORM_MINMAX);
I1.convertTo(I1, CV_8U);
}
disparity.convertTo(disparity_32f, CV_32F, subpixel ? 1. / sgm::StereoSGM::SUBPIXEL_SCALE : 1);
reprojectPointsTo3D(disparity_32f, camera, points, subpixel);
drawPoints3D(points, draw);
disparity_32f.convertTo(disparity_8u, CV_8U, 255. / disp_size);
cv::applyColorMap(disparity_8u, disparity_color, cv::COLORMAP_JET);
disparity_color.setTo(cv::Scalar(0, 0, 0), disparity_32f < 0); // invalid disparity will be negative
cv::putText(disparity_color, format_string("sgm execution time: %4.1f[msec] %4.1f[FPS]", 1e-3 * duration, fps),
cv::Point(50, 50), 2, 0.75, cv::Scalar(255, 255, 255));
cv::imshow("left image", I1);
cv::imshow("disparity", disparity_color);
cv::imshow("points", draw);
const char c = cv::waitKey(1);
if (c == 27) // ESC
break;
}
return 0;
}
| fixstars-jp/libSGM | sample/reprojection/stereosgm_reprojection.cpp | C++ | apache-2.0 | 8,104 |
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.aggregation;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.SlowTest;
import com.hazelcast.test.bounce.BounceMemberRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class AggregationMemberBounceTest extends HazelcastTestSupport {
private static final int MEMBER_COUNT = 4;
private static final int DRIVER_COUNT = 4;
private static final int TEST_DURATION_SECONDS = 40;
private String mapName;
@Rule
public BounceMemberRule bounceMemberRule = BounceMemberRule.with(getConfig())
.clusterSize(MEMBER_COUNT)
.driverCount(DRIVER_COUNT).build();
protected Config getConfig() {
return new Config();
}
@Before
public void setup() {
mapName = randomMapName();
final HazelcastInstance steadyMember = bounceMemberRule.getSteadyMember();
IMap<Integer, AggregatorsSpecTest.Person> map = steadyMember.getMap(mapName);
AggregatorsSpecTest.populateMapWithPersons(map, "");
}
@Test
public void aggregationReturnsCorrectResultWhenBouncing() {
Runnable[] runnables = new Runnable[DRIVER_COUNT];
for (int i = 0; i < DRIVER_COUNT; i++) {
HazelcastInstance driver = bounceMemberRule.getNextTestDriver();
final IMap<Integer, AggregatorsSpecTest.Person> map = driver.getMap(mapName);
runnables[i] = new Runnable() {
@Override
public void run() {
String postfix = "";
AggregatorsSpecTest.assertMinAggregators(map, postfix);
AggregatorsSpecTest.assertMaxAggregators(map, postfix);
AggregatorsSpecTest.assertSumAggregators(map, postfix);
AggregatorsSpecTest.assertAverageAggregators(map, postfix);
AggregatorsSpecTest.assertCountAggregators(map, postfix);
AggregatorsSpecTest.assertDistinctAggregators(map, postfix);
}
};
}
bounceMemberRule.testRepeatedly(runnables, TEST_DURATION_SECONDS);
}
}
| tombujok/hazelcast | hazelcast/src/test/java/com/hazelcast/aggregation/AggregationMemberBounceTest.java | Java | apache-2.0 | 3,105 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
namespace Google\Service\CloudDeploy;
class SerialPipeline extends \Google\Collection
{
protected $collection_key = 'stages';
protected $stagesType = Stage::class;
protected $stagesDataType = 'array';
/**
* @param Stage[]
*/
public function setStages($stages)
{
$this->stages = $stages;
}
/**
* @return Stage[]
*/
public function getStages()
{
return $this->stages;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SerialPipeline::class, 'Google_Service_CloudDeploy_SerialPipeline');
| googleapis/google-api-php-client-services | src/CloudDeploy/SerialPipeline.php | PHP | apache-2.0 | 1,176 |
package org.opengis.cite.iso19139.util;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.apache.xerces.util.XMLCatalogResolver;
import org.opengis.cite.validation.SchematronValidator;
/**
* A utility class that provides convenience methods to support schema
* validation.
*/
public class ValidationUtils {
private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver();
private static XMLCatalogResolver initCatalogResolver() {
URL catalogURL = ValidationUtils.class
.getResource("/org/opengis/cite/iso19139/schematron-catalog.xml");
XMLCatalogResolver resolver = new XMLCatalogResolver();
resolver.setCatalogList(new String[]{catalogURL.toString()});
return resolver;
}
/**
* Constructs a SchematronValidator that will check an XML resource against
* the rules defined in a Schematron schema. An attempt is made to resolve
* the schema reference using an entity catalog; if this fails the reference
* is used as given.
*
* @param schemaRef A reference to a Schematron schema; this is expected to
* be a relative or absolute URI value, possibly matching the system
* identifier for some entry in an entity catalog.
* @param phase The name of the phase to invoke.
* @return A SchematronValidator instance, or {@code null} if the validator
* cannot be constructed (e.g. invalid schema reference or phase name).
*/
public static SchematronValidator buildSchematronValidator(
String schemaRef, String phase) {
Source source = null;
try {
String catalogRef = SCH_RESOLVER
.resolveSystem(schemaRef.toString());
if (null != catalogRef) {
source = new StreamSource(URI.create(catalogRef).toString());
} else {
source = new StreamSource(schemaRef);
}
} catch (IOException x) {
TestSuiteLogger.log(Level.WARNING,
"Error reading Schematron schema catalog.", x);
}
SchematronValidator validator = null;
try {
validator = new SchematronValidator(source, phase);
} catch (Exception e) {
TestSuiteLogger.log(Level.WARNING,
"Error creating Schematron validator.", e);
}
return validator;
}
/**
* Extracts a set of XML Schema references from a source XML document. The
* document element is expected to include the standard xsi:schemaLocation
* attribute.
*
* @param source The source instance to read from; its base URI (systemId)
* should be set.
* @param baseURI An alternative base URI to use if the source does not have
* a system identifier set or if its system id is a {@code file} URI. This
* will usually be the URI used to retrieve the resource; it may be null.
* @return A Set containing absolute URI references that specify the
* locations of XML Schema resources.
* @throws XMLStreamException If an error occurs while reading the source
* instance.
*/
public static Set<URI> extractSchemaReferences(Source source, String baseURI)
throws XMLStreamException {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(source);
// advance to document element
StartElement docElem = reader.nextTag().asStartElement();
Attribute schemaLoc = docElem.getAttributeByName(new QName(
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation"));
if (null == schemaLoc) {
//throw new RuntimeException("No xsi:schemaLocation attribute found.");
}
String[] uriValues = schemaLoc.getValue().split("\\s+");
if (uriValues.length % 2 != 0) {
//throw new RuntimeException("xsi:schemaLocation attribute contains an odd number of URI values:\n"+ Arrays.toString(uriValues));
}
Set<URI> schemaURIs = new HashSet<URI>();
// one or more pairs of [namespace name] [schema location]
for (int i = 0; i < uriValues.length; i += 2) {
URI schemaURI = null;
if (!URI.create(uriValues[i + 1]).isAbsolute()
&& (null != source.getSystemId())) {
String schemaRef = URIUtils.resolveRelativeURI(
source.getSystemId(), uriValues[i + 1]).toString();
if (schemaRef.startsWith("file")
&& !new File(schemaRef).exists() && (null != baseURI)) {
schemaRef = URIUtils.resolveRelativeURI(baseURI,
uriValues[i + 1]).toString();
}
schemaURI = URI.create(schemaRef);
} else {
schemaURI = URI.create(uriValues[i + 1]);
}
schemaURIs.add(schemaURI);
}
return schemaURIs;
}
}
| opengeospatial/ets-19139 | src/main/java/org/opengis/cite/iso19139/util/ValidationUtils.java | Java | apache-2.0 | 5,493 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Specialized;
namespace System.Web.WebPages
{
internal class UrlRewriterHelper
{
// internal for tests
internal const string UrlWasRewrittenServerVar = "IIS_WasUrlRewritten";
internal const string UrlRewriterEnabledServerVar = "IIS_UrlRewriteModule";
internal const string UrlWasRequestRewrittenTrueValue = "true";
internal const string UrlWasRequestRewrittenFalseValue = "false";
private object _lockObject = new object();
private bool _urlRewriterIsTurnedOnValue;
private volatile bool _urlRewriterIsTurnedOnCalculated = false;
private static bool WasThisRequestRewritten(HttpContextBase httpContext)
{
if (httpContext.Items.Contains(UrlWasRewrittenServerVar))
{
return Object.Equals(httpContext.Items[UrlWasRewrittenServerVar], UrlWasRequestRewrittenTrueValue);
}
else
{
HttpWorkerRequest httpWorkerRequest = (HttpWorkerRequest)httpContext.GetService(typeof(HttpWorkerRequest));
bool requestWasRewritten = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable(UrlWasRewrittenServerVar) != null);
if (requestWasRewritten)
{
httpContext.Items.Add(UrlWasRewrittenServerVar, UrlWasRequestRewrittenTrueValue);
}
else
{
httpContext.Items.Add(UrlWasRewrittenServerVar, UrlWasRequestRewrittenFalseValue);
}
return requestWasRewritten;
}
}
private bool IsUrlRewriterTurnedOn(HttpContextBase httpContext)
{
// Need to do double-check locking because a single instance of this class is shared in the entire app domain (see PathHelpers)
if (!_urlRewriterIsTurnedOnCalculated)
{
lock (_lockObject)
{
if (!_urlRewriterIsTurnedOnCalculated)
{
HttpWorkerRequest httpWorkerRequest = (HttpWorkerRequest)httpContext.GetService(typeof(HttpWorkerRequest));
bool urlRewriterIsEnabled = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable(UrlRewriterEnabledServerVar) != null);
_urlRewriterIsTurnedOnValue = urlRewriterIsEnabled;
_urlRewriterIsTurnedOnCalculated = true;
}
}
}
return _urlRewriterIsTurnedOnValue;
}
public virtual bool WasRequestRewritten(HttpContextBase httpContext)
{
return IsUrlRewriterTurnedOn(httpContext) && WasThisRequestRewritten(httpContext);
}
}
}
| Terminator-Aaron/Katana | aspnetwebsrc/System.Web.WebPages/Utils/UrlRewriterHelper.cs | C# | apache-2.0 | 2,946 |
/*
* Copyright 2009 Mike Cumings
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.igniterealtime.jbosh;
import java.io.IOException;
import java.io.StringReader;
import java.lang.ref.SoftReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* Implementation of the BodyParser interface which uses the XmlPullParser
* API. When available, this API provides an order of magnitude performance
* improvement over the default SAX parser implementation.
*/
final class BodyParserXmlPull implements BodyParser {
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(BodyParserXmlPull.class.getName());
/**
* Thread local to contain a XmlPullParser instance for each thread that
* attempts to use one. This allows us to gain an order of magnitude of
* performance as a result of not constructing parsers for each
* invocation while retaining thread safety.
*/
private static final ThreadLocal<SoftReference<XmlPullParser>> XPP_PARSER =
new ThreadLocal<SoftReference<XmlPullParser>>() {
@Override protected SoftReference<XmlPullParser> initialValue() {
return new SoftReference<XmlPullParser>(null);
}
};
///////////////////////////////////////////////////////////////////////////
// BodyParser interface methods:
/**
* {@inheritDoc}
*/
public BodyParserResults parse(final String xml) throws BOSHException {
BodyParserResults result = new BodyParserResults();
Exception thrown;
try {
XmlPullParser xpp = getXmlPullParser();
xpp.setInput(new StringReader(xml));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Start tag: " + xpp.getName());
}
} else {
eventType = xpp.next();
continue;
}
String prefix = xpp.getPrefix();
if (prefix == null) {
prefix = XMLConstants.DEFAULT_NS_PREFIX;
}
String uri = xpp.getNamespace();
String localName = xpp.getName();
QName name = new QName(uri, localName, prefix);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Start element: ");
LOG.finest(" prefix: " + prefix);
LOG.finest(" URI: " + uri);
LOG.finest(" local: " + localName);
}
BodyQName bodyName = AbstractBody.getBodyQName();
if (!bodyName.equalsQName(name)) {
throw(new IllegalStateException(
"Root element was not '" + bodyName.getLocalPart()
+ "' in the '" + bodyName.getNamespaceURI()
+ "' namespace. (Was '" + localName
+ "' in '" + uri + "')"));
}
for (int idx=0; idx < xpp.getAttributeCount(); idx++) {
String attrURI = xpp.getAttributeNamespace(idx);
if (attrURI.length() == 0) {
attrURI = xpp.getNamespace(null);
}
String attrPrefix = xpp.getAttributePrefix(idx);
if (attrPrefix == null) {
attrPrefix = XMLConstants.DEFAULT_NS_PREFIX;
}
String attrLN = xpp.getAttributeName(idx);
String attrVal = xpp.getAttributeValue(idx);
BodyQName aqn = BodyQName.createWithPrefix(
attrURI, attrLN, attrPrefix);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(" Attribute: {" + attrURI + "}"
+ attrLN + " = '" + attrVal + "'");
}
result.addBodyAttributeValue(aqn, attrVal);
}
break;
}
return result;
} catch (RuntimeException rtx) {
thrown = rtx;
} catch (XmlPullParserException xmlppx) {
thrown = xmlppx;
} catch (IOException iox) {
thrown = iox;
}
throw(new BOSHException("Could not parse body:\n" + xml, thrown));
}
///////////////////////////////////////////////////////////////////////////
// Private methods:
/**
* Gets a XmlPullParser for use in parsing incoming messages.
*
* @return parser instance
*/
private static XmlPullParser getXmlPullParser() {
SoftReference<XmlPullParser> ref = XPP_PARSER.get();
XmlPullParser result = ref.get();
if (result == null) {
Exception thrown;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
result = factory.newPullParser();
ref = new SoftReference<XmlPullParser>(result);
XPP_PARSER.set(ref);
return result;
} catch (Exception ex) {
thrown = ex;
}
throw(new IllegalStateException(
"Could not create XmlPull parser", thrown));
} else {
return result;
}
}
}
| igniterealtime/jbosh | src/main/java/org/igniterealtime/jbosh/BodyParserXmlPull.java | Java | apache-2.0 | 6,391 |
package org.carlspring.strongbox.storage.repository;
/**
* @author mtodorov
*/
public enum RepositoryLayoutEnum
{
MAVEN_1("Maven 1"), // Unsupported
MAVEN_2("Maven 2"),
IVY("Ivy"), // Unsupported
RPM("RPM"), // Unsupported
YUM("YUM"), // Unsupported
NUGET_HIERACHLICAL("Nuget Hierarchical");
private String layout;
RepositoryLayoutEnum(String layout)
{
this.layout = layout;
}
public String getLayout()
{
return layout;
}
public void setLayout(String layout)
{
this.layout = layout;
}
}
| AlexOreshkevich/strongbox | strongbox-storage/strongbox-storage-api/src/main/java/org/carlspring/strongbox/storage/repository/RepositoryLayoutEnum.java | Java | apache-2.0 | 627 |
// This file is part of OpenTSDB.
// Copyright (C) 2012 The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.core;
import org.junit.Assert;
import org.junit.Test;
import java.util.Random;
public final class TestAggregators {
private static final Random random;
static {
final long seed = System.nanoTime();
System.out.println("Random seed: " + seed);
random = new Random(seed);
}
/**
* Epsilon used to compare floating point values.
* Instead of using a fixed epsilon to compare our numbers, we calculate
* it based on the percentage of our actual expected values. We do things
* this way because our numbers can be extremely large and if you change
* the scale of the numbers a static precision may no longer work
*/
private static final double EPSILON_PERCENTAGE = 0.0001;
/** Helper class to hold a bunch of numbers we can iterate on. */
private static final class Numbers implements Aggregator.Longs, Aggregator.Doubles {
private final long[] numbers;
private int i = 0;
public Numbers(final long[] numbers) {
this.numbers = numbers;
}
@Override
public boolean hasNextValue() {
return i < numbers.length;
}
@Override
public long nextLongValue() {
return numbers[i++];
}
@Override
public double nextDoubleValue() {
return numbers[i++];
}
void reset() {
i = 0;
}
}
@Test
public void testStdDevKnownValues() {
final long[] values = new long[10000];
for (int i = 0; i < values.length; i++) {
values[i] = i;
}
// Expected value calculated by NumPy
// $ python2.7
// >>> import numpy
// >>> numpy.std(range(10000))
// 2886.7513315143719
final double expected = 2886.7513315143719D;
final double epsilon = 0.01;
checkSimilarStdDev(values, expected, epsilon);
}
@Test
public void testStdDevRandomValues() {
final long[] values = new long[1000];
for (int i = 0; i < values.length; i++) {
values[i] = random.nextLong();
}
final double expected = naiveStdDev(values);
// Calculate the epsilon based on the percentage of the number.
final double epsilon = EPSILON_PERCENTAGE * expected;
checkSimilarStdDev(values, expected, epsilon);
}
@Test
public void testStdDevNoDeviation() {
final long[] values = {3,3,3};
final double expected = 0;
checkSimilarStdDev(values, expected, 0);
}
@Test
public void testStdDevFewDataInputs() {
final long[] values = {1,2};
final double expected = 0.5;
checkSimilarStdDev(values, expected, 0);
}
private static void checkSimilarStdDev(final long[] values,
final double expected,
final double epsilon) {
final Numbers numbers = new Numbers(values);
final Aggregator agg = Aggregators.get("dev");
Assert.assertEquals(expected, agg.runDouble(numbers), epsilon);
numbers.reset();
Assert.assertEquals(expected, agg.runLong(numbers), Math.max(epsilon, 1.0));
}
private static double naiveStdDev(long[] values) {
double sum = 0;
for (final double value : values) {
sum += value;
}
double mean = sum / values.length;
double squaresum = 0;
for (final double value : values) {
squaresum += Math.pow(value - mean, 2);
}
final double variance = squaresum / values.length;
return Math.sqrt(variance);
}
}
| c3p0hz/microscope | microscope-storage/src/test/java/net/opentsdb/core/TestAggregators.java | Java | apache-2.0 | 4,122 |
var MSG = {
title: "Codi",
blocks: "Blocs",
linkTooltip: "Desa i enllaça als blocs.",
runTooltip: "Executa el programa definit pels blocs de l'àrea de treball.",
badCode: "Error de programa:\n %1",
timeout: "S'ha superat el nombre màxim d'iteracions d'execució.",
trashTooltip: "Descarta tots els blocs.",
catLogic: "Lògica",
catLoops: "Bucles",
catMath: "Matemàtiques",
catText: "Text",
catLists: "Llistes",
catColour: "Color",
catVariables: "Variables",
catFunctions: "Procediments",
listVariable: "llista",
textVariable: "text",
httpRequestError: "Hi ha hagut un problema amb la sol·licitud.",
linkAlert: "Comparteix els teus blocs amb aquest enllaç: %1",
hashError: "Ho sentim, '%1' no es correspon amb cap fitxer desat de Blockly.",
loadError: "No s'ha pogut carregar el teu fitxer desat. Potser va ser creat amb una versió diferent de Blockly?",
parseError: "Error d'anàlisi %1:\n%2\n\nSeleccioneu 'Acceptar' per abandonar els vostres canvis, o 'Cancel·lar' per continuar editant l'%1."
};
| rachel-fenichel/blockly | demos/code/msg/ca.js | JavaScript | apache-2.0 | 1,052 |
/*
* Copyright 2015 herd contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.finra.herd.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test driver for the FileUtils class.
*/
public class HerdFileUtilsTest extends AbstractCoreTest
{
private Path localTempPath;
@Before
public void setup() throws IOException
{
// Create a local temp directory.
localTempPath = Files.createTempDirectory(null);
}
@After
public void cleanup() throws IOException
{
FileUtils.deleteDirectory(localTempPath.toFile());
}
@Test
public void testVerifyFileExistsAndReadable() throws IOException
{
File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);
HerdFileUtils.verifyFileExistsAndReadable(testFile);
}
@Test
public void testVerifyFileExistsAndReadableFileNoExists() throws IOException
{
File testFile = new File("I_DO_NOT_EXIST");
try
{
HerdFileUtils.verifyFileExistsAndReadable(testFile);
fail("Should throw an IllegalArgumentException when file does not exist.");
}
catch (IllegalArgumentException e)
{
assertEquals(String.format("File \"%s\" doesn't exist.", testFile.getName()), e.getMessage());
}
}
@Test
public void testVerifyFileExistsAndReadableFileIsDirectory() throws IOException
{
File testDirectory = localTempPath.toFile();
try
{
HerdFileUtils.verifyFileExistsAndReadable(testDirectory);
fail("Should throw an IllegalArgumentException when argument is a directory.");
}
catch (IllegalArgumentException e)
{
assertEquals(String.format("File \"%s\" is not a valid file that can be read as a manifest. Is it a directory?", testDirectory.getName()),
e.getMessage());
}
}
@Test
public void testVerifyFileExistsAndReadableFileNotReadable() throws IOException
{
File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);
if (testFile.setReadable(false))
{
try
{
HerdFileUtils.verifyFileExistsAndReadable(testFile);
fail("Should throw an IllegalArgumentException when file is not readable.");
}
catch (IllegalArgumentException e)
{
assertEquals(String.format("Unable to read file \"%s\". Check permissions.", testFile.getName()), e.getMessage());
}
}
}
/**
* Cleans up a local test directory by deleting a test file.
*
* @throws IOException if fails to create a local test file
*/
@Test
public void testCleanDirectoryIgnoreException() throws IOException
{
File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);
HerdFileUtils.cleanDirectoryIgnoreException(localTempPath.toFile());
assertFalse(testFile.exists());
assertTrue(localTempPath.toFile().exists());
}
/**
* Tries to clean a directory which is actually a file.
*/
@Test
public void testCleanDirectoryIgnoreExceptionWithException() throws Exception
{
final File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);
executeWithoutLogging(HerdFileUtils.class, new Command()
{
@Override
public void execute() throws Exception
{
HerdFileUtils.cleanDirectoryIgnoreException(testFile);
}
});
assertTrue(testFile.exists());
}
/**
* Deletes a local test directory with a test file.
*
* @throws IOException if fails to create a local test file
*/
@Test
public void testDeleteDirectoryIgnoreException() throws IOException
{
File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);
HerdFileUtils.deleteDirectoryIgnoreException(localTempPath.toFile());
assertFalse(testFile.exists());
assertFalse(localTempPath.toFile().exists());
}
/**
* Tries to delete a directory which is actually a file.
*/
@Test
public void testDeleteDirectoryIgnoreExceptionWithException() throws Exception
{
final File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);
executeWithoutLogging(HerdFileUtils.class, new Command()
{
@Override
public void execute() throws Exception
{
HerdFileUtils.deleteDirectoryIgnoreException(testFile);
}
});
assertTrue(testFile.exists());
}
/**
* Deletes a local test file.
*
* @throws IOException if fails to create a local test file
*/
@Test
public void testDeleteFileIgnoreException() throws IOException
{
File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);
HerdFileUtils.deleteFileIgnoreException(testFile);
assertFalse(testFile.exists());
assertTrue(localTempPath.toFile().exists());
}
/**
* Tries to delete a non-existing local test file.
*/
@Test
public void testDeleteFileIgnoreExceptionWithException() throws Exception
{
executeWithoutLogging(HerdFileUtils.class, new Command()
{
@Override
public void execute() throws Exception
{
HerdFileUtils.deleteDirectoryIgnoreException(new File("I_DO_NOT_EXIST"));
}
});
}
}
| kusid/herd | herd-code/herd-core/src/test/java/org/finra/herd/core/HerdFileUtilsTest.java | Java | apache-2.0 | 6,570 |
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.lock;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("lock")
public interface LockResource {
@POST
@Path("timelock-lock")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
boolean lockUsingTimelockApi(@QueryParam("number") int numDescriptors, int descriptorSize);
@POST
@Path("remote-lock")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
boolean lockUsingLegacyLockApi(@QueryParam("number") int numDescriptors, int descriptorSize);
}
| palantir/atlasdb | atlasdb-ete-tests/src/main/java/com/palantir/atlasdb/lock/LockResource.java | Java | apache-2.0 | 1,330 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.docker.headers;
import java.util.HashMap;
import java.util.Map;
import com.github.dockerjava.api.DockerClient;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.docker.DockerClientProfile;
import org.apache.camel.component.docker.DockerComponent;
import org.apache.camel.component.docker.DockerConfiguration;
import org.apache.camel.component.docker.DockerConstants;
import org.apache.camel.component.docker.DockerOperation;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public abstract class BaseDockerHeaderTest<T> extends CamelTestSupport {
@Mock
protected DockerClient dockerClient;
protected DockerConfiguration dockerConfiguration;
@Mock
T mockObject;
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:in").to("docker://" + getOperation().toString());
}
};
}
@Before
public void setupTest() {
setupMocks();
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
dockerConfiguration = new DockerConfiguration();
dockerConfiguration.setParameters(getDefaultParameters());
DockerComponent dockerComponent = new DockerComponent(dockerConfiguration);
dockerComponent.setClient(getClientProfile(), dockerClient);
camelContext.addComponent("docker", dockerComponent);
return camelContext;
}
protected String getHost() {
return "localhost";
}
protected Integer getPort() {
return 5000;
}
protected String getEmail() {
return "docker@camel.apache.org";
}
protected Integer getMaxPerRouteConnections() {
return 100;
}
protected Integer getMaxTotalConnections() {
return 100;
}
protected String getServerAddress() {
return "https://index.docker.io/v1/";
}
public T getMockObject() {
return mockObject;
}
protected Map<String, Object> getDefaultParameters() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(DockerConstants.DOCKER_HOST, getHost());
parameters.put(DockerConstants.DOCKER_PORT, getPort());
parameters.put(DockerConstants.DOCKER_EMAIL, getEmail());
parameters.put(DockerConstants.DOCKER_SERVER_ADDRESS, getServerAddress());
parameters.put(DockerConstants.DOCKER_MAX_PER_ROUTE_CONNECTIONS, getMaxPerRouteConnections());
parameters.put(DockerConstants.DOCKER_MAX_TOTAL_CONNECTIONS, getMaxTotalConnections());
return parameters;
}
protected DockerClientProfile getClientProfile() {
DockerClientProfile clientProfile = new DockerClientProfile();
clientProfile.setHost(getHost());
clientProfile.setPort(getPort());
clientProfile.setEmail(getEmail());
clientProfile.setServerAddress(getServerAddress());
clientProfile.setMaxPerRouteConnections(getMaxPerRouteConnections());
clientProfile.setMaxTotalConnections(getMaxTotalConnections());
return clientProfile;
}
protected abstract void setupMocks();
protected abstract DockerOperation getOperation();
}
| koscejev/camel | components/camel-docker/src/test/java/org/apache/camel/component/docker/headers/BaseDockerHeaderTest.java | Java | apache-2.0 | 4,447 |
/* $Id: RobotsManager.java 988245 2010-08-23 18:39:35Z kwright $ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.crawler.connectors.webcrawler;
import java.util.*;
import java.io.*;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.*;
import org.apache.manifoldcf.authorities.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.CacheKeyFactory;
import org.apache.manifoldcf.crawler.system.ManifoldCF;
import org.apache.manifoldcf.crawler.system.Logging;
/** This class manages the database table into which we write robots.txt files for hosts. The data resides in the database,
* as well as in cache (up to a certain point). The result is that there is a memory limited, database-backed repository
* of robots files that we can draw on.
*
* <br><br>
* <b>robotsdata</b>
* <table border="1" cellpadding="3" cellspacing="0">
* <tr class="TableHeadingColor">
* <th>Field</th><th>Type</th><th>Description </th>
* <tr><td>hostname</td><td>VARCHAR(255)</td><td>Primary Key</td></tr>
* <tr><td>robotsdata</td><td>BIGINT</td><td></td></tr>
* <tr><td>expirationtime</td><td>BLOB</td><td></td></tr>
* </table>
* <br><br>
*
*/
public class RobotsManager extends org.apache.manifoldcf.core.database.BaseTable
{
public static final String _rcsid = "@(#)$Id: RobotsManager.java 988245 2010-08-23 18:39:35Z kwright $";
// Robots cache class. Only one needed.
protected static RobotsCacheClass robotsCacheClass = new RobotsCacheClass();
// Database fields
protected final static String hostField = "hostname";
protected final static String robotsField = "robotsdata";
protected final static String expirationField = "expirationtime";
// Cache manager. This handle is set up during the constructor.
ICacheManager cacheManager;
/** Constructor. Note that one robotsmanager handle is only useful within a specific thread context,
* so the calling connector object logic must recreate the handle whenever the thread context changes.
*@param tc is the thread context.
*@param database is the database handle.
*/
public RobotsManager(IThreadContext tc, IDBInterface database)
throws ManifoldCFException
{
super(database,"robotsdata");
cacheManager = CacheManagerFactory.make(tc);
}
/** Install the manager.
*/
public void install()
throws ManifoldCFException
{
// Standard practice: outer loop on install methods, no transactions
while (true)
{
Map existing = getTableSchema(null,null);
if (existing == null)
{
// Install the table.
HashMap map = new HashMap();
map.put(hostField,new ColumnDescription("VARCHAR(255)",true,false,null,null,false));
map.put(expirationField,new ColumnDescription("BIGINT",false,false,null,null,false));
map.put(robotsField,new ColumnDescription("BLOB",false,true,null,null,false));
performCreate(map,null);
}
else
{
// Upgrade code, if needed, goes here
}
// Handle indexes, if needed
break;
}
}
/** Uninstall the manager.
*/
public void deinstall()
throws ManifoldCFException
{
performDrop(null);
}
/** Read robots.txt data from the cache or from the database.
*@param hostName is the host for which the data is desired.
*@param currentTime is the time of the check.
*@return null if the record needs to be fetched, true if fetch is allowed.
*/
public Boolean checkFetchAllowed(String userAgent, String hostName, long currentTime, String pathString,
IVersionActivity activities)
throws ManifoldCFException
{
// Build description objects
HostDescription[] objectDescriptions = new HostDescription[1];
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getRobotsKey(hostName));
objectDescriptions[0] = new HostDescription(hostName,new StringSet(ssb));
HostExecutor exec = new HostExecutor(this,activities,objectDescriptions[0]);
cacheManager.findObjectsAndExecute(objectDescriptions,null,exec,getTransactionID());
// We do the expiration check here, rather than in the query, so that caching
// is possible.
RobotsData rd = exec.getResults();
if (rd == null || rd.getExpirationTime() <= currentTime)
return null;
return new Boolean(rd.isFetchAllowed(userAgent,pathString));
}
/** Write robots.txt, replacing any existing row.
*@param hostName is the host.
*@param expirationTime is the time this data should expire.
*@param data is the robots data stream. May be null.
*/
public void writeRobotsData(String hostName, long expirationTime, InputStream data)
throws ManifoldCFException, IOException
{
TempFileInput tfi = null;
try
{
if (data != null)
{
try
{
tfi = new TempFileInput(data);
}
catch (ManifoldCFException e)
{
if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
throw e;
throw new IOException("Fetch failed: "+e.getMessage());
}
}
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getRobotsKey(hostName));
StringSet cacheKeys = new StringSet(ssb);
ICacheHandle ch = cacheManager.enterCache(null,cacheKeys,getTransactionID());
try
{
beginTransaction();
try
{
// See whether the instance exists
ArrayList params = new ArrayList();
params.add(hostName);
IResultSet set = performQuery("SELECT * FROM "+getTableName()+" WHERE "+
hostField+"=?",params,null,null);
HashMap values = new HashMap();
values.put(expirationField,new Long(expirationTime));
if (tfi != null)
values.put(robotsField,tfi);
if (set.getRowCount() > 0)
{
// Update
params.clear();
params.add(hostName);
performUpdate(values," WHERE "+hostField+"=?",params,null);
}
else
{
// Insert
values.put(hostField,hostName);
// We only need the general key because this is new.
performInsert(values,null);
}
cacheManager.invalidateKeys(ch);
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
finally
{
cacheManager.leaveCache(ch);
}
}
finally
{
if (tfi != null)
tfi.discard();
}
}
// Protected methods and classes
/** Construct a key which represents an individual host name.
*@param hostName is the name of the connector.
*@return the cache key.
*/
protected static String getRobotsKey(String hostName)
{
return "ROBOTS_"+hostName;
}
/** Read robots data, if it exists.
*@return null if the data doesn't exist at all. Return robots data if it does.
*/
protected RobotsData readRobotsData(String hostName, IVersionActivity activities)
throws ManifoldCFException
{
try
{
ArrayList list = new ArrayList();
list.add(hostName);
IResultSet set = performQuery("SELECT "+robotsField+","+expirationField+" FROM "+getTableName()+
" WHERE "+hostField+"=?",list,null,null);
if (set.getRowCount() == 0)
return null;
if (set.getRowCount() > 1)
throw new ManifoldCFException("Unexpected number of robotsdata rows matching '"+hostName+"': "+Integer.toString(set.getRowCount()));
IResultRow row = set.getRow(0);
long expiration = ((Long)row.getValue(expirationField)).longValue();
BinaryInput bi = (BinaryInput)row.getValue(robotsField);
if (bi == null)
return new RobotsData(null,expiration,hostName,activities);
try
{
InputStream is = bi.getStream();
return new RobotsData(is,expiration,hostName,activities);
}
finally
{
bi.discard();
}
}
catch (InterruptedIOException e)
{
throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new ManifoldCFException("IO error reading robots data for "+hostName+": "+e.getMessage(),e);
}
}
/** Convert a string from the robots file into a readable form that does NOT contain NUL characters (since postgresql does not accept those).
*/
protected static String makeReadable(String inputString)
{
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < inputString.length())
{
char y = inputString.charAt(i++);
if (y >= ' ')
sb.append(y);
else
{
sb.append('^');
sb.append((char)(y + '@'));
}
}
return sb.toString();
}
/** This is a cached data item.
*/
protected static class RobotsData
{
protected long expiration;
protected ArrayList records = null;
/** Constructor. */
public RobotsData(InputStream is, long expiration, String hostName, IVersionActivity activities)
throws IOException, ManifoldCFException
{
this.expiration = expiration;
if (is == null)
{
records = null;
return;
}
Reader r = new InputStreamReader(is,"utf-8");
try
{
BufferedReader br = new BufferedReader(r);
try
{
parseRobotsTxt(br,hostName,activities);
}
finally
{
br.close();
}
}
finally
{
r.close();
}
}
/** Check if fetch is allowed */
public boolean isFetchAllowed(String userAgent, String pathString)
{
if (records == null)
return true;
boolean wasDisallowed = false;
boolean wasAllowed = false;
// First matching user-agent takes precedence, according to the following chunk of spec:
// "These name tokens are used in User-agent lines in /robots.txt to
// identify to which specific robots the record applies. The robot
// must obey the first record in /robots.txt that contains a User-
// Agent line whose value contains the name token of the robot as a
// substring. The name comparisons are case-insensitive. If no such
// record exists, it should obey the first record with a User-agent
// line with a "*" value, if present. If no record satisfied either
// condition, or no records are present at all, access is unlimited."
boolean sawAgent = false;
String userAgentUpper = userAgent.toUpperCase();
int i = 0;
while (i < records.size())
{
Record r = (Record)records.get(i++);
if (r.isAgentMatch(userAgentUpper,false))
{
if (r.isDisallowed(pathString))
wasDisallowed = true;
if (r.isAllowed(pathString))
wasAllowed = true;
sawAgent = true;
break;
}
}
if (sawAgent == false)
{
i = 0;
while (i < records.size())
{
Record r = (Record)records.get(i++);
if (r.isAgentMatch("*",true))
{
if (r.isDisallowed(pathString))
wasDisallowed = true;
if (r.isAllowed(pathString))
wasAllowed = true;
sawAgent = true;
break;
}
}
}
if (sawAgent == false)
return true;
// Allowed always overrides disallowed
if (wasAllowed)
return true;
if (wasDisallowed)
return false;
// No match -> crawl allowed
return true;
}
/** Get expiration */
public long getExpirationTime()
{
return expiration;
}
/** Parse the robots.txt file using a reader.
* Is NOT expected to close the stream.
*/
protected void parseRobotsTxt(BufferedReader r, String hostName, IVersionActivity activities)
throws IOException, ManifoldCFException
{
boolean parseCompleted = false;
boolean robotsWasHtml = false;
boolean foundErrors = false;
String description = null;
long startParseTime = System.currentTimeMillis();
try
{
records = new ArrayList();
Record record = null;
boolean seenAction = false;
while (true)
{
String x = r.readLine();
if (x == null)
break;
int numSignPos = x.indexOf("#");
if (numSignPos != -1)
x = x.substring(0,numSignPos);
String lowercaseLine = x.toLowerCase().trim();
if (lowercaseLine.startsWith("user-agent:"))
{
if (seenAction)
{
records.add(record);
record = null;
seenAction = false;
}
if (record == null)
record = new Record();
String agentName = x.substring("User-agent:".length()).trim();
record.addAgent(agentName);
}
else if (lowercaseLine.startsWith("user-agent"))
{
if (seenAction)
{
records.add(record);
record = null;
seenAction = false;
}
if (record == null)
record = new Record();
String agentName = x.substring("User-agent".length()).trim();
record.addAgent(agentName);
}
else if (lowercaseLine.startsWith("disallow:"))
{
if (record == null)
{
description = "Disallow without User-agent";
Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description);
foundErrors = true;
}
else
{
String disallowPath = x.substring("Disallow:".length()).trim();
// The spec says that a blank disallow means let everything through.
if (disallowPath.length() > 0)
record.addDisallow(disallowPath);
seenAction = true;
}
}
else if (lowercaseLine.startsWith("disallow"))
{
if (record == null)
{
description = "Disallow without User-agent";
Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description);
foundErrors = true;
}
else
{
String disallowPath = x.substring("Disallow".length()).trim();
// The spec says that a blank disallow means let everything through.
if (disallowPath.length() > 0)
record.addDisallow(disallowPath);
seenAction = true;
}
}
else if (lowercaseLine.startsWith("allow:"))
{
if (record == null)
{
description = "Allow without User-agent";
Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description);
foundErrors = true;
}
else
{
String allowPath = x.substring("Allow:".length()).trim();
// The spec says that a blank disallow means let everything through.
if (allowPath.length() > 0)
record.addAllow(allowPath);
seenAction = true;
}
}
else if (lowercaseLine.startsWith("allow"))
{
if (record == null)
{
description = "Allow without User-agent";
Logging.connectors.warn("Web: Bad robots.txt file format from '"+hostName+"': "+description);
foundErrors = true;
}
else
{
String allowPath = x.substring("Allow".length()).trim();
// The spec says that a blank disallow means let everything through.
if (allowPath.length() > 0)
record.addAllow(allowPath);
seenAction = true;
}
}
else if (lowercaseLine.startsWith("crawl-delay:"))
{
// We don't complain about this, but right now we don't listen to it either.
}
else if (lowercaseLine.startsWith("crawl-delay"))
{
// We don't complain about this, but right now we don't listen to it either.
}
else
{
// If it's not just a blank line, complain
if (x.trim().length() > 0)
{
String problemLine = makeReadable(x);
description = "Unknown robots.txt line: '"+problemLine+"'";
Logging.connectors.warn("Web: Unknown robots.txt line from '"+hostName+"': '"+problemLine+"'");
if (x.indexOf("<html") != -1 || x.indexOf("<HTML") != -1)
{
// Looks like some kind of an html file, probably as a result of a redirection, so just abort as if we have a page error
robotsWasHtml = true;
parseCompleted = true;
break;
}
foundErrors = true;
}
}
}
if (record != null)
records.add(record);
parseCompleted = true;
}
finally
{
// Log the fact that we attempted to parse robots.txt, as well as what happened
// These are the following situations we will report:
// (1) INCOMPLETE - Parsing did not complete - if the stream was interrupted
// (2) HTML - Robots was html - if the robots data seemed to be html
// (3) ERRORS - Robots had errors - if the robots data was accepted but had errors in it
// (4) SUCCESS - Robots parsed successfully - if the robots data was parsed without problem
String status;
if (parseCompleted)
{
if (robotsWasHtml)
{
status = "HTML";
description = "Robots file contained HTML, skipped";
}
else
{
if (foundErrors)
{
status = "ERRORS";
// description should already be set
}
else
{
status = "SUCCESS";
description = null;
}
}
}
else
{
status = "INCOMPLETE";
description = "Parsing was interrupted";
}
activities.recordActivity(new Long(startParseTime),WebcrawlerConnector.ACTIVITY_ROBOTSPARSE,
null,hostName,status,description,null);
}
}
}
/** Check if path matches specification */
protected static boolean doesPathMatch(String path, String spec)
{
// For robots 1.0, this function would do just this:
// return path.startsWith(spec);
// However, we implement the "google bot" spec, which allows wildcard matches that are, in fact, regular-expression-like in some ways.
// The "specification" can be found here: http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=40367
return doesPathMatch(path,0,spec,0);
}
/** Recursive method for matching specification to path. */
protected static boolean doesPathMatch(String path, int pathIndex, String spec, int specIndex)
{
while (true)
{
if (specIndex == spec.length())
// Hit the end of the specification! We're done.
return true;
char specChar = spec.charAt(specIndex++);
if (specChar == '*')
{
// Found a specification wildcard.
// Eat up all the '*' characters at this position - otherwise each additional one increments the exponent of how long this can take,
// making denial-of-service via robots parsing a possibility.
while (specIndex < spec.length())
{
if (spec.charAt(specIndex) != '*')
break;
specIndex++;
}
// It represents zero or more characters, so we must recursively try for a match against all remaining characters in the path string.
while (true)
{
boolean match = doesPathMatch(path,pathIndex,spec,specIndex);
if (match)
return true;
if (path.length() == pathIndex)
// Nothing further to try, and no match
return false;
pathIndex++;
// Try again
}
}
else if (specChar == '$' && specIndex == spec.length())
{
// Found a specification end-of-path character.
// (It can only be legitimately the last character of the specification.)
return pathIndex == path.length();
}
if (pathIndex == path.length())
// Hit the end of the path! (but not the end of the specification!)
return false;
if (path.charAt(pathIndex) != specChar)
return false;
// On to the next match
pathIndex++;
}
}
/** This is the object description for a robots host object.
* This is the key that is used to look up cached data.
*/
protected static class HostDescription extends org.apache.manifoldcf.core.cachemanager.BaseDescription
{
protected String hostName;
protected String criticalSectionName;
protected StringSet cacheKeys;
public HostDescription(String hostName, StringSet invKeys)
{
super("robotscache");
this.hostName = hostName;
criticalSectionName = getClass().getName()+"-"+hostName;
cacheKeys = invKeys;
}
public String getHostName()
{
return hostName;
}
public int hashCode()
{
return hostName.hashCode();
}
public boolean equals(Object o)
{
if (!(o instanceof HostDescription))
return false;
HostDescription d = (HostDescription)o;
return d.hostName.equals(hostName);
}
public String getCriticalSectionName()
{
return criticalSectionName;
}
/** Get the cache keys for an object (which may or may not exist yet in
* the cache). This method is called in order for cache manager to throw the correct locks.
* @return the object's cache keys, or null if the object should not
* be cached.
*/
public StringSet getObjectKeys()
{
return cacheKeys;
}
/** Get the object class for an object. The object class is used to determine
* the group of objects treated in the same LRU manner.
* @return the newly created object's object class, or null if there is no
* such class, and LRU behavior is not desired.
*/
public ICacheClass getObjectClass()
{
return robotsCacheClass;
}
}
/** Cache class for robots.
* An instance of this class describes the cache class for robots data caching. There's
* only ever a need for one, so that will be created statically.
*/
protected static class RobotsCacheClass implements ICacheClass
{
/** Get the name of the object class.
* This determines the set of objects that are treated in the same
* LRU pool.
*@return the class name.
*/
public String getClassName()
{
// We count all the robot data, so this is a constant string.
return "ROBOTSCLASS";
}
/** Get the maximum LRU count of the object class.
*@return the maximum number of the objects of the particular class
* allowed.
*/
public int getMaxLRUCount()
{
// Hardwired for the moment; 2000 robots data records will be cached,
// and no more.
return 2000;
}
}
/** This is the executor object for locating robots host objects.
* This object furnishes the operations the cache manager needs to rebuild objects that it needs that are
* not in the cache at the moment.
*/
protected static class HostExecutor extends org.apache.manifoldcf.core.cachemanager.ExecutorBase
{
// Member variables
protected RobotsManager thisManager;
protected RobotsData returnValue;
protected HostDescription thisHost;
protected IVersionActivity activities;
/** Constructor.
*@param manager is the RobotsManager class instance.
*@param objectDescription is the desired object description.
*/
public HostExecutor(RobotsManager manager, IVersionActivity activities, HostDescription objectDescription)
{
super();
thisManager = manager;
this.activities = activities;
thisHost = objectDescription;
returnValue = null;
}
/** Get the result.
*@return the looked-up or read cached instance.
*/
public RobotsData getResults()
{
return returnValue;
}
/** Create a set of new objects to operate on and cache. This method is called only
* if the specified object(s) are NOT available in the cache. The specified objects
* should be created and returned; if they are not created, it means that the
* execution cannot proceed, and the execute() method will not be called.
* @param objectDescriptions is the set of unique identifier of the object.
* @return the newly created objects to cache, or null, if any object cannot be created.
* The order of the returned objects must correspond to the order of the object descriptinos.
*/
public Object[] create(ICacheDescription[] objectDescriptions) throws ManifoldCFException
{
// I'm not expecting multiple values to be request, so it's OK to walk through the objects
// and do a request at a time.
RobotsData[] rval = new RobotsData[objectDescriptions.length];
int i = 0;
while (i < rval.length)
{
HostDescription desc = (HostDescription)objectDescriptions[i];
// I need to cache both the data and the expiration date, and pick up both when I
// do the query. This is because I don't want to cache based on request time, since that
// would screw up everything!
rval[i] = thisManager.readRobotsData(desc.getHostName(),activities);
i++;
}
return rval;
}
/** Notify the implementing class of the existence of a cached version of the
* object. The object is passed to this method so that the execute() method below
* will have it available to operate on. This method is also called for all objects
* that are freshly created as well.
* @param objectDescription is the unique identifier of the object.
* @param cachedObject is the cached object.
*/
public void exists(ICacheDescription objectDescription, Object cachedObject) throws ManifoldCFException
{
// Cast what came in as what it really is
HostDescription objectDesc = (HostDescription)objectDescription;
RobotsData robotsData = (RobotsData)cachedObject;
if (objectDesc.equals(thisHost))
returnValue = robotsData;
}
/** Perform the desired operation. This method is called after either createGetObject()
* or exists() is called for every requested object.
*/
public void execute() throws ManifoldCFException
{
// Does nothing; we only want to fetch objects in this cacher.
}
}
/** This class represents a record in a robots.txt file. It contains one or
* more user-agents, and one or more disallows.
*/
protected static class Record
{
protected ArrayList userAgents = new ArrayList();
protected ArrayList disallows = new ArrayList();
protected ArrayList allows = new ArrayList();
/** Constructor.
*/
public Record()
{
}
/** Add a user-agent.
*/
public void addAgent(String agentName)
{
userAgents.add(agentName);
}
/** Add a disallow.
*/
public void addDisallow(String disallowPath)
{
disallows.add(disallowPath);
}
/** Add an allow.
*/
public void addAllow(String allowPath)
{
allows.add(allowPath);
}
/** See if user-agent matches.
*/
public boolean isAgentMatch(String agentNameUpper, boolean exactMatch)
{
int i = 0;
while (i < userAgents.size())
{
String agent = ((String)userAgents.get(i++)).toUpperCase();
if (exactMatch && agent.trim().equals(agentNameUpper))
return true;
if (!exactMatch && agentNameUpper.indexOf(agent) != -1)
return true;
}
return false;
}
/** See if path is disallowed. Only called if user-agent has already
* matched. (This checks if there's an explicit match with one of the
* Disallows clauses.)
*/
public boolean isDisallowed(String path)
{
int i = 0;
while (i < disallows.size())
{
String disallow = (String)disallows.get(i++);
if (doesPathMatch(path,disallow))
return true;
}
return false;
}
/** See if path is allowed. Only called if user-agent has already
* matched. (This checks if there's an explicit match with one of the
* Allows clauses).
*/
public boolean isAllowed(String path)
{
int i = 0;
while (i < allows.size())
{
String allow = (String)allows.get(i++);
if (doesPathMatch(path,allow))
return true;
}
return false;
}
}
}
| buddhikaDilhan/GSoC_buddhika | connectors/webcrawler/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/webcrawler/RobotsManager.java | Java | apache-2.0 | 30,130 |
/*
* Copyright 2017 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.collector.mapper.flink;
import com.navercorp.pinpoint.common.server.bo.stat.JvmGcBo;
import com.navercorp.pinpoint.thrift.dto.flink.TFJvmGc;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author minwoo.jung
*/
public class TFJvmGcMapperTest {
@Test
public void mapTest() {
TFJvmGcMapper tFJvmGcMapper = new TFJvmGcMapper();
JvmGcBo jvmGcBo = new JvmGcBo();
jvmGcBo.setHeapUsed(3000);
jvmGcBo.setNonHeapUsed(500);
TFJvmGc tFJvmGc = tFJvmGcMapper.map(jvmGcBo);
assertEquals(3000, tFJvmGc.getJvmMemoryHeapUsed());
assertEquals(500, tFJvmGc.getJvmMemoryNonHeapUsed());
}
} | koo-taejin/pinpoint | collector/src/test/java/com/navercorp/pinpoint/collector/mapper/flink/TFJvmGcMapperTest.java | Java | apache-2.0 | 1,299 |
/**
* Copyright (C) 2012 Vaadin Ltd
*
* This program is available under Commercial Vaadin Add-On License 3.0
* (CVALv3).
*
* See the file licensing.txt distributed with this software for more
* information about licensing.
*
* You should have received a copy of the license along with this program.
* If not, see <http://vaadin.com/license/cval-3>.
*/
package com.vaadin.testbench.elements;
import com.vaadin.testbench.elementsbase.ServerClass;
@ServerClass("com.vaadin.ui.LegacyWindow")
public class LegacyWindowElement extends UIElement {
}
| bpupadhyaya/dashboard-demo-1 | src/main/java/com/vaadin/testbench/elements/LegacyWindowElement.java | Java | apache-2.0 | 557 |
package sql_connect_database;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import manage_incomeoutlay.IncomeOutlay;
import manage_incomeoutlay.NomalTypeOfUser;
import manage_incomeoutlay.TypeOfUse;
import member_system.User;
import connect_database.CreateConnection;
import connect_database.CreateDistributeCon;
import connect_database.ManageConnection;
import connect_database.SelectIncomeOutlay;
import connect_database.SelectUser;
import framework_azure.ChangeForSQL;
import framework_azure.ConvertNameId;
public class SQL_SelectIncomeOutlay implements SelectIncomeOutlay {
@Override
public ArrayList<IncomeOutlay> selectIncomeOutlay(User user,
Date startDate, Date stopDate) throws Exception {
// TODO Auto-generated method stub
String stringStartDate = ChangeForSQL.changeDateToString(startDate);
String stringStopDate = ChangeForSQL.changeDateToString(stopDate);
ArrayList<IncomeOutlay> list = new ArrayList<IncomeOutlay>();
Connection connection = ManageConnection.getConnection(user.getUsername().hashCode());
Statement statement = connection.createStatement();
String select = String.format("select * from incomeoutlay ");
String join = "inner join type_incomeoutlay"
+ " on incomeoutlay.typeName = type_incomeoutlay.typeName and incomeoutlay.userId = type_incomeoutlay.userId "
+ "inner join priority "
+ "on type_incomeoutlay.priorityId = priority.priorityId ";
String where = String.format("where saveDate <= %s and saveDate >= %s and incomeoutlay.userId = %s",
ChangeForSQL.changeString(stringStopDate),
ChangeForSQL.changeString(stringStartDate),
ChangeForSQL.changeString(String.valueOf(user.getUsername().hashCode()))
);
String sqlCommand = select+join+where;
System.out.println(sqlCommand);
ResultSet resultSet = statement.executeQuery(sqlCommand);
while(resultSet.next())
{
///////////// INCOME ///////////////////////////
String owner = user.getUsername();
String nameIncomeOutlay = resultSet.getString("name");
double amount = resultSet.getDouble("amount");
String saveDateString = resultSet.getString("saveDate");
String comment = resultSet.getString("commentDetail");
Date saveDate = ChangeForSQL.changeStringToDate(saveDateString);
////////////////////////////////////////////////////
//////////////////// TYPE OF USE ///////////////////////
String priorityName = resultSet.getString("priorityName");
String typeName = resultSet.getString("typeName");
String type = resultSet.getString("type");
//////////////////////////////////////////////////////////////////////////
TypeOfUse typeOfUse = new NomalTypeOfUser(typeName, type, priorityName);
IncomeOutlay incomeOutlay = new IncomeOutlay(owner, nameIncomeOutlay, amount, saveDate, typeOfUse, comment);
// System.out.println(incomeOutlay);
list.add(incomeOutlay);
}
if(list.size()==0)
{
return null;
}
else
{
return list;
}
}
@Override
public ArrayList<IncomeOutlay> selectIncomeOutlayWithJob(String jobName,
Date startDate, Date stopDate) throws Exception {
// TODO Auto-generated method stub
int numDb = 2;
ArrayList< ArrayList<IncomeOutlay>> listAll = new ArrayList<ArrayList<IncomeOutlay>>();
for(int i=0;i<2;i++)
{
ArrayList<IncomeOutlay> temList = this.getIncomeOutlayWithJob(jobName, startDate, stopDate, i);
listAll.add(temList);
}
ArrayList<IncomeOutlay> returnList = new ArrayList<IncomeOutlay>();
for(int i=0;i<numDb;i++)
{
ArrayList<IncomeOutlay> temList = listAll.get(i);
returnList.addAll(temList);
}
return returnList;
}
private ArrayList<IncomeOutlay> getIncomeOutlayWithJob(String jobName,
Date startDate, Date stopDate,int selectDB) throws Exception
{
Connection conn = new CreateDistributeCon().createConnection(selectDB);
Statement statement = conn.createStatement();
String stringStartDate = ChangeForSQL.changeDateToString(startDate);
String stringStopDate = ChangeForSQL.changeDateToString(stopDate);
String jobId = ConvertNameId.getObject().nameToId("job", jobName);
ArrayList<IncomeOutlay> list = new ArrayList<IncomeOutlay>();
String sql_select = "select * from incomeoutlay ";
String sql_join =
" inner join user_data "
+ " on incomeoutlay.userId = user_data.userId "
+"inner join type_incomeoutlay"
+ " on incomeoutlay.typeName = type_incomeoutlay.typeName and incomeoutlay.userId = type_incomeoutlay.userId "
+ "inner join priority "
+ " on type_incomeoutlay.priorityId = priority.priorityId ";
String where = String.format("where saveDate <= %s and saveDate >= %s and jobId =%s ",
ChangeForSQL.changeString(stringStopDate),
ChangeForSQL.changeString(stringStartDate),
ChangeForSQL.changeString(jobId)
);
String sql_command = sql_select+sql_join+where;
// System.out.println(sql_command);
ResultSet resultSet = statement.executeQuery(sql_command);
while(resultSet.next())
{
///////////// INCOME ///////////////////////////
String owner = resultSet.getString("username");
String nameIncomeOutlay = resultSet.getString("name");
double amount = resultSet.getDouble("amount");
String saveDateString = resultSet.getString("saveDate");
String comment = resultSet.getString("commentDetail");
Date saveDate = ChangeForSQL.changeStringToDate(saveDateString);
////////////////////////////////////////////////////
//////////////////// TYPE OF USE ///////////////////////
String priorityName = resultSet.getString("priorityName");
String typeName = resultSet.getString("typeName");
String type = resultSet.getString("type");
//////////////////////////////////////////////////////////////////////////
TypeOfUse typeOfUse = new NomalTypeOfUser(typeName, type, priorityName);
IncomeOutlay incomeOutlay = new IncomeOutlay(owner, nameIncomeOutlay, amount, saveDate, typeOfUse, comment);
// System.out.println(incomeOutlay);
list.add(incomeOutlay);
}
return list;
}
}
| CE-KMITL-CLOUD-2014/Money-Movement | ROOT/src/sql_connect_database/SQL_SelectIncomeOutlay.java | Java | artistic-2.0 | 6,249 |
package slack
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"os"
)
const (
// APIURL of the slack api.
APIURL = "https://slack.com/api/"
// WEBAPIURLFormat ...
WEBAPIURLFormat = "https://%s.slack.com/api/users.admin.%s?t=%d"
)
// httpClient defines the minimal interface needed for an http.Client to be implemented.
type httpClient interface {
Do(*http.Request) (*http.Response, error)
}
// ResponseMetadata holds pagination metadata
type ResponseMetadata struct {
Cursor string `json:"next_cursor"`
}
func (t *ResponseMetadata) initialize() *ResponseMetadata {
if t != nil {
return t
}
return &ResponseMetadata{}
}
// AuthTestResponse ...
type AuthTestResponse struct {
URL string `json:"url"`
Team string `json:"team"`
User string `json:"user"`
TeamID string `json:"team_id"`
UserID string `json:"user_id"`
// EnterpriseID is only returned when an enterprise id present
EnterpriseID string `json:"enterprise_id,omitempty"`
}
type authTestResponseFull struct {
SlackResponse
AuthTestResponse
}
// Client for the slack api.
type ParamOption func(*url.Values)
type Client struct {
token string
endpoint string
debug bool
log ilogger
httpclient httpClient
}
// Option defines an option for a Client
type Option func(*Client)
// OptionHTTPClient - provide a custom http client to the slack client.
func OptionHTTPClient(client httpClient) func(*Client) {
return func(c *Client) {
c.httpclient = client
}
}
// OptionDebug enable debugging for the client
func OptionDebug(b bool) func(*Client) {
return func(c *Client) {
c.debug = b
}
}
// OptionLog set logging for client.
func OptionLog(l logger) func(*Client) {
return func(c *Client) {
c.log = internalLog{logger: l}
}
}
// OptionAPIURL set the url for the client. only useful for testing.
func OptionAPIURL(u string) func(*Client) {
return func(c *Client) { c.endpoint = u }
}
// New builds a slack client from the provided token and options.
func New(token string, options ...Option) *Client {
s := &Client{
token: token,
endpoint: APIURL,
httpclient: &http.Client{},
log: log.New(os.Stderr, "nlopes/slack", log.LstdFlags|log.Lshortfile),
}
for _, opt := range options {
opt(s)
}
return s
}
// AuthTest tests if the user is able to do authenticated requests or not
func (api *Client) AuthTest() (response *AuthTestResponse, error error) {
return api.AuthTestContext(context.Background())
}
// AuthTestContext tests if the user is able to do authenticated requests or not with a custom context
func (api *Client) AuthTestContext(ctx context.Context) (response *AuthTestResponse, err error) {
api.Debugf("Challenging auth...")
responseFull := &authTestResponseFull{}
err = api.postMethod(ctx, "auth.test", url.Values{"token": {api.token}}, responseFull)
if err != nil {
return nil, err
}
return &responseFull.AuthTestResponse, responseFull.Err()
}
// Debugf print a formatted debug line.
func (api *Client) Debugf(format string, v ...interface{}) {
if api.debug {
api.log.Output(2, fmt.Sprintf(format, v...))
}
}
// Debugln print a debug line.
func (api *Client) Debugln(v ...interface{}) {
if api.debug {
api.log.Output(2, fmt.Sprintln(v...))
}
}
// Debug returns if debug is enabled.
func (api *Client) Debug() bool {
return api.debug
}
// post to a slack web method.
func (api *Client) postMethod(ctx context.Context, path string, values url.Values, intf interface{}) error {
return postForm(ctx, api.httpclient, api.endpoint+path, values, intf, api)
}
// get a slack web method.
func (api *Client) getMethod(ctx context.Context, path string, values url.Values, intf interface{}) error {
return getResource(ctx, api.httpclient, api.endpoint+path, values, intf, api)
}
| nlopes/slack | slack.go | GO | bsd-2-clause | 3,771 |
i = 40 - 3
for j in range(3, 12, 2):
print(j)
i = i + 1
print(i)
| almarklein/wasmfun | simplepy/example1.py | Python | bsd-2-clause | 74 |
class Tag < Formula
desc "Manipulate and query tags on macOS files"
homepage "https://github.com/jdberry/tag/"
url "https://github.com/jdberry/tag/archive/v0.10.tar.gz"
sha256 "5ab057d3e3f0dbb5c3be3970ffd90f69af4cb6201c18c1cbaa23ef367e5b071e"
license "MIT"
revision 1
head "https://github.com/jdberry/tag.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "68b99acc16647610b02c286aae5b302c7c2128164817d9eb197d2d5f9f51ca72"
sha256 cellar: :any_skip_relocation, big_sur: "a63e067af22cda164f890108f610bfecd4bc3b2759fd1dd473dac59d1654a156"
sha256 cellar: :any_skip_relocation, catalina: "e1572ae47d558d60983f7c1cbe9ae42a5c7f2dcb950762ab6c721e81351f5657"
sha256 cellar: :any_skip_relocation, mojave: "ee5dbe68476b6ae900b92486f3dc3c7a9755296c1fee54a75cd64c7d6af66763"
sha256 cellar: :any_skip_relocation, high_sierra: "5801c9fac7b1a4bad52f02fd8a09b64050ebc52515bd96115153c7049bd4619f"
sha256 cellar: :any_skip_relocation, sierra: "5711ce58bd5b224252f1869f84f937c6bca0775bf4c86a6a1168418c1218dc98"
end
def install
system "make", "install", "prefix=#{prefix}"
end
test do
test_tag = "test_tag"
test_file = Pathname.pwd+"test_file"
touch test_file
system "#{bin}/tag", "--add", test_tag, test_file
assert_equal test_tag, `#{bin}/tag --list --no-name #{test_file}`.chomp
end
end
| mbcoguno/homebrew-core | Formula/tag.rb | Ruby | bsd-2-clause | 1,407 |
// Copyright ©2005, 2006 Freescale Semiconductor, Inc.
// Please see the License for the specific language governing rights and
// limitations under the License.
// ===========================================================================
// MEModelMenuBar.cpp © 1996-97 Metrowerks Inc. All rights reserved.
// ===========================================================================
//
// Created: 10/10/96
// $Date: 2006/01/18 01:33:09 $
// $History: MEModelMenuBar.cpp $
//
// ***************** Version 6 *****************
// User: scouten QDate: 03/17/97 Time: 16:57
// Updated in $/Constructor/Source files/CO- Core/Editors/Menus
// Added object titles for property inspector. (Bug fix #1104.)
//
// ***************** Version 5 *****************
// User: scouten QDate: 02/20/97 Time: 17:07
// Updated in $/Constructor/Source files/CO- Core/Editors/Menus
// Improved commenting.
//
// ***************** Version 4 *****************
// User: Andrew Date: 02/04/97 Time: 21:04
// Checked in '$/ConstructorWin/Sources'
// Comment: Initial merge for MSVC-hosted build
//
// ***************** Version 3 *****************
// User: scouten Date: 12/06/96 Time: 23:55
// Checked in '$/Constructor/Source files/Editors/Menus/+ Generic menu editor'
// Comment: Updated to Clint's drop 12/06/96.
//
// ***************** Version 2 *****************
// User: scouten Date: 10/23/96 Time: 20:56
// Checked in '$/Constructor/Source files/Editors/Menus'
// Comment: Baseline working version of menu editor.
//
// ***************** Version 1 *****************
// User: scouten Date: 10/16/96 Time: 01:59
// Created
// Comment: Baseline source 15 October 1996.
//
// ===========================================================================
// Prefix file for Windows build
#ifdef WINVER
#include "ctor.h"
#endif
// ===========================================================================
#include "MEModelMenuBar.h"
// Core : Data model : Attributes
#include "DMContainerAttribute.h"
// ===========================================================================
// * Resource IDs
// ===========================================================================
const ResIDT STR_METitleStrings = 7010;
const ResIDT str_MenuBar = 1;
const ResIDT str_Menu = 2;
const ResIDT str_MenuItem = 3;
const ResIDT str_MenuSeparator = 4;
const ResIDT str_SpaceOpenQuote = 5;
const ResIDT str_CloseQuote = 6;
// ===========================================================================
#pragma mark *** MEModelMenuBar ***
// ---------------------------------------------------------------------------
// * MEModelMenuBar(LStream*)
// ---------------------------------------------------------------------------
// Stream constructor. No extra data is read for MEModelMenu.
MEModelMenuBar::MEModelMenuBar(
LStream* inStream)
: DMObject(inStream)
{
}
// ---------------------------------------------------------------------------
// * MEModelMenuBar(MEModelMenuBar&)
// ---------------------------------------------------------------------------
// Copy constructor
MEModelMenuBar::MEModelMenuBar(
const MEModelMenuBar& inOriginal)
: DMObject(inOriginal)
{
ValidateObject_(&inOriginal);
}
// ---------------------------------------------------------------------------
// * ~MEModelMenuBar
// ---------------------------------------------------------------------------
// Destructor
MEModelMenuBar::~MEModelMenuBar()
{
ValidateThis_();
}
// ---------------------------------------------------------------------------
// * GetDisplayableName
// ---------------------------------------------------------------------------
// Make a displayable name for property inspector. Just returns the string
// "Menu Bar".
void
MEModelMenuBar::GetDisplayableName(
LStr255& outTitle) const
{
// Validate pointers.
ValidateThis_();
// Start with object type.
outTitle = LStr255(STR_METitleStrings, str_MenuBar);
}
| mctully/tntbasic | third_party/PowerPlant/constructor/Constructor_Pro/Constructor/Source files/CO- Core/Editors/Menus/MEModelMenuBar.cpp | C++ | bsd-2-clause | 4,013 |
#include "master.hpp"
namespace factor
{
code_heap::code_heap(cell size)
{
if(size > ((u64)1 << (sizeof(cell) * 8 - 6))) fatal_error("Heap too large",size);
seg = new segment(align_page(size),true);
if(!seg) fatal_error("Out of memory in code_heap constructor",size);
cell start = seg->start + seh_area_size;
allocator = new free_list_allocator<code_block>(seg->end - start,start);
/* See os-windows-nt-x86.64.cpp for seh_area usage */
seh_area = (char *)seg->start;
}
code_heap::~code_heap()
{
delete allocator;
allocator = NULL;
delete seg;
seg = NULL;
}
void code_heap::write_barrier(code_block *compiled)
{
points_to_nursery.insert(compiled);
points_to_aging.insert(compiled);
}
void code_heap::clear_remembered_set()
{
points_to_nursery.clear();
points_to_aging.clear();
}
bool code_heap::uninitialized_p(code_block *compiled)
{
return uninitialized_blocks.count(compiled) > 0;
}
bool code_heap::marked_p(code_block *compiled)
{
return allocator->state.marked_p(compiled);
}
void code_heap::set_marked_p(code_block *compiled)
{
allocator->state.set_marked_p(compiled);
}
void code_heap::clear_mark_bits()
{
allocator->state.clear_mark_bits();
}
void code_heap::free(code_block *compiled)
{
assert(!uninitialized_p(compiled));
points_to_nursery.erase(compiled);
points_to_aging.erase(compiled);
allocator->free(compiled);
}
void code_heap::flush_icache()
{
factor::flush_icache(seg->start,seg->size);
}
/* Allocate a code heap during startup */
void factor_vm::init_code_heap(cell size)
{
code = new code_heap(size);
}
bool factor_vm::in_code_heap_p(cell ptr)
{
return (ptr >= code->seg->start && ptr <= code->seg->end);
}
struct word_updater {
factor_vm *parent;
bool reset_inline_caches;
word_updater(factor_vm *parent_, bool reset_inline_caches_) :
parent(parent_), reset_inline_caches(reset_inline_caches_) {}
void operator()(code_block *compiled, cell size)
{
parent->update_word_references(compiled,reset_inline_caches);
}
};
/* Update pointers to words referenced from all code blocks.
Only needed after redefining an existing word.
If generic words were redefined, inline caches need to be reset. */
void factor_vm::update_code_heap_words(bool reset_inline_caches)
{
word_updater updater(this,reset_inline_caches);
each_code_block(updater);
}
/* Fix up new words only.
Fast path for compilation units that only define new words. */
void factor_vm::initialize_code_blocks()
{
std::map<code_block *, cell>::const_iterator iter = code->uninitialized_blocks.begin();
std::map<code_block *, cell>::const_iterator end = code->uninitialized_blocks.end();
for(; iter != end; iter++)
initialize_code_block(iter->first,iter->second);
code->uninitialized_blocks.clear();
}
void factor_vm::primitive_modify_code_heap()
{
bool reset_inline_caches = to_boolean(ctx->pop());
bool update_existing_words = to_boolean(ctx->pop());
data_root<array> alist(ctx->pop(),this);
cell count = array_capacity(alist.untagged());
if(count == 0)
return;
for(cell i = 0; i < count; i++)
{
data_root<array> pair(array_nth(alist.untagged(),i),this);
data_root<word> word(array_nth(pair.untagged(),0),this);
data_root<object> data(array_nth(pair.untagged(),1),this);
switch(data.type())
{
case QUOTATION_TYPE:
jit_compile_word(word.value(),data.value(),false);
break;
case ARRAY_TYPE:
{
array *compiled_data = data.as<array>().untagged();
cell parameters = array_nth(compiled_data,0);
cell literals = array_nth(compiled_data,1);
cell relocation = array_nth(compiled_data,2);
cell labels = array_nth(compiled_data,3);
cell code = array_nth(compiled_data,4);
code_block *compiled = add_code_block(
code_block_optimized,
code,
labels,
word.value(),
relocation,
parameters,
literals);
word->code = compiled;
}
break;
default:
critical_error("Expected a quotation or an array",data.value());
break;
}
update_word_entry_point(word.untagged());
}
if(update_existing_words)
update_code_heap_words(reset_inline_caches);
else
initialize_code_blocks();
}
code_heap_room factor_vm::code_room()
{
code_heap_room room;
room.size = code->allocator->size;
room.occupied_space = code->allocator->occupied_space();
room.total_free = code->allocator->free_space();
room.contiguous_free = code->allocator->largest_free_block();
room.free_block_count = code->allocator->free_block_count();
return room;
}
void factor_vm::primitive_code_room()
{
code_heap_room room = code_room();
ctx->push(tag<byte_array>(byte_array_from_value(&room)));
}
struct stack_trace_stripper {
explicit stack_trace_stripper() {}
void operator()(code_block *compiled, cell size)
{
compiled->owner = false_object;
}
};
void factor_vm::primitive_strip_stack_traces()
{
stack_trace_stripper stripper;
each_code_block(stripper);
}
struct code_block_accumulator {
std::vector<cell> objects;
void operator()(code_block *compiled, cell size)
{
objects.push_back(compiled->owner);
objects.push_back(compiled->parameters);
objects.push_back(compiled->relocation);
objects.push_back(tag_fixnum(compiled->type()));
objects.push_back(tag_fixnum(compiled->size()));
/* Note: the entry point is always a multiple of the heap
alignment (16 bytes). We cannot allocate while iterating
through the code heap, so it is not possible to call allot_cell()
here. It is OK, however, to add it as if it were a fixnum, and
have library code shift it to the left by 4. */
cell entry_point = (cell)compiled->entry_point();
assert((entry_point & (data_alignment - 1)) == 0);
assert((entry_point & TAG_MASK) == FIXNUM_TYPE);
objects.push_back(entry_point);
}
};
cell factor_vm::code_blocks()
{
code_block_accumulator accum;
each_code_block(accum);
return std_vector_to_array(accum.objects);
}
void factor_vm::primitive_code_blocks()
{
ctx->push(code_blocks());
}
}
| cataska/factor | vm/code_heap.cpp | C++ | bsd-2-clause | 5,956 |
# Copyright 2010-2014 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'spec_helper'
require 'command-t/scanner/file_scanner/ruby_file_scanner'
describe CommandT::FileScanner::RubyFileScanner do
before do
@dir = File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'fixtures')
@all_fixtures = %w(
bar/abc bar/xyz baz bing foo/alpha/t1 foo/alpha/t2 foo/beta
)
@scanner = CommandT::FileScanner::RubyFileScanner.new(@dir)
stub(::VIM).evaluate(/exists/) { 1 }
stub(::VIM).evaluate(/expand\(.+\)/) { '0' }
stub(::VIM).evaluate(/wildignore/) { '' }
end
describe 'paths method' do
it 'returns a list of regular files' do
@scanner.paths.should =~ @all_fixtures
end
end
describe 'path= method' do
it 'allows repeated applications of scanner at different paths' do
@scanner.paths.should =~ @all_fixtures
# drill down 1 level
@scanner.path = File.join(@dir, 'foo')
@scanner.paths.should =~ %w(alpha/t1 alpha/t2 beta)
# and another
@scanner.path = File.join(@dir, 'foo', 'alpha')
@scanner.paths.should =~ %w(t1 t2)
end
end
describe "'wildignore' exclusion" do
it "calls on VIM's expand() function for pattern filtering" do
@scanner = CommandT::FileScanner::RubyFileScanner.new @dir
mock(::VIM).evaluate(/expand\(.+\)/).times(10)
@scanner.paths
end
end
describe ':max_depth option' do
it 'does not descend below "max_depth" levels' do
@scanner = CommandT::FileScanner::RubyFileScanner.new @dir, :max_depth => 1
@scanner.paths.should =~ %w(bar/abc bar/xyz baz bing foo/beta)
end
end
end
| nendre/command-t | spec/command-t/scanner/file_scanner/ruby_file_scanner_spec.rb | Ruby | bsd-2-clause | 2,934 |
<?php
class MockFrapi_Controller_Api extends Frapi_Controller_Api
{
public function __construct() {}
} | rogeriopradoj/frapi-without-vhost | tests/mock/MockFrapi/Controller/Api.php | PHP | bsd-2-clause | 107 |
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include "UNIX_PreconfiguredTransportActionFixture.h"
#include <PreconfiguredTransportAction/UNIX_PreconfiguredTransportActionProvider.h>
UNIX_PreconfiguredTransportActionFixture::UNIX_PreconfiguredTransportActionFixture()
{
}
UNIX_PreconfiguredTransportActionFixture::~UNIX_PreconfiguredTransportActionFixture()
{
}
void UNIX_PreconfiguredTransportActionFixture::Run()
{
CIMName className("UNIX_PreconfiguredTransportAction");
CIMNamespaceName nameSpace("root/cimv2");
UNIX_PreconfiguredTransportAction _p;
UNIX_PreconfiguredTransportActionProvider _provider;
Uint32 propertyCount;
CIMOMHandle omHandle;
_provider.initialize(omHandle);
_p.initialize();
for(int pIndex = 0; _p.load(pIndex); pIndex++)
{
CIMInstance instance = _provider.constructInstance(className,
nameSpace,
_p);
CIMObjectPath path = instance.getPath();
cout << path.toString() << endl;
propertyCount = instance.getPropertyCount();
for(Uint32 i = 0; i < propertyCount; i++)
{
CIMProperty propertyItem = instance.getProperty(i);
cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl;
}
cout << "------------------------------------" << endl;
cout << endl;
}
_p.finalize();
}
| brunolauze/pegasus-providers | tests/UNIXProviders.Tests/UNIX_PreconfiguredTransportActionFixture.cpp | C++ | bsd-2-clause | 2,950 |
#include "catch.hpp"
#include "variant.hpp"
#include "variant_io.hpp"
#include <string>
struct some_visitor
{
int var_;
some_visitor(int init)
: var_(init) {}
int operator()(int val) const
{
return var_ + val;
}
int operator()(double val) const
{
return var_ + int(val);
}
int operator()(const std::string&) const
{
return 0;
}
};
TEST_CASE("non-const visitor works on const variants", "[visitor][unary visitor]")
{
using variant_type = const mapbox::util::variant<int, double, std::string>;
variant_type var1(123);
variant_type var2(3.2);
variant_type var3("foo");
REQUIRE(var1.get<int>() == 123);
REQUIRE(var2.get<double>() == Approx(3.2));
REQUIRE(var3.get<std::string>() == "foo");
some_visitor visitor{1};
REQUIRE(mapbox::util::apply_visitor(visitor, var1) == 124);
REQUIRE(mapbox::util::apply_visitor(visitor, var2) == 4);
REQUIRE(mapbox::util::apply_visitor(visitor, var3) == 0);
}
TEST_CASE("const visitor works on const variants", "[visitor][unary visitor]")
{
using variant_type = const mapbox::util::variant<int, double, std::string>;
variant_type var1(123);
variant_type var2(3.2);
variant_type var3("foo");
REQUIRE(var1.get<int>() == 123);
REQUIRE(var2.get<double>() == Approx(3.2));
REQUIRE(var3.get<std::string>() == "foo");
const some_visitor visitor{1};
REQUIRE(mapbox::util::apply_visitor(visitor, var1) == 124);
REQUIRE(mapbox::util::apply_visitor(visitor, var2) == 4);
REQUIRE(mapbox::util::apply_visitor(visitor, var3) == 0);
}
TEST_CASE("rvalue visitor works on const variants", "[visitor][unary visitor]")
{
using variant_type = const mapbox::util::variant<int, double, std::string>;
variant_type var1(123);
variant_type var2(3.2);
variant_type var3("foo");
REQUIRE(var1.get<int>() == 123);
REQUIRE(var2.get<double>() == Approx(3.2));
REQUIRE(var3.get<std::string>() == "foo");
REQUIRE(mapbox::util::apply_visitor(some_visitor{1}, var1) == 124);
REQUIRE(mapbox::util::apply_visitor(some_visitor{1}, var2) == 4);
REQUIRE(mapbox::util::apply_visitor(some_visitor{1}, var3) == 0);
}
TEST_CASE("visitor works on rvalue variants", "[visitor][unary visitor]")
{
using variant_type = const mapbox::util::variant<int, double, std::string>;
REQUIRE(mapbox::util::apply_visitor(some_visitor{1}, variant_type{123}) == 124);
REQUIRE(mapbox::util::apply_visitor(some_visitor{1}, variant_type{3.2}) == 4);
REQUIRE(mapbox::util::apply_visitor(some_visitor{1}, variant_type{"foo"}) == 0);
}
struct total_sizeof
{
total_sizeof() : total_(0) {}
template <class Value>
int operator()(const Value&) const
{
total_ += int(sizeof(Value));
return total_;
}
int result() const
{
return total_;
}
mutable int total_;
}; // total_sizeof
TEST_CASE("changes in visitor should be visible", "[visitor][unary visitor]")
{
using variant_type = mapbox::util::variant<int, std::string, double>;
variant_type v;
total_sizeof ts;
v = 5.9;
REQUIRE(mapbox::util::apply_visitor(ts, v) == sizeof(double));
REQUIRE(ts.result() == sizeof(double));
}
TEST_CASE("changes in const visitor (with mutable internals) should be visible", "[visitor][unary visitor]")
{
using variant_type = const mapbox::util::variant<int, std::string, double>;
variant_type v{"foo"};
const total_sizeof ts;
REQUIRE(mapbox::util::apply_visitor(ts, v) == sizeof(std::string));
REQUIRE(ts.result() == sizeof(std::string));
}
| beemogmbh/osrm-backend | third_party/variant/test/t/unary_visitor.cpp | C++ | bsd-2-clause | 3,628 |
using LightBDD.Framework;
using LightBDD.Framework.Extensibility;
namespace LightBDD.Fixie2
{
/// <summary>
/// Base class for feature tests with Fixie framework.
/// It offers <see cref="Runner"/> property allowing to execute scenarios belonging to the feature class.
/// </summary>
[FeatureFixture]
public class FeatureFixture
{
/// <summary>
/// Returns <see cref="IBddRunner"/> allowing to execute scenarios belonging to the feature class.
/// </summary>
protected IBddRunner Runner { get; }
/// <summary>
/// Constructor initializing <see cref="Runner"/> for feature class instance.
/// </summary>
protected FeatureFixture()
{
Runner = FeatureRunnerProvider.GetRunnerFor(GetType()).GetBddRunner(this);
}
}
} | Suremaker/LightBDD | src/LightBDD.Fixie2/FeatureFixture.cs | C# | bsd-2-clause | 841 |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAPI;
namespace XenAdmin.Actions
{
/// <summary>
/// An action which just runs a delegate.
/// It is bad style to use this for more than the very simplest delegate: preferably just a single API call.
/// Anything more complicated should be turned into a proper action of its own.
/// </summary>
public class DelegatedAsyncAction : AsyncAction
{
private readonly Action<Session> invoker;
private readonly string endDescription;
public DelegatedAsyncAction(IXenConnection connection, string title, string startDescription, string endDescription,
Action<Session> invoker, params string[] rbacMethods)
: this(connection, title, startDescription, endDescription, invoker, false, rbacMethods)
{
}
public DelegatedAsyncAction(IXenConnection connection, string title, string startDescription, string endDescription,
Action<Session> invoker, bool suppressHistory, params string[] rbacMethods)
: base(connection, title, startDescription, suppressHistory)
{
this.endDescription = endDescription;
this.invoker = invoker;
ApiMethodsToRoleCheck = new RbacMethodList(rbacMethods);
}
protected override void Run()
{
if (invoker != null)
invoker(Session);
Description = endDescription;
}
}
}
| kc284/xenadmin | XenModel/Actions/DelegatedAsyncAction.cs | C# | bsd-2-clause | 2,997 |
package org.mozartoz.truffle.nodes.builtins;
import static org.mozartoz.truffle.nodes.builtins.Builtin.ALL;
import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.runtime.OzVar;
import org.mozartoz.truffle.runtime.PropertyRegistry;
import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.NodeChildren;
import com.oracle.truffle.api.dsl.Specialization;
public abstract class PropertyBuiltins {
private static final PropertyRegistry REGISTRY = PropertyRegistry.INSTANCE;
@Builtin(proc = true, deref = ALL)
@GenerateNodeFactory
@NodeChildren({ @NodeChild("property"), @NodeChild("value") })
public static abstract class RegisterValueNode extends OzNode {
@Specialization
Object registerValue(String property, Object value) {
REGISTRY.registerValue(property, value);
return unit;
}
}
@Builtin(proc = true, deref = ALL)
@GenerateNodeFactory
@NodeChildren({ @NodeChild("property"), @NodeChild("value") })
public static abstract class RegisterConstantNode extends OzNode {
@Specialization
Object registerConstant(String property, Object value) {
REGISTRY.registerConstant(property, value);
return unit;
}
}
@Builtin(deref = 1)
@GenerateNodeFactory
@NodeChildren({ @NodeChild("property"), @NodeChild("result") })
public static abstract class GetNode extends OzNode {
@Specialization
boolean get(String property, OzVar result) {
Object value = REGISTRY.get(property);
if (value != null) {
result.bind(value);
return true;
} else {
result.bind(unit);
return false;
}
}
}
@Builtin(deref = ALL)
@GenerateNodeFactory
@NodeChildren({ @NodeChild("property"), @NodeChild("value") })
public static abstract class PutNode extends OzNode {
@Specialization
boolean put(String property, Object value) {
if (REGISTRY.containsKey(property)) {
REGISTRY.put(property, value);
return true;
} else {
return false;
}
}
}
}
| eregon/mozart-graal | vm/src/org/mozartoz/truffle/nodes/builtins/PropertyBuiltins.java | Java | bsd-2-clause | 2,012 |
# doc-export: Icons2
"""
This example demonstrates the use of icons in Flexx.
When run as a script, Icons1 is used, passing icon and title to the application.
In the examples section of the docs, Icons2 is used, which sets icon and title
in the init(). Click "open in new tab" to see the effect.
"""
import os
import flexx
from flexx import flx
# todo: support icons in widgets like Button, TabWidget, etc.
# todo: support fontawesome icons
fname = os.path.join(os.path.dirname(flexx.__file__), 'resources', 'flexx.ico')
black_png = ('data:image/png;base64,'
'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAIUlEQVR42mNgY'
'GD4TyEeTAacOHGCKDxqwKgBtDVgaGYmAD/v6XAYiQl7AAAAAElFTkSuQmCC')
class Icons1(flx.Widget):
def init(self):
flx.Button(text='Not much to see here ...')
class Icons2(flx.Widget):
def init(self):
self.set_title('Icon demo')
self.set_icon(black_png)
flx.Button(text='Not much to see here ...')
if __name__ == '__main__':
# Select application icon. Can be a url, a relative url to a shared asset,
# a base64 encoded image, or a local filename. Note that the local filename
# works for setting the aplication icon in a desktop-like app, but not for
# a web app. File types can be ico or png.
# << Uncomment any of the lines below >>
# icon = None # use default
# icon = 'https://assets-cdn.github.com/favicon.ico'
# icon = flx.assets.add_shared_data('ico.icon', open(fname, 'rb').read())
icon = black_png
# icon = fname
m = flx.App(Icons1, title='Icon demo', icon=icon).launch('app')
flx.start()
| zoofIO/flexx | flexxamples/howtos/icons.py | Python | bsd-2-clause | 1,647 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from apiclient import errors
from base import GDBase
import logging
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
from pprint import pprint
from auth import GDAuth
permission_resource_properties = {
"role": ["owner", "reader", "writer"],
"type": ["user", "group", "domain", "anyone"]}
help_permission_text = [(j + ": " + ', '.join(permission_resource_properties[j]))
for j in permission_resource_properties.keys()]
class GDPerm:
def __init__(self, file_id, action):
# base
auth = GDAuth()
creds = auth.get_credentials()
if creds is None:
raise Exception("Failed to retrieve credentials")
self.http = auth.get_authorized_http()
base = GDBase()
self.service = base.get_drive_service(self.http)
self.root = base.get_root()
self.file_id = base.get_id_from_url(file_id)
self.action = action['name']
self.param = action['param']
def run(self):
try:
result = getattr(self, self.action)()
except Exception as e:
logger.error(e)
raise
return result
def insert(self):
new_permission = {
'type': self.param[0],
'role': self.param[1],
'value': self.param[2],
}
try:
return self.service.permissions().insert(
fileId=self.file_id, body=new_permission).execute()
except errors.HttpError as error:
logger.error('An error occurred: %s' % error)
return None
def update(self):
new_permission = {
'type': self.param[1],
'role': self.param[2],
'value': self.param[3],
}
try:
return self.service.permissions().update(
fileId=self.file_id,
permissionId=self.param[0],
body=new_permission).execute()
except errors.HttpError as error:
logger.error('An error occurred: %s' % error)
return None
def list(self):
try:
permissions = self.service.permissions().list(fileId=self.file_id).execute()
logger.debug(permissions)
return permissions.get('items', [])
except errors.HttpError as error:
logger.error('An error occurred: %s' % error)
return None
def get(self):
try:
permissions = self.service.permissions().get(
fileId=self.file_id, permissionId=self.param).execute()
return permissions
except errors.HttpError as error:
logger.error('An error occurred: %s' % error)
return None
def delete(self):
try:
permissions = self.service.permissions().delete(
fileId=self.file_id, permissionId=self.param).execute()
return permissions
except errors.HttpError as error:
logger.error('An error occurred: %s' % error)
return None
def get_by_user(self):
permissions = self.list()
user_email = self.param.lower()
for p in permissions:
if "emailAddress" in p:
perm_email = p["emailAddress"].lower()
if user_email == perm_email:
return p
return None
| tienfuc/gdcmdtools | gdcmdtools/perm.py | Python | bsd-2-clause | 3,399 |
(function($) {
$.fn.extend({
'events': function() {
return this.filter('.event');
},
'highlight': function() {
return this.events()
.removeClass('dimmed')
.addClass('highlighted');
},
'dim': function() {
return this.events()
.removeClass('highlighted')
.addClass('dimmed');
},
'removeDimHighlight': function() {
return this.events()
.removeClass('dimmed highlighted')
},
'byTag': function(tag) {
return this.events()
.find('.tag:contains(' + tag + ')')
.parents('.event')
}
});
})(jQuery);
function highlight_events_by_score() {
function color(score) {
// score 1 -> rosso (l=50%)
// score 0 -> bianco (l=100%)
var x = 100 - (score * 50);
return "hsla(0, 100%, " + x + "%, 1)";
}
$('.event').each(function() {
var e = $(this);
var score = e.attr('data-score');
if(typeof(score) == "undefined") {
e.css('background', null);
}
else {
e.css('background', color(score));
}
})
}
function highlight_events_by_seats() {
function color(score) {
// score 1 -> blu (l=50%)
// score 0 -> bianco (l=100%)
var x = 100 - (score * 50);
return "hsla(240, 100%, " + x + "%, 1)";
}
$('.event').each(function() {
var e = $(this);
var score = e.attr('data-seats');
if(typeof(score) == "undefined") {
e.css('background', null);
}
else {
e.css('background', color(score));
}
})
}
function highlight_chart() {
var slices = {};
var srex = /time-(\d+)/;
$('.event').dim()
$('.track')
.each(function() {
var track = $(this);
var sch = track.parents('.schedule').attr('id');
if(!(sch in slices)) {
var sslices = {};
slices[sch] = sslices;
}
else {
var sslices = slices[sch];
}
track.children('.event[data-talk]')
.each(function() {
var start = parseInt(this.className.match(srex)[1]);
if(!(start in sslices)) {
sslices[start] = [];
}
sslices[start].push($(this));
});
})
$.each(slices, function(schedule, subslice) {
$.each(subslice, function(key, events) {
var kvotes = [];
for(var ix=0; ix<events.length; ix++) {
var tid = events[ix].attr('data-talk');
kvotes.push([ user.votes[tid] || 0, events[ix] ]);
}
kvotes.sort(function(a,b) { return a[0] - b[0]; }).reverse();
var max = kvotes[0][0];
if(max > 5) {
for(var ix=0; ix<kvotes.length; ix++) {
var vote = kvotes[ix][0];
if(vote == max) {
kvotes[ix][1].highlight();
}
}
}
});
});
}
function highlight_tag(tag) {
if(!$.isArray(tag))
tag = [ tag ];
var events = $('.event');
if(!tag.length) {
events.removeDimHighlight();
}
else {
events.dim();
for(var ix=0, ex=tag.length; ix<ex; ix++) {
events.byTag(tag[ix]).removeDimHighlight();
}
if(tag.length == 1) {
var positions = [];
events.byTag(tag[0]).each(function() {
positions.push($(this).offset().top);
});
positions.sort();
window.scroll(0, positions[0]);
}
}
}
function highlighter(mode, option) {
mode = mode || '';
option = option || '';
var hstatus = $(document).data('highlighter') || ['', []];
var remove = false;
if(hstatus[0] != mode) {
$('.event').removeDimHighlight();
hstatus[1] = [];
}
else if(hstatus[1].indexOf(option) != -1) {
remove = true;
}
switch(mode) {
case 'chart':
if(remove) {
$('.event').removeDimHighlight();
}
else {
highlight_chart();
}
break;
case 'tag':
var tags = hstatus[1];
if(remove) {
var ix = tags.indexOf(option);
tags.splice(ix, 1);
}
else {
tags = tags.concat([ option ]);
}
highlight_tag(tags);
break;
default:
mode = '';
option = null;
$('.event').removeDimHighlight();
}
hstatus[0] = mode;
if(option == null) {
hstatus[1] = [];
}
else {
var ix = hstatus[1].indexOf(option);
if(remove && ix != -1) {
hstatus[1].splice(ix, 1);
}
else if(!remove && ix == -1) {
hstatus[1].push(option);
}
}
$(document)
.data('highlighter', hstatus)
.trigger('highlighter', hstatus);
}
(function() {
var nav = $('#schedule-navigator');
var options = nav.children('div');
options
.find('.disabled')
.bind('click', function(ev) { ev.stopImmediatePropagation(); return false;})
.end()
.children('a')
.bind('click', function(ev) {
var e = $(this);
var target = e.parent().children('div');
var visible = !target.is(':hidden');
options
.removeClass('selected')
.children('div')
.hide();
if(!visible)
target
.show()
.parent()
.addClass('selected');
return false;
})
.end()
.children('div')
.prepend('' +
'<div class="close">' +
' <a href="#"><img src="' + STATIC_URL + 'p5/images/close.png" width="24" /></a>' +
'</div>')
.find('.close')
.bind('click', function(ev) {
$(this)
.parent().hide()
.parent().removeClass('selected');
return false;
})
options
.find('.track-toggle')
.bind('click', function(ev) {
var e = $(this);
var tracks = $([]);
$(e.attr('data-tracks').split(',')).each(function(ix, val) {
tracks = tracks.add($('.track[data-track=' + val + ']'));
})
var visible = tracks.is(':hidden');
/*
* nascondere/mostrare le track è semplice, il problema è
* accorciare gli eventi a sale unificate
*/
if(visible) {
tracks.show();
e.removeClass('filter-active');
}
else {
tracks.hide();
e.addClass('filter-active');
}
var sch = tracks.eq(0).parents('.schedule');
var direction = sch.parent().get(0).className.indexOf('vertical') != -1 ? 'v' : 'h';
var offset = direction == 'v' ? tracks.width() : tracks.height();
if(!visible)
offset *= -1;
/*
* devo accumulare le modifiche invece che applicarle
* subito perché c'è una transizione css e i metodi
* .width/.height non mi riportano la dimensione
* corretta fino a quando non è terminata l'animazione
*/
var sizes = {};
tracks.each(function() {
var t = $(this)
/*
* gli eventi da manipolare sono tutti quelli presenti
* nelle track precedenti che coinvolgano anche la track corrente
*/
var previous = t.prevAll('.track');
previous
.each(function(tix, val) {
/*
* mi interessano solo gli elementi di questa track
* che vanno a toccare una delle track manipolate
*/
$(this)
.children('.event')
.not('.tracks-1')
.filter(function(ix) {
var match = this.className.match(/tracks-(\d)/);
if(!match)
return false;
return parseInt(match[1]) + (previous.length - tix -1) > previous.length;
})
.each(function() {
var evt = $(this);
if(!(this.id in sizes))
sizes[this.id] = direction == 'v' ? evt.outerWidth() : evt.outerHeight();
sizes[this.id] += offset;
});
});
});
for(var key in sizes) {
if(direction == 'v')
$(document.getElementById(key)).width(sizes[key]);
else
$(document.getElementById(key)).height(sizes[key]);
}
return false;
})
.end()
.find('.highlights li > a')
.click(function(ev) {
$(this)
.parents('.highlights')
.find('li > div')
.hide()
})
.end()
.find('.highlight-chart')
.each(function(ix, val) {
if($.isEmptyObject(user.votes)) {
$(this)
.addClass('disabled')
.after(' <a href="#" title="You have not participated to the community vote">?</a>');
}
else {
$(this).bind('click', function(ev) {
highlighter('chart');
return false;
})
}
})
.end()
.find('.highlight-tag')
.click(function(ev) {
$(this).next().toggle();
return false;
})
.end()
.find('.tag-list a.tag')
.click(function(ev) {
var tag = $(this).attr('data-tag');
highlighter('tag', tag);
return false;
})
.end()
.find('.highlight-remove')
.click(function(ev) {
highlighter();
return false;
})
.end()
$(document)
.bind('highlighter', function(ev, mode, moptions) {
var h = options.find('.highlight-chart');
if(mode == "chart") {
h.addClass('highlight-active');
}
else {
h.removeClass('highlight-active');
}
h = options.find('.highlight-tag')
tags = options.find('.tag-list .tag');
tags.removeClass('selected');
if(mode == "tag") {
h.addClass('highlight-active');
for(var ix=0, ex=moptions.length; ix<ex; ix++) {
tags.filter('[data-tag=' + moptions[ix] + ']').addClass('selected');
}
}
else {
h.removeClass('highlight-active');
}
});
})();
(function() {
var user_interest_toolbar = '' +
' <div class="talk-interest">' +
' <a class="up" href="#" />' +
' </div>' +
'';
var EVENT_WIDTH_EXPOSED = 400;
function expose(e) {
var schedule = e.parents('.schedule__body');
var track = e.parent();
var offset = track.position().left + EVENT_WIDTH_EXPOSED - schedule.width();
e.addClass('exposed');
if (offset > 0) {
e.css('margin-left', -offset + 'px');
}
e.trigger('exposed');
}
function unexpose(e) {
e.removeClass('exposed');
e.css('margin-left', 0);
}
function event_url(base, evt) {
var sch = evt.parents('.schedule');
return base
.replace('0', evt.attr('data-id'))
.replace('_S_', sch.attr('id'))
.replace('_C_', sch.parent().attr('data-conference'));
}
function update_booking_status(evt) {
var be = $('<div class="book-event maximized">loading...</div>');
$('.book-event', evt).remove();
$('.tools', evt).append(be);
/* i training sono prenotabili solo da chi ha acquisitato un biglietto
* standard o daily; il server impone il vincolo ma replico la logica
* per poter dare un feedback immediato.
*/
var full = false;
var training = evt.parents('.track[data-track=training1], .track[data-track=training2]').length > 0;
for(var ix=0; ix<user.tickets.length; ix++) {
var t = user.tickets[ix];
if(t[1] == 'conference' && ((t[2].substr(2, 1) == 'S' || t[2].substr(2, 1) == 'D') || !training)) {
full = true;
break;
}
}
if(!full) {
be.html('<div class="restricted"><a href="/training">Restricted access</a></div>');
return;
}
var base = "/conference/schedule/_C_/_S_/0/booking";
$.get(event_url(base, evt), function(data) {
if(data.user) {
be.html('<div class="cancel"><a href="#">Cancel booking</a></div>');
}
else {
if(data.available) {
be.html('<div class="book"><a href="#">Book this event</a></div>');
}
else {
be.html('<div class="sold-out">Sold out</div>');
}
}
sync_event_book_status(evt, data);
}, 'json');
}
function sync_event_book_status(evt, value) {
evt.find('.info').remove();
if(value.user) {
evt.append('<div class="info booked minimized">BOOKED</div>');
}
else {
if(value.available > 0) {
var training = evt.parents('.track[data-track=training1], .track[data-track=training2]').length > 0;
if(training) {
var msg = 'BOOK IT<br /><span title="Are you still doing the math instead of booking? Only ' + value.available + ' seats are availables; book your seat now!">0<span>x</span>' + value.available.toString(16) + '</span> LEFT';
}
else {
var msg = 'BOOK IT, ' + value.available + ' LEFT';
}
evt.append(''
+ '<div class="info available minimized">'
+ msg
+ '</div>');
}
else {
evt.append('<div class="info sold-out minimized">SOLDOUT</div>');
}
}
}
// eseguo la richiesthe ajax prima della manipolazione del DOM, in questo
// modo le due operazioni dovrebbero procedere parallelamente.
(function() {
var conf = document.location.pathname.split('/')[3];
$.getJSON('/conference/schedule/' + conf + '/events/booking', function(data) {
$.each(data, function(key, value) {
sync_event_book_status($('#e' + key), value);
});
});
})();
(function() {
var conf = document.location.pathname.split('/')[3];
$.getJSON('/conference/schedule/' + conf + '/events/expected_attendance', function(data) {
$.each(data, function(eid, data) {
var e = $('#e' + eid);
e.attr('data-score', data.score_normalized);
var seats_normalized = data.expected / data.seats;
if(seats_normalized > 1)
seats_normalized = 1
e.attr('data-seats', seats_normalized);
e.attr('data-raw-seats', data.seats);
e.attr('data-raw-expected', data.expected);
if(data.overbook) {
var track = e.parents('.track').attr('data-track');
if(track != 'helpdesk1' && track != 'helpdesk2'
&& track != 'training1' && track != 'training2'
&& !e.hasClass('keynote')) {
e.addClass('overbooked');
e.append('<div class="warning overbook">'
+'<img src="' + STATIC_URL + 'p7/images/warning.png" title="our estimate of attendance exceeds the room size" />'
+'</div>');
}
}
});
});
})();
$('.event.bookable')
.bind('exposed', function(ev) {
update_booking_status($(this));
return false;
});
$('.book-event a').live('click', function(ev) {
var b = $(this).parent();
var base = "/conference/schedule/_C_/_S_/0/booking";
var evt = b.parents('.event');
var url = event_url(base, evt);
if(b.hasClass('book')) {
if(confirm('You are booking a seat in this training. You can cancel your booking at any time if you change your mind, to leave your seat available for someone else.')) {
$.ajax({
url: url,
type: 'POST',
data: {
value: 1
},
success: function() {
update_booking_status(evt);
},
error: function(xhr, status, error_) {
var msg = 'Cannot proceed';
switch(xhr.responseText) {
case 'sold out':
msg = 'Training full';
break;
case 'time conflict':
msg = 'Another training booked in this time slot';
break;
case 'ticket error':
msg = 'Restricted access';
break;
case 'already booked':
msg = 'You already have another reservation for this type of event';
break;
}
alert(msg);
}
});
}
}
else if(b.hasClass('cancel')) {
if(confirm('Are you sure to cancel your reservation?')) {
$.ajax({
url: url,
type: 'POST',
data: {},
success: function() {
update_booking_status(evt);
}
});
}
}
else {
return true;
}
return false;
});
$('.event')
.filter(function(ix) {
// escludo gli elementi "strutturali", non devo interagirci
var e = $(this);
return !e.hasClass('special') && !e.hasClass('break');
})
.filter(function() { return !!$(this).attr('data-talk') || $('.abstract', this).length; })
.prepend('' +
'<div class="maximized close-event">' +
' <a href="#"><img src="' + STATIC_URL + 'p5/images/close.png" width="24" /></a>' +
'</div>')
.bind('click', function(ev) {
var e = $(this);
if(e.hasClass('exposed'))
return;
$('.exposed')
.not(e)
.each(function() { unexpose($(this)) });
expose(e);
})
.find('a')
.bind('click', function(ev) {
/*
* non voglio seguire i link su un evento collassato
*/
var evt = $(this).parents('.event');
if(!evt.hasClass('exposed'))
ev.preventDefault();
return true;
})
.end()
.find('.close-event a')
.bind('click', function(ev) {
unexpose($(this).parents('.event'));
return false;
})
.end()
.bind('exposed', function(ev) {
var e = $(this);
/* se ho aperto un evento che non è collegato ad un talk
* significa che tutti i dati da mostrare sono già presenti
* nell'html.
*/
if(!e.attr('data-talk')) {
return;
}
if(!e.data('loaded')) {
var talk = $('h3.name a', e).attr('href');
if(talk) {
var ab = $('.abstract', e)
.text('loading...');
$.ajax({
url: talk + '.xml',
dataType: 'xml',
success: function(data, text, xhr) {
ab.html($('talk abstract', data).html());
}
});
}
e.data('loaded', 1);
}
})
.end()
.each(function(ix, val) {
var e = $(this);
var tools = e.find('.tools');
if(user.authenticated) {
var tid = e.attr('data-talk');
if(tid && tid in user.votes) {
tools.append('<div class="maximized talk-vote">' + user.votes[tid] + '/10</div>');
}
/*
* gli eventi del partner program sono "virtuali" non esistano
* nel db e hanno un id < 0
*/
if(e.attr('data-id') > 0) {
if(!e.hasClass('bookable')) {
var i = user.interest[e.attr('data-id')];
if(i == 1) {
e.addClass('interest-up');
}
else if(i == -1) {
e.addClass('interest-down');
}
tools.append(user_interest_toolbar);
if(i == 1) {
tools.find('a.up').addClass('active');
}
else if(i == -1) {
tools.find('a.down').addClass('active');
}
}
}
}
var t0 = Date.now();
/*
* aggiunta elisione
*/
var name = e.find('.name a');
if(name.length) {
// numero di linee visibili
var lh = parseFloat(name.css('line-height'));
var lines = Math.floor((e.height() - name.position().top) / lh);
// nuova altezza del tag a
var h = lines * lh;
if(h < name.height()) {
name.truncateText(h);
}
}
})
.find('.toggle-notice')
.bind('click', function(ev) {
$(this)
.parents('.event')
.children('.notice')
.css('left', 0)
return false;
})
.end()
.find('.notice')
.bind('click', function(ev) {
/* over the top! 100% non è abbastanza per chrome! */
$(this).css('left', '110%');
return false;
})
.end()
.find('.talk-interest a')
.bind('click', function(ev) {
var base = "/conference/schedule/_C_/_S_/0/interest"
var e = $(this);
var evt = e.parents('.event');
var url = event_url(base, evt);
var up = e.hasClass('up');
if(!e.hasClass('active')) {
var val = up ? 1 : -1;
}
else {
var val = 0;
}
$.ajax({
url: url,
type: 'POST',
data: {
interest: val
},
success: function() {
evt.removeClass('interest-up interest-down');
var wrap = e.parents('.talk-interest');
$('a', wrap).removeClass('active');
if(val > 0) {
$('a.up', wrap).addClass('active');
evt.addClass('interest-up');
}
else if(val < 0) {
$('a.down', wrap).addClass('active');
evt.addClass('interest-down');
}
}
});
return false;
})
.end()
.find('.tag')
.bind('click', function(ev) {
$('.event')
.removeDimHighlight()
.byTag($(this).text())
.highlight();
return false;
})
.end()
/*
* Eventi sovrapposti; non riesco a stilare in maniera oppurtuna gli eventi
* sovrapposti usando solo selettori CSS. questo pezzetto di js mi serve
* per assegnare le classi corrette agli eventi
*
* Divido gli eventi in classi di intersezione (gli eventi che si
* intersecano due alla volta, tre alla volta, etc); ad ogni evento associa
* una classe "left-intersection-X" con X che va da 0 al numero di elementi
* nella gruppo di intersezione.
*/
$('.track[data-track=partner0]').each(function() {
var events = {};
$('.event[data-intersection]', this).each(function() {
var group = $(this).attr('data-intersection');
var start = this.className.match(/time-(\d+)/)[1];
if(group in events) {
events[group].push([start, this]);
}
else {
events[group] = [[start, this]];
}
});
$.each(events, function(group, events) {
events.sort(function(a,b) {
var a = Number(a[0]);
var b = Number(b[0]);
return a == b ? 0 : (a < b ? -1 : 1);
});
group = Number(group.substr(1)) + 1;
$.each(events, function(ix, el) {
$(el).addClass('left-intersection-' + (ix % group));
});
});
var tickets = {};
for(var ix=0, ex=user.tickets.length; ix<ex; ix++) {
tickets[user.tickets[ix][2]] = 1;
}
$('.event', this).each(function() {
var e = $(this);
var fcode = e.attr('data-fare');
var sbar = e.find('.status-bar');
if(fcode in tickets) {
sbar.append('<div class="info">You have bought a ticket for this event</div>');
e.addClass('booked');
}
else {
sbar.append('<div class="info"><a href="/p3/cart/?f=' + fcode + '">Buy a ticket</a></div>');
}
});
});
$('.special > *:first-child').verticalAlign();
$('.break > *:first-child').verticalAlign();
$('.poster ul a').truncateText();
})();
| leriomaggio/pycon_site | p3/static/p7/javascripts/schedule.js | JavaScript | bsd-2-clause | 28,339 |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Security.Cryptography.X509Certificates;
using XenAdmin.Core;
using XenAdmin.Network;
namespace XenAdmin.Dialogs.Network
{
public partial class CertificateChangedDialog : XenDialogBase
{
private X509Certificate2 _newCertificate;
private string _hostname;
public CertificateChangedDialog(X509Certificate certificate, string hostname)
{
InitializeComponent();
AlwaysIgnoreCheckBox.Enabled = Registry.SSLCertificateTypes == SSLCertificateTypes.None;
_newCertificate = new X509Certificate2(certificate);
_hostname = hostname;
string h = _hostname.Ellipsise(35);
labelTrusted.Text = string.Format(labelTrusted.Text, h,
_newCertificate.VerifyInAllStores() ? Messages.TRUSTED : Messages.NOT_TRUSTED);
BlurbLabel.Text = string.Format(BlurbLabel.Text, h);
Blurb2Label.Text = string.Format(Blurb2Label.Text, h);
}
private void ViewCertificateButton_Click(object sender, EventArgs e)
{
X509Certificate2UI.DisplayCertificate(_newCertificate, Handle);
}
private void Okbutton_Click(object sender, EventArgs e)
{
Settings.ReplaceCertificate(_hostname, _newCertificate.GetCertHashString());
if (AlwaysIgnoreCheckBox.Enabled && AlwaysIgnoreCheckBox.Checked)
{
Properties.Settings.Default.WarnChangedCertificate = false;
Settings.TrySaveSettings();
}
}
}
} | xenserver/xenadmin | XenAdmin/Dialogs/Network/CertificateChangedDialog.cs | C# | bsd-2-clause | 3,087 |
/*
* Alert Message
* (C) 2004-2006,2011 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/tls_alert.h>
#include <botan/exceptn.h>
namespace Botan {
namespace TLS {
Alert::Alert(const secure_vector<uint8_t>& buf)
{
if(buf.size() != 2)
throw Decoding_Error("Alert: Bad size " + std::to_string(buf.size()) +
" for alert message");
if(buf[0] == 1) m_fatal = false;
else if(buf[0] == 2) m_fatal = true;
else
throw Decoding_Error("Alert: Bad code for alert level");
const uint8_t dc = buf[1];
m_type_code = static_cast<Type>(dc);
}
std::vector<uint8_t> Alert::serialize() const
{
return std::vector<uint8_t>({
static_cast<uint8_t>(is_fatal() ? 2 : 1),
static_cast<uint8_t>(type())
});
}
std::string Alert::type_string() const
{
switch(type())
{
case CLOSE_NOTIFY:
return "close_notify";
case UNEXPECTED_MESSAGE:
return "unexpected_message";
case BAD_RECORD_MAC:
return "bad_record_mac";
case DECRYPTION_FAILED:
return "decryption_failed";
case RECORD_OVERFLOW:
return "record_overflow";
case DECOMPRESSION_FAILURE:
return "decompression_failure";
case HANDSHAKE_FAILURE:
return "handshake_failure";
case NO_CERTIFICATE:
return "no_certificate";
case BAD_CERTIFICATE:
return "bad_certificate";
case UNSUPPORTED_CERTIFICATE:
return "unsupported_certificate";
case CERTIFICATE_REVOKED:
return "certificate_revoked";
case CERTIFICATE_EXPIRED:
return "certificate_expired";
case CERTIFICATE_UNKNOWN:
return "certificate_unknown";
case ILLEGAL_PARAMETER:
return "illegal_parameter";
case UNKNOWN_CA:
return "unknown_ca";
case ACCESS_DENIED:
return "access_denied";
case DECODE_ERROR:
return "decode_error";
case DECRYPT_ERROR:
return "decrypt_error";
case EXPORT_RESTRICTION:
return "export_restriction";
case PROTOCOL_VERSION:
return "protocol_version";
case INSUFFICIENT_SECURITY:
return "insufficient_security";
case INTERNAL_ERROR:
return "internal_error";
case INAPPROPRIATE_FALLBACK:
return "inappropriate_fallback";
case USER_CANCELED:
return "user_canceled";
case NO_RENEGOTIATION:
return "no_renegotiation";
case UNSUPPORTED_EXTENSION:
return "unsupported_extension";
case CERTIFICATE_UNOBTAINABLE:
return "certificate_unobtainable";
case UNRECOGNIZED_NAME:
return "unrecognized_name";
case BAD_CERTIFICATE_STATUS_RESPONSE:
return "bad_certificate_status_response";
case BAD_CERTIFICATE_HASH_VALUE:
return "bad_certificate_hash_value";
case UNKNOWN_PSK_IDENTITY:
return "unknown_psk_identity";
case NO_APPLICATION_PROTOCOL:
return "no_application_protocol";
case NULL_ALERT:
return "none";
}
/*
* This is effectively the default case for the switch above, but we
* leave it out so that when an alert type is added to the enum the
* compiler can warn us that it is not included in the switch
* statement.
*/
return "unrecognized_alert_" + std::to_string(type());
}
}
}
| Rohde-Schwarz-Cybersecurity/botan | src/lib/tls/tls_alert.cpp | C++ | bsd-2-clause | 3,464 |
package com.atlassian.jira.plugins.dvcs.webwork;
import com.atlassian.jira.compatibility.util.ApplicationUserUtil;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import java.util.Map;
public class DvcsPanelCondition implements Condition
{
private final PanelVisibilityManager panelVisibilityManager;
public DvcsPanelCondition(PanelVisibilityManager panelVisibilityManager)
{
this.panelVisibilityManager = panelVisibilityManager;
}
@Override
public void init(Map<String, String> params) throws PluginParseException
{
}
@Override
public boolean shouldDisplay(Map<String, Object> context)
{
ApplicationUser user = ApplicationUserUtil.from(context.get("user"));
Issue issue = (Issue) context.get("issue");
return panelVisibilityManager.showPanel(issue, user);
}
}
| markphip/testing | jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/webwork/DvcsPanelCondition.java | Java | bsd-2-clause | 1,011 |
from functools import partial
from collections import deque
from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core import types, cgutils
from numba.np import numpy_support
class DataModel(object):
"""
DataModel describe how a FE type is represented in the LLVM IR at
different contexts.
Contexts are:
- value: representation inside function body. Maybe stored in stack.
The representation here are flexible.
- data: representation used when storing into containers (e.g. arrays).
- argument: representation used for function argument. All composite
types are unflattened into multiple primitive types.
- return: representation used for return argument.
Throughput the compiler pipeline, a LLVM value is usually passed around
in the "value" representation. All "as_" prefix function converts from
"value" representation. All "from_" prefix function converts to the
"value" representation.
"""
def __init__(self, dmm, fe_type):
self._dmm = dmm
self._fe_type = fe_type
@property
def fe_type(self):
return self._fe_type
def get_value_type(self):
raise NotImplementedError(self)
def get_data_type(self):
return self.get_value_type()
def get_argument_type(self):
"""Return a LLVM type or nested tuple of LLVM type
"""
return self.get_value_type()
def get_return_type(self):
return self.get_value_type()
def as_data(self, builder, value):
raise NotImplementedError(self)
def as_argument(self, builder, value):
"""
Takes one LLVM value
Return a LLVM value or nested tuple of LLVM value
"""
raise NotImplementedError(self)
def as_return(self, builder, value):
raise NotImplementedError(self)
def from_data(self, builder, value):
raise NotImplementedError(self)
def from_argument(self, builder, value):
"""
Takes a LLVM value or nested tuple of LLVM value
Returns one LLVM value
"""
raise NotImplementedError(self)
def from_return(self, builder, value):
raise NotImplementedError(self)
def load_from_data_pointer(self, builder, ptr, align=None):
"""
Load value from a pointer to data.
This is the default implementation, sufficient for most purposes.
"""
return self.from_data(builder, builder.load(ptr, align=align))
def traverse(self, builder):
"""
Traverse contained members.
Returns a iterable of contained (types, getters).
Each getter is a one-argument function accepting a LLVM value.
"""
return []
def traverse_models(self):
"""
Recursively list all models involved in this model.
"""
return [self._dmm[t] for t in self.traverse_types()]
def traverse_types(self):
"""
Recursively list all frontend types involved in this model.
"""
types = [self._fe_type]
queue = deque([self])
while len(queue) > 0:
dm = queue.popleft()
for i_dm in dm.inner_models():
if i_dm._fe_type not in types:
queue.append(i_dm)
types.append(i_dm._fe_type)
return types
def inner_models(self):
"""
List all *inner* models.
"""
return []
def get_nrt_meminfo(self, builder, value):
"""
Returns the MemInfo object or None if it is not tracked.
It is only defined for types.meminfo_pointer
"""
return None
def has_nrt_meminfo(self):
return False
def contains_nrt_meminfo(self):
"""
Recursively check all contained types for need for NRT meminfo.
"""
return any(model.has_nrt_meminfo() for model in self.traverse_models())
def _compared_fields(self):
return (type(self), self._fe_type)
def __hash__(self):
return hash(tuple(self._compared_fields()))
def __eq__(self, other):
if type(self) is type(other):
return self._compared_fields() == other._compared_fields()
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
@register_default(types.Omitted)
class OmittedArgDataModel(DataModel):
"""
A data model for omitted arguments. Only the "argument" representation
is defined, other representations raise a NotImplementedError.
"""
# Omitted arguments are using a dummy value type
def get_value_type(self):
return ir.LiteralStructType([])
# Omitted arguments don't produce any LLVM function argument.
def get_argument_type(self):
return ()
def as_argument(self, builder, val):
return ()
def from_argument(self, builder, val):
assert val == (), val
return None
@register_default(types.Boolean)
@register_default(types.BooleanLiteral)
class BooleanModel(DataModel):
_bit_type = ir.IntType(1)
_byte_type = ir.IntType(8)
def get_value_type(self):
return self._bit_type
def get_data_type(self):
return self._byte_type
def get_return_type(self):
return self.get_data_type()
def get_argument_type(self):
return self.get_data_type()
def as_data(self, builder, value):
return builder.zext(value, self.get_data_type())
def as_argument(self, builder, value):
return self.as_data(builder, value)
def as_return(self, builder, value):
return self.as_data(builder, value)
def from_data(self, builder, value):
ty = self.get_value_type()
resalloca = cgutils.alloca_once(builder, ty)
cond = builder.icmp_unsigned('==', value, value.type(0))
with builder.if_else(cond) as (then, otherwise):
with then:
builder.store(ty(0), resalloca)
with otherwise:
builder.store(ty(1), resalloca)
return builder.load(resalloca)
def from_argument(self, builder, value):
return self.from_data(builder, value)
def from_return(self, builder, value):
return self.from_data(builder, value)
class PrimitiveModel(DataModel):
"""A primitive type can be represented natively in the target in all
usage contexts.
"""
def __init__(self, dmm, fe_type, be_type):
super(PrimitiveModel, self).__init__(dmm, fe_type)
self.be_type = be_type
def get_value_type(self):
return self.be_type
def as_data(self, builder, value):
return value
def as_argument(self, builder, value):
return value
def as_return(self, builder, value):
return value
def from_data(self, builder, value):
return value
def from_argument(self, builder, value):
return value
def from_return(self, builder, value):
return value
class ProxyModel(DataModel):
"""
Helper class for models which delegate to another model.
"""
def get_value_type(self):
return self._proxied_model.get_value_type()
def get_data_type(self):
return self._proxied_model.get_data_type()
def get_return_type(self):
return self._proxied_model.get_return_type()
def get_argument_type(self):
return self._proxied_model.get_argument_type()
def as_data(self, builder, value):
return self._proxied_model.as_data(builder, value)
def as_argument(self, builder, value):
return self._proxied_model.as_argument(builder, value)
def as_return(self, builder, value):
return self._proxied_model.as_return(builder, value)
def from_data(self, builder, value):
return self._proxied_model.from_data(builder, value)
def from_argument(self, builder, value):
return self._proxied_model.from_argument(builder, value)
def from_return(self, builder, value):
return self._proxied_model.from_return(builder, value)
@register_default(types.EnumMember)
@register_default(types.IntEnumMember)
class EnumModel(ProxyModel):
"""
Enum members are represented exactly like their values.
"""
def __init__(self, dmm, fe_type):
super(EnumModel, self).__init__(dmm, fe_type)
self._proxied_model = dmm.lookup(fe_type.dtype)
@register_default(types.Opaque)
@register_default(types.PyObject)
@register_default(types.RawPointer)
@register_default(types.NoneType)
@register_default(types.StringLiteral)
@register_default(types.EllipsisType)
@register_default(types.Function)
@register_default(types.Type)
@register_default(types.Object)
@register_default(types.Module)
@register_default(types.Phantom)
@register_default(types.ContextManager)
@register_default(types.Dispatcher)
@register_default(types.ObjModeDispatcher)
@register_default(types.ExceptionClass)
@register_default(types.Dummy)
@register_default(types.ExceptionInstance)
@register_default(types.ExternalFunction)
@register_default(types.EnumClass)
@register_default(types.IntEnumClass)
@register_default(types.NumberClass)
@register_default(types.TypeRef)
@register_default(types.NamedTupleClass)
@register_default(types.DType)
@register_default(types.RecursiveCall)
@register_default(types.MakeFunctionLiteral)
@register_default(types.Poison)
class OpaqueModel(PrimitiveModel):
"""
Passed as opaque pointers
"""
_ptr_type = ir.IntType(8).as_pointer()
def __init__(self, dmm, fe_type):
be_type = self._ptr_type
super(OpaqueModel, self).__init__(dmm, fe_type, be_type)
@register_default(types.MemInfoPointer)
class MemInfoModel(OpaqueModel):
def inner_models(self):
return [self._dmm.lookup(self._fe_type.dtype)]
def has_nrt_meminfo(self):
return True
def get_nrt_meminfo(self, builder, value):
return value
@register_default(types.Integer)
@register_default(types.IntegerLiteral)
class IntegerModel(PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(fe_type.bitwidth)
super(IntegerModel, self).__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
@register_default(types.CPointer)
class PointerModel(PrimitiveModel):
def __init__(self, dmm, fe_type):
self._pointee_model = dmm.lookup(fe_type.dtype)
self._pointee_be_type = self._pointee_model.get_data_type()
be_type = self._pointee_be_type.as_pointer()
super(PointerModel, self).__init__(dmm, fe_type, be_type)
@register_default(types.EphemeralPointer)
class EphemeralPointerModel(PointerModel):
def get_data_type(self):
return self._pointee_be_type
def as_data(self, builder, value):
value = builder.load(value)
return self._pointee_model.as_data(builder, value)
def from_data(self, builder, value):
raise NotImplementedError("use load_from_data_pointer() instead")
def load_from_data_pointer(self, builder, ptr, align=None):
return builder.bitcast(ptr, self.get_value_type())
@register_default(types.EphemeralArray)
class EphemeralArrayModel(PointerModel):
def __init__(self, dmm, fe_type):
super(EphemeralArrayModel, self).__init__(dmm, fe_type)
self._data_type = ir.ArrayType(self._pointee_be_type,
self._fe_type.count)
def get_data_type(self):
return self._data_type
def as_data(self, builder, value):
values = [builder.load(cgutils.gep_inbounds(builder, value, i))
for i in range(self._fe_type.count)]
return cgutils.pack_array(builder, values)
def from_data(self, builder, value):
raise NotImplementedError("use load_from_data_pointer() instead")
def load_from_data_pointer(self, builder, ptr, align=None):
return builder.bitcast(ptr, self.get_value_type())
@register_default(types.ExternalFunctionPointer)
class ExternalFuncPointerModel(PrimitiveModel):
def __init__(self, dmm, fe_type):
sig = fe_type.sig
# Since the function is non-Numba, there is no adaptation
# of arguments and return value, hence get_value_type().
retty = dmm.lookup(sig.return_type).get_value_type()
args = [dmm.lookup(t).get_value_type() for t in sig.args]
be_type = ir.PointerType(ir.FunctionType(retty, args))
super(ExternalFuncPointerModel, self).__init__(dmm, fe_type, be_type)
@register_default(types.UniTuple)
@register_default(types.NamedUniTuple)
@register_default(types.StarArgUniTuple)
class UniTupleModel(DataModel):
def __init__(self, dmm, fe_type):
super(UniTupleModel, self).__init__(dmm, fe_type)
self._elem_model = dmm.lookup(fe_type.dtype)
self._count = len(fe_type)
self._value_type = ir.ArrayType(self._elem_model.get_value_type(),
self._count)
self._data_type = ir.ArrayType(self._elem_model.get_data_type(),
self._count)
def get_value_type(self):
return self._value_type
def get_data_type(self):
return self._data_type
def get_return_type(self):
return self.get_value_type()
def get_argument_type(self):
return (self._elem_model.get_argument_type(),) * self._count
def as_argument(self, builder, value):
out = []
for i in range(self._count):
v = builder.extract_value(value, [i])
v = self._elem_model.as_argument(builder, v)
out.append(v)
return out
def from_argument(self, builder, value):
out = ir.Constant(self.get_value_type(), ir.Undefined)
for i, v in enumerate(value):
v = self._elem_model.from_argument(builder, v)
out = builder.insert_value(out, v, [i])
return out
def as_data(self, builder, value):
out = ir.Constant(self.get_data_type(), ir.Undefined)
for i in range(self._count):
val = builder.extract_value(value, [i])
dval = self._elem_model.as_data(builder, val)
out = builder.insert_value(out, dval, [i])
return out
def from_data(self, builder, value):
out = ir.Constant(self.get_value_type(), ir.Undefined)
for i in range(self._count):
val = builder.extract_value(value, [i])
dval = self._elem_model.from_data(builder, val)
out = builder.insert_value(out, dval, [i])
return out
def as_return(self, builder, value):
return value
def from_return(self, builder, value):
return value
def traverse(self, builder):
def getter(i, value):
return builder.extract_value(value, i)
return [(self._fe_type.dtype, partial(getter, i))
for i in range(self._count)]
def inner_models(self):
return [self._elem_model]
class CompositeModel(DataModel):
"""Any model that is composed of multiple other models should subclass from
this.
"""
pass
class StructModel(CompositeModel):
_value_type = None
_data_type = None
def __init__(self, dmm, fe_type, members):
super(StructModel, self).__init__(dmm, fe_type)
if members:
self._fields, self._members = zip(*members)
else:
self._fields = self._members = ()
self._models = tuple([self._dmm.lookup(t) for t in self._members])
def get_member_fe_type(self, name):
"""
StructModel-specific: get the Numba type of the field named *name*.
"""
pos = self.get_field_position(name)
return self._members[pos]
def get_value_type(self):
if self._value_type is None:
self._value_type = ir.LiteralStructType([t.get_value_type()
for t in self._models])
return self._value_type
def get_data_type(self):
if self._data_type is None:
self._data_type = ir.LiteralStructType([t.get_data_type()
for t in self._models])
return self._data_type
def get_argument_type(self):
return tuple([t.get_argument_type() for t in self._models])
def get_return_type(self):
return self.get_data_type()
def _as(self, methname, builder, value):
extracted = []
for i, dm in enumerate(self._models):
extracted.append(getattr(dm, methname)(builder,
self.get(builder, value, i)))
return tuple(extracted)
def _from(self, methname, builder, value):
struct = ir.Constant(self.get_value_type(), ir.Undefined)
for i, (dm, val) in enumerate(zip(self._models, value)):
v = getattr(dm, methname)(builder, val)
struct = self.set(builder, struct, v, i)
return struct
def as_data(self, builder, value):
"""
Converts the LLVM struct in `value` into a representation suited for
storing into arrays.
Note
----
Current implementation rarely changes how types are represented for
"value" and "data". This is usually a pointless rebuild of the
immutable LLVM struct value. Luckily, LLVM optimization removes all
redundancy.
Sample usecase: Structures nested with pointers to other structures
that can be serialized into a flat representation when storing into
array.
"""
elems = self._as("as_data", builder, value)
struct = ir.Constant(self.get_data_type(), ir.Undefined)
for i, el in enumerate(elems):
struct = builder.insert_value(struct, el, [i])
return struct
def from_data(self, builder, value):
"""
Convert from "data" representation back into "value" representation.
Usually invoked when loading from array.
See notes in `as_data()`
"""
vals = [builder.extract_value(value, [i])
for i in range(len(self._members))]
return self._from("from_data", builder, vals)
def load_from_data_pointer(self, builder, ptr, align=None):
values = []
for i, model in enumerate(self._models):
elem_ptr = cgutils.gep_inbounds(builder, ptr, 0, i)
val = model.load_from_data_pointer(builder, elem_ptr, align)
values.append(val)
struct = ir.Constant(self.get_value_type(), ir.Undefined)
for i, val in enumerate(values):
struct = self.set(builder, struct, val, i)
return struct
def as_argument(self, builder, value):
return self._as("as_argument", builder, value)
def from_argument(self, builder, value):
return self._from("from_argument", builder, value)
def as_return(self, builder, value):
elems = self._as("as_data", builder, value)
struct = ir.Constant(self.get_data_type(), ir.Undefined)
for i, el in enumerate(elems):
struct = builder.insert_value(struct, el, [i])
return struct
def from_return(self, builder, value):
vals = [builder.extract_value(value, [i])
for i in range(len(self._members))]
return self._from("from_data", builder, vals)
def get(self, builder, val, pos):
"""Get a field at the given position or the fieldname
Args
----
builder:
LLVM IRBuilder
val:
value to be inserted
pos: int or str
field index or field name
Returns
-------
Extracted value
"""
if isinstance(pos, str):
pos = self.get_field_position(pos)
return builder.extract_value(val, [pos],
name="extracted." + self._fields[pos])
def set(self, builder, stval, val, pos):
"""Set a field at the given position or the fieldname
Args
----
builder:
LLVM IRBuilder
stval:
LLVM struct value
val:
value to be inserted
pos: int or str
field index or field name
Returns
-------
A new LLVM struct with the value inserted
"""
if isinstance(pos, str):
pos = self.get_field_position(pos)
return builder.insert_value(stval, val, [pos],
name="inserted." + self._fields[pos])
def get_field_position(self, field):
try:
return self._fields.index(field)
except ValueError:
raise KeyError("%s does not have a field named %r"
% (self.__class__.__name__, field))
@property
def field_count(self):
return len(self._fields)
def get_type(self, pos):
"""Get the frontend type (numba type) of a field given the position
or the fieldname
Args
----
pos: int or str
field index or field name
"""
if isinstance(pos, str):
pos = self.get_field_position(pos)
return self._members[pos]
def get_model(self, pos):
"""
Get the datamodel of a field given the position or the fieldname.
Args
----
pos: int or str
field index or field name
"""
return self._models[pos]
def traverse(self, builder):
def getter(k, value):
if value.type != self.get_value_type():
args = self.get_value_type(), value.type
raise TypeError("expecting {0} but got {1}".format(*args))
return self.get(builder, value, k)
return [(self.get_type(k), partial(getter, k)) for k in self._fields]
def inner_models(self):
return self._models
@register_default(types.Complex)
class ComplexModel(StructModel):
_element_type = NotImplemented
def __init__(self, dmm, fe_type):
members = [
('real', fe_type.underlying_float),
('imag', fe_type.underlying_float),
]
super(ComplexModel, self).__init__(dmm, fe_type, members)
@register_default(types.LiteralList)
@register_default(types.LiteralStrKeyDict)
@register_default(types.Tuple)
@register_default(types.NamedTuple)
@register_default(types.StarArgTuple)
class TupleModel(StructModel):
def __init__(self, dmm, fe_type):
members = [('f' + str(i), t) for i, t in enumerate(fe_type)]
super(TupleModel, self).__init__(dmm, fe_type, members)
@register_default(types.UnionType)
class UnionModel(StructModel):
def __init__(self, dmm, fe_type):
members = [
('tag', types.uintp),
# XXX: it should really be a MemInfoPointer(types.voidptr)
('payload', types.Tuple.from_types(fe_type.types)),
]
super(UnionModel, self).__init__(dmm, fe_type, members)
@register_default(types.Pair)
class PairModel(StructModel):
def __init__(self, dmm, fe_type):
members = [('first', fe_type.first_type),
('second', fe_type.second_type)]
super(PairModel, self).__init__(dmm, fe_type, members)
@register_default(types.ListPayload)
class ListPayloadModel(StructModel):
def __init__(self, dmm, fe_type):
# The fields are mutable but the payload is always manipulated
# by reference. This scheme allows mutations of an array to
# be seen by its iterators.
members = [
('size', types.intp),
('allocated', types.intp),
# This member is only used only for reflected lists
('dirty', types.boolean),
# Actually an inlined var-sized array
('data', fe_type.container.dtype),
]
super(ListPayloadModel, self).__init__(dmm, fe_type, members)
@register_default(types.List)
class ListModel(StructModel):
def __init__(self, dmm, fe_type):
payload_type = types.ListPayload(fe_type)
members = [
# The meminfo data points to a ListPayload
('meminfo', types.MemInfoPointer(payload_type)),
# This member is only used only for reflected lists
('parent', types.pyobject),
]
super(ListModel, self).__init__(dmm, fe_type, members)
@register_default(types.ListIter)
class ListIterModel(StructModel):
def __init__(self, dmm, fe_type):
payload_type = types.ListPayload(fe_type.container)
members = [
# The meminfo data points to a ListPayload (shared with the
# original list object)
('meminfo', types.MemInfoPointer(payload_type)),
('index', types.EphemeralPointer(types.intp)),
]
super(ListIterModel, self).__init__(dmm, fe_type, members)
@register_default(types.SetEntry)
class SetEntryModel(StructModel):
def __init__(self, dmm, fe_type):
dtype = fe_type.set_type.dtype
members = [
# -1 = empty, -2 = deleted
('hash', types.intp),
('key', dtype),
]
super(SetEntryModel, self).__init__(dmm, fe_type, members)
@register_default(types.SetPayload)
class SetPayloadModel(StructModel):
def __init__(self, dmm, fe_type):
entry_type = types.SetEntry(fe_type.container)
members = [
# Number of active + deleted entries
('fill', types.intp),
# Number of active entries
('used', types.intp),
# Allocated size - 1 (size being a power of 2)
('mask', types.intp),
# Search finger
('finger', types.intp),
# This member is only used only for reflected sets
('dirty', types.boolean),
# Actually an inlined var-sized array
('entries', entry_type),
]
super(SetPayloadModel, self).__init__(dmm, fe_type, members)
@register_default(types.Set)
class SetModel(StructModel):
def __init__(self, dmm, fe_type):
payload_type = types.SetPayload(fe_type)
members = [
# The meminfo data points to a SetPayload
('meminfo', types.MemInfoPointer(payload_type)),
# This member is only used only for reflected sets
('parent', types.pyobject),
]
super(SetModel, self).__init__(dmm, fe_type, members)
@register_default(types.SetIter)
class SetIterModel(StructModel):
def __init__(self, dmm, fe_type):
payload_type = types.SetPayload(fe_type.container)
members = [
# The meminfo data points to a SetPayload (shared with the
# original set object)
('meminfo', types.MemInfoPointer(payload_type)),
# The index into the entries table
('index', types.EphemeralPointer(types.intp)),
]
super(SetIterModel, self).__init__(dmm, fe_type, members)
@register_default(types.Array)
@register_default(types.Buffer)
@register_default(types.ByteArray)
@register_default(types.Bytes)
@register_default(types.MemoryView)
@register_default(types.PyArray)
class ArrayModel(StructModel):
def __init__(self, dmm, fe_type):
ndim = fe_type.ndim
members = [
('meminfo', types.MemInfoPointer(fe_type.dtype)),
('parent', types.pyobject),
('nitems', types.intp),
('itemsize', types.intp),
('data', types.CPointer(fe_type.dtype)),
('shape', types.UniTuple(types.intp, ndim)),
('strides', types.UniTuple(types.intp, ndim)),
]
super(ArrayModel, self).__init__(dmm, fe_type, members)
@register_default(types.ArrayFlags)
class ArrayFlagsModel(StructModel):
def __init__(self, dmm, fe_type):
members = [
('parent', fe_type.array_type),
]
super(ArrayFlagsModel, self).__init__(dmm, fe_type, members)
@register_default(types.NestedArray)
class NestedArrayModel(ArrayModel):
def __init__(self, dmm, fe_type):
self._be_type = dmm.lookup(fe_type.dtype).get_data_type()
super(NestedArrayModel, self).__init__(dmm, fe_type)
@register_default(types.Optional)
class OptionalModel(StructModel):
def __init__(self, dmm, fe_type):
members = [
('data', fe_type.type),
('valid', types.boolean),
]
self._value_model = dmm.lookup(fe_type.type)
super(OptionalModel, self).__init__(dmm, fe_type, members)
def get_return_type(self):
return self._value_model.get_return_type()
def as_return(self, builder, value):
raise NotImplementedError
def from_return(self, builder, value):
return self._value_model.from_return(builder, value)
def traverse(self, builder):
def get_data(value):
valid = get_valid(value)
data = self.get(builder, value, "data")
return builder.select(valid, data, ir.Constant(data.type, None))
def get_valid(value):
return self.get(builder, value, "valid")
return [(self.get_type("data"), get_data),
(self.get_type("valid"), get_valid)]
@register_default(types.Record)
class RecordModel(CompositeModel):
def __init__(self, dmm, fe_type):
super(RecordModel, self).__init__(dmm, fe_type)
self._models = [self._dmm.lookup(t) for _, t in fe_type.members]
self._be_type = ir.ArrayType(ir.IntType(8), fe_type.size)
self._be_ptr_type = self._be_type.as_pointer()
def get_value_type(self):
"""Passed around as reference to underlying data
"""
return self._be_ptr_type
def get_argument_type(self):
return self._be_ptr_type
def get_return_type(self):
return self._be_ptr_type
def get_data_type(self):
return self._be_type
def as_data(self, builder, value):
return builder.load(value)
def from_data(self, builder, value):
raise NotImplementedError("use load_from_data_pointer() instead")
def as_argument(self, builder, value):
return value
def from_argument(self, builder, value):
return value
def as_return(self, builder, value):
return value
def from_return(self, builder, value):
return value
def load_from_data_pointer(self, builder, ptr, align=None):
return builder.bitcast(ptr, self.get_value_type())
@register_default(types.UnicodeCharSeq)
class UnicodeCharSeq(DataModel):
def __init__(self, dmm, fe_type):
super(UnicodeCharSeq, self).__init__(dmm, fe_type)
charty = ir.IntType(numpy_support.sizeof_unicode_char * 8)
self._be_type = ir.ArrayType(charty, fe_type.count)
def get_value_type(self):
return self._be_type
def get_data_type(self):
return self._be_type
def as_data(self, builder, value):
return value
def from_data(self, builder, value):
return value
def as_return(self, builder, value):
return value
def from_return(self, builder, value):
return value
def as_argument(self, builder, value):
return value
def from_argument(self, builder, value):
return value
@register_default(types.CharSeq)
class CharSeq(DataModel):
def __init__(self, dmm, fe_type):
super(CharSeq, self).__init__(dmm, fe_type)
charty = ir.IntType(8)
self._be_type = ir.ArrayType(charty, fe_type.count)
def get_value_type(self):
return self._be_type
def get_data_type(self):
return self._be_type
def as_data(self, builder, value):
return value
def from_data(self, builder, value):
return value
def as_return(self, builder, value):
return value
def from_return(self, builder, value):
return value
def as_argument(self, builder, value):
return value
def from_argument(self, builder, value):
return value
class CContiguousFlatIter(StructModel):
def __init__(self, dmm, fe_type, need_indices):
assert fe_type.array_type.layout == 'C'
array_type = fe_type.array_type
dtype = array_type.dtype
ndim = array_type.ndim
members = [('array', array_type),
('stride', types.intp),
('index', types.EphemeralPointer(types.intp)),
]
if need_indices:
# For ndenumerate()
members.append(('indices', types.EphemeralArray(types.intp, ndim)))
super(CContiguousFlatIter, self).__init__(dmm, fe_type, members)
class FlatIter(StructModel):
def __init__(self, dmm, fe_type):
array_type = fe_type.array_type
dtype = array_type.dtype
ndim = array_type.ndim
members = [('array', array_type),
('pointers', types.EphemeralArray(types.CPointer(dtype), ndim)),
('indices', types.EphemeralArray(types.intp, ndim)),
('exhausted', types.EphemeralPointer(types.boolean)),
]
super(FlatIter, self).__init__(dmm, fe_type, members)
@register_default(types.UniTupleIter)
class UniTupleIter(StructModel):
def __init__(self, dmm, fe_type):
members = [('index', types.EphemeralPointer(types.intp)),
('tuple', fe_type.container,)]
super(UniTupleIter, self).__init__(dmm, fe_type, members)
@register_default(types.misc.SliceLiteral)
@register_default(types.SliceType)
class SliceModel(StructModel):
def __init__(self, dmm, fe_type):
members = [('start', types.intp),
('stop', types.intp),
('step', types.intp),
]
super(SliceModel, self).__init__(dmm, fe_type, members)
@register_default(types.NPDatetime)
@register_default(types.NPTimedelta)
class NPDatetimeModel(PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super(NPDatetimeModel, self).__init__(dmm, fe_type, be_type)
@register_default(types.ArrayIterator)
class ArrayIterator(StructModel):
def __init__(self, dmm, fe_type):
# We use an unsigned index to avoid the cost of negative index tests.
members = [('index', types.EphemeralPointer(types.uintp)),
('array', fe_type.array_type)]
super(ArrayIterator, self).__init__(dmm, fe_type, members)
@register_default(types.EnumerateType)
class EnumerateType(StructModel):
def __init__(self, dmm, fe_type):
members = [('count', types.EphemeralPointer(types.intp)),
('iter', fe_type.source_type)]
super(EnumerateType, self).__init__(dmm, fe_type, members)
@register_default(types.ZipType)
class ZipType(StructModel):
def __init__(self, dmm, fe_type):
members = [('iter%d' % i, source_type.iterator_type)
for i, source_type in enumerate(fe_type.source_types)]
super(ZipType, self).__init__(dmm, fe_type, members)
@register_default(types.RangeIteratorType)
class RangeIteratorType(StructModel):
def __init__(self, dmm, fe_type):
int_type = fe_type.yield_type
members = [('iter', types.EphemeralPointer(int_type)),
('stop', int_type),
('step', int_type),
('count', types.EphemeralPointer(int_type))]
super(RangeIteratorType, self).__init__(dmm, fe_type, members)
@register_default(types.Generator)
class GeneratorModel(CompositeModel):
def __init__(self, dmm, fe_type):
super(GeneratorModel, self).__init__(dmm, fe_type)
# XXX Fold this in DataPacker?
self._arg_models = [self._dmm.lookup(t) for t in fe_type.arg_types
if not isinstance(t, types.Omitted)]
self._state_models = [self._dmm.lookup(t) for t in fe_type.state_types]
self._args_be_type = ir.LiteralStructType(
[t.get_data_type() for t in self._arg_models])
self._state_be_type = ir.LiteralStructType(
[t.get_data_type() for t in self._state_models])
# The whole generator closure
self._be_type = ir.LiteralStructType(
[self._dmm.lookup(types.int32).get_value_type(),
self._args_be_type, self._state_be_type])
self._be_ptr_type = self._be_type.as_pointer()
def get_value_type(self):
"""
The generator closure is passed around as a reference.
"""
return self._be_ptr_type
def get_argument_type(self):
return self._be_ptr_type
def get_return_type(self):
return self._be_type
def get_data_type(self):
return self._be_type
def as_argument(self, builder, value):
return value
def from_argument(self, builder, value):
return value
def as_return(self, builder, value):
return self.as_data(builder, value)
def from_return(self, builder, value):
return self.from_data(builder, value)
def as_data(self, builder, value):
return builder.load(value)
def from_data(self, builder, value):
stack = cgutils.alloca_once(builder, value.type)
builder.store(value, stack)
return stack
@register_default(types.ArrayCTypes)
class ArrayCTypesModel(StructModel):
def __init__(self, dmm, fe_type):
# ndim = fe_type.ndim
members = [('data', types.CPointer(fe_type.dtype)),
('meminfo', types.MemInfoPointer(fe_type.dtype))]
super(ArrayCTypesModel, self).__init__(dmm, fe_type, members)
@register_default(types.RangeType)
class RangeModel(StructModel):
def __init__(self, dmm, fe_type):
int_type = fe_type.iterator_type.yield_type
members = [('start', int_type),
('stop', int_type),
('step', int_type)]
super(RangeModel, self).__init__(dmm, fe_type, members)
# =============================================================================
@register_default(types.NumpyNdIndexType)
class NdIndexModel(StructModel):
def __init__(self, dmm, fe_type):
ndim = fe_type.ndim
members = [('shape', types.UniTuple(types.intp, ndim)),
('indices', types.EphemeralArray(types.intp, ndim)),
('exhausted', types.EphemeralPointer(types.boolean)),
]
super(NdIndexModel, self).__init__(dmm, fe_type, members)
@register_default(types.NumpyFlatType)
def handle_numpy_flat_type(dmm, ty):
if ty.array_type.layout == 'C':
return CContiguousFlatIter(dmm, ty, need_indices=False)
else:
return FlatIter(dmm, ty)
@register_default(types.NumpyNdEnumerateType)
def handle_numpy_ndenumerate_type(dmm, ty):
if ty.array_type.layout == 'C':
return CContiguousFlatIter(dmm, ty, need_indices=True)
else:
return FlatIter(dmm, ty)
@register_default(types.BoundFunction)
def handle_bound_function(dmm, ty):
# The same as the underlying type
return dmm[ty.this]
@register_default(types.NumpyNdIterType)
class NdIter(StructModel):
def __init__(self, dmm, fe_type):
array_types = fe_type.arrays
ndim = fe_type.ndim
shape_len = ndim if fe_type.need_shaped_indexing else 1
members = [('exhausted', types.EphemeralPointer(types.boolean)),
('arrays', types.Tuple(array_types)),
# The iterator's main shape and indices
('shape', types.UniTuple(types.intp, shape_len)),
('indices', types.EphemeralArray(types.intp, shape_len)),
]
# Indexing state for the various sub-iterators
# XXX use a tuple instead?
for i, sub in enumerate(fe_type.indexers):
kind, start_dim, end_dim, _ = sub
member_name = 'index%d' % i
if kind == 'flat':
# A single index into the flattened array
members.append((member_name, types.EphemeralPointer(types.intp)))
elif kind in ('scalar', 'indexed', '0d'):
# Nothing required
pass
else:
assert 0
# Slots holding values of the scalar args
# XXX use a tuple instead?
for i, ty in enumerate(fe_type.arrays):
if not isinstance(ty, types.Array):
member_name = 'scalar%d' % i
members.append((member_name, types.EphemeralPointer(ty)))
super(NdIter, self).__init__(dmm, fe_type, members)
@register_default(types.DeferredType)
class DeferredStructModel(CompositeModel):
def __init__(self, dmm, fe_type):
super(DeferredStructModel, self).__init__(dmm, fe_type)
self.typename = "deferred.{0}".format(id(fe_type))
self.actual_fe_type = fe_type.get()
def get_value_type(self):
return ir.global_context.get_identified_type(self.typename + '.value')
def get_data_type(self):
return ir.global_context.get_identified_type(self.typename + '.data')
def get_argument_type(self):
return self._actual_model.get_argument_type()
def as_argument(self, builder, value):
inner = self.get(builder, value)
return self._actual_model.as_argument(builder, inner)
def from_argument(self, builder, value):
res = self._actual_model.from_argument(builder, value)
return self.set(builder, self.make_uninitialized(), res)
def from_data(self, builder, value):
self._define()
elem = self.get(builder, value)
value = self._actual_model.from_data(builder, elem)
out = self.make_uninitialized()
return self.set(builder, out, value)
def as_data(self, builder, value):
self._define()
elem = self.get(builder, value)
value = self._actual_model.as_data(builder, elem)
out = self.make_uninitialized(kind='data')
return self.set(builder, out, value)
def from_return(self, builder, value):
return value
def as_return(self, builder, value):
return value
def get(self, builder, value):
return builder.extract_value(value, [0])
def set(self, builder, value, content):
return builder.insert_value(value, content, [0])
def make_uninitialized(self, kind='value'):
self._define()
if kind == 'value':
ty = self.get_value_type()
else:
ty = self.get_data_type()
return ir.Constant(ty, ir.Undefined)
def _define(self):
valty = self.get_value_type()
self._define_value_type(valty)
datty = self.get_data_type()
self._define_data_type(datty)
def _define_value_type(self, value_type):
if value_type.is_opaque:
value_type.set_body(self._actual_model.get_value_type())
def _define_data_type(self, data_type):
if data_type.is_opaque:
data_type.set_body(self._actual_model.get_data_type())
@property
def _actual_model(self):
return self._dmm.lookup(self.actual_fe_type)
def traverse(self, builder):
return [(self.actual_fe_type,
lambda value: builder.extract_value(value, [0]))]
@register_default(types.StructRefPayload)
class StructPayloadModel(StructModel):
"""Model for the payload of a mutable struct
"""
def __init__(self, dmm, fe_typ):
members = tuple(fe_typ.field_dict.items())
super().__init__(dmm, fe_typ, members)
class StructRefModel(StructModel):
"""Model for a mutable struct.
A reference to the payload
"""
def __init__(self, dmm, fe_typ):
dtype = fe_typ.get_data_type()
members = [
("meminfo", types.MemInfoPointer(dtype)),
]
super().__init__(dmm, fe_typ, members)
| IntelLabs/numba | numba/core/datamodel/models.py | Python | bsd-2-clause | 44,245 |
/**
* Close Changeset
* http://wiki.openstreetmap.org/wiki/API_v0.6#Close:_PUT_.2Fapi.2F0.6.2Fchangeset.2F.23id.2Fclose
*/
module.exports = function (req, res, api, params, next) {
var parts = params.id.split(':')
var version = parts.length === 2 ? parts[1] : null
api.closeChangeset(parts[0], version, function (err) {
if (err) {
if (err.name === 'ForkedChangesetError') {
err.message += '\n specify the version after the id using this syntax:\n' +
'PUT /api/0.6/changeset/$ID:$VERSION/close'
}
return next(err)
}
res.end()
})
}
| digidem/osm-p2p-server | routes/changeset_close.js | JavaScript | bsd-2-clause | 590 |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using XenAPI;
using XenAdmin.Diagnostics.Problems;
using XenAdmin.Core;
using System.IO;
using XenAdmin.Diagnostics.Problems.HostProblem;
using System.Collections.Generic;
using XenAdmin.Actions;
using System.Linq;
namespace XenAdmin.Diagnostics.Checks
{
class DiskSpaceForAutomatedUpdatesCheck : HostPostLivenessCheck
{
private readonly Dictionary<Host, List<XenServerPatch>> updateSequence;
public DiskSpaceForAutomatedUpdatesCheck(Host host, Dictionary<Host, List<XenServerPatch>> updateSequence)
: base(host)
{
this.updateSequence = updateSequence;
}
protected override Problem RunHostCheck()
{
if (!Host.Connection.IsConnected)
throw new EndOfStreamException(Helpers.GetName(Host.Connection));
var elyOrGreater = Helpers.ElyOrGreater(Host.Connection);
// check the disk space on host
var requiredDiskSpace = elyOrGreater
? updateSequence[Host].Sum(p => p.InstallationSize) // all updates on this host (for installation)
: Host.IsCoordinator()
? updateSequence[Host].Sum(p => p.InstallationSize) + updateSequence.Values.SelectMany(p => p).Distinct().Sum(p => p.InstallationSize) // coordinator: all updates on coordinator (for installation) + all updates in pool (for upload)
: updateSequence[Host].Sum(p => p.InstallationSize) * 2; // non-coordinator: all updates on this host x 2 (for installation + upload)
var action = new GetDiskSpaceRequirementsAction(Host, requiredDiskSpace, true, DiskSpaceRequirements.OperationTypes.automatedUpdates);
try
{
action.RunExternal(action.Session);
}
catch
{
log.WarnFormat("Could not get disk space requirements");
}
if (action.Succeeded && action.DiskSpaceRequirements.AvailableDiskSpace < requiredDiskSpace)
return new HostOutOfSpaceProblem(this, Host, action.DiskSpaceRequirements);
// check the disk space for uploading the update files to the pool's SRs (only needs to be done once, so only run this on the coordinator)
if (elyOrGreater && Host.IsCoordinator())
{
var allPatches = updateSequence.Values.SelectMany(p => p).Distinct().ToList();
var maxFileSize = allPatches.Max(p => p.DownloadSize);
var availableSRs = Host.Connection.Cache.SRs.Where(sr => sr.SupportsVdiCreate() && !sr.IsDetached()).ToList();
var maxSrSize = availableSRs.Max(sr => sr.FreeSpace());
// can accomodate the largest file?
if (maxSrSize < maxFileSize)
{
return new HostOutOfSpaceProblem(this, Host,
new DiskSpaceRequirements(DiskSpaceRequirements.OperationTypes.automatedUpdatesUploadOne, Host, null, maxFileSize, maxSrSize, 0));
}
// can accomodate all files?
var totalFileSize = allPatches.Sum(p => p.DownloadSize);
var totalAvailableSpace = availableSRs.Sum(sr => sr.FreeSpace());
if (totalAvailableSpace < totalFileSize)
{
return new HostOutOfSpaceProblem(this, Host,
new DiskSpaceRequirements(DiskSpaceRequirements.OperationTypes.automatedUpdatesUploadAll, Host, null, totalFileSize, totalAvailableSpace, 0));
}
}
return null;
}
public override string Description
{
get { return Messages.SERVER_SIDE_CHECK_AUTO_MODE_DESCRIPTION; }
}
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}
}
| kc284/xenadmin | XenAdmin/Diagnostics/Checks/DiskSpaceForBatchUpdatesCheck.cs | C# | bsd-2-clause | 5,462 |
///////////////////////////////////////////////////////////////////////////////
// Name: tests/controls/pickertest.cpp
// Purpose: Tests for various wxPickerBase based classes
// Author: Steven Lamerton
// Created: 2010-08-07
// Copyright: (c) 2010 Steven Lamerton
///////////////////////////////////////////////////////////////////////////////
#include "testprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/app.h"
#endif // WX_PRECOMP
#include "wx/clrpicker.h"
#include "wx/filepicker.h"
#include "wx/fontpicker.h"
#include "pickerbasetest.h"
#include "asserthelper.h"
#if wxUSE_COLOURPICKERCTRL
class ColourPickerCtrlTestCase : public PickerBaseTestCase,
public CppUnit::TestCase
{
public:
ColourPickerCtrlTestCase() { }
virtual void setUp();
virtual void tearDown();
private:
virtual wxPickerBase *GetBase() const { return m_colour; }
CPPUNIT_TEST_SUITE( ColourPickerCtrlTestCase );
wxPICKER_BASE_TESTS();
CPPUNIT_TEST_SUITE_END();
wxColourPickerCtrl *m_colour;
wxDECLARE_NO_COPY_CLASS(ColourPickerCtrlTestCase);
};
// register in the unnamed registry so that these tests are run by default
CPPUNIT_TEST_SUITE_REGISTRATION( ColourPickerCtrlTestCase );
// also include in its own registry so that these tests can be run alone
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( ColourPickerCtrlTestCase,
"ColourPickerCtrlTestCase" );
void ColourPickerCtrlTestCase::setUp()
{
m_colour = new wxColourPickerCtrl(wxTheApp->GetTopWindow(), wxID_ANY,
*wxBLACK, wxDefaultPosition,
wxDefaultSize, wxCLRP_USE_TEXTCTRL);
}
void ColourPickerCtrlTestCase::tearDown()
{
wxDELETE(m_colour);
}
#endif //wxUSE_COLOURPICKERCTRL
#if wxUSE_DIRPICKERCTRL
class DirPickerCtrlTestCase : public PickerBaseTestCase,
public CppUnit::TestCase
{
public:
DirPickerCtrlTestCase() { }
virtual void setUp();
virtual void tearDown();
private:
virtual wxPickerBase *GetBase() const { return m_dir; }
CPPUNIT_TEST_SUITE( DirPickerCtrlTestCase );
wxPICKER_BASE_TESTS();
CPPUNIT_TEST_SUITE_END();
wxDirPickerCtrl *m_dir;
wxDECLARE_NO_COPY_CLASS(DirPickerCtrlTestCase);
};
// register in the unnamed registry so that these tests are run by default
CPPUNIT_TEST_SUITE_REGISTRATION( DirPickerCtrlTestCase );
// also include in its own registry so that these tests can be run alone
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( DirPickerCtrlTestCase,
"DirPickerCtrlTestCase" );
void DirPickerCtrlTestCase::setUp()
{
m_dir = new wxDirPickerCtrl(wxTheApp->GetTopWindow(), wxID_ANY,
wxEmptyString, wxDirSelectorPromptStr,
wxDefaultPosition, wxDefaultSize,
wxDIRP_USE_TEXTCTRL);
}
void DirPickerCtrlTestCase::tearDown()
{
wxDELETE(m_dir);
}
#endif //wxUSE_DIRPICKERCTRL
#if wxUSE_FILEPICKERCTRL
class FilePickerCtrlTestCase : public PickerBaseTestCase,
public CppUnit::TestCase
{
public:
FilePickerCtrlTestCase() { }
virtual void setUp();
virtual void tearDown();
private:
virtual wxPickerBase *GetBase() const { return m_file; }
CPPUNIT_TEST_SUITE( FilePickerCtrlTestCase );
wxPICKER_BASE_TESTS();
CPPUNIT_TEST_SUITE_END();
wxFilePickerCtrl *m_file;
wxDECLARE_NO_COPY_CLASS(FilePickerCtrlTestCase);
};
// register in the unnamed registry so that these tests are run by default
CPPUNIT_TEST_SUITE_REGISTRATION( FilePickerCtrlTestCase );
// also include in its own registry so that these tests can be run alone
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( FilePickerCtrlTestCase,
"FilePickerCtrlTestCase" );
void FilePickerCtrlTestCase::setUp()
{
m_file = new wxFilePickerCtrl(wxTheApp->GetTopWindow(), wxID_ANY,
wxEmptyString, wxFileSelectorPromptStr,
wxFileSelectorDefaultWildcardStr,
wxDefaultPosition, wxDefaultSize,
wxFLP_USE_TEXTCTRL);
}
void FilePickerCtrlTestCase::tearDown()
{
wxDELETE(m_file);
}
#endif //wxUSE_FILEPICKERCTRL
#if wxUSE_FONTPICKERCTRL
class FontPickerCtrlTestCase : public PickerBaseTestCase,
public CppUnit::TestCase
{
public:
FontPickerCtrlTestCase() { }
virtual void setUp();
virtual void tearDown();
private:
virtual wxPickerBase *GetBase() const { return m_font; }
CPPUNIT_TEST_SUITE( FontPickerCtrlTestCase );
wxPICKER_BASE_TESTS();
CPPUNIT_TEST( ColourSelection );
CPPUNIT_TEST_SUITE_END();
void ColourSelection();
wxFontPickerCtrl *m_font;
wxDECLARE_NO_COPY_CLASS(FontPickerCtrlTestCase);
};
// register in the unnamed registry so that these tests are run by default
CPPUNIT_TEST_SUITE_REGISTRATION( FontPickerCtrlTestCase );
// also include in its own registry so that these tests can be run alone
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( FontPickerCtrlTestCase,
"FontPickerCtrlTestCase" );
void FontPickerCtrlTestCase::setUp()
{
m_font = new wxFontPickerCtrl(wxTheApp->GetTopWindow(), wxID_ANY,
wxNullFont, wxDefaultPosition, wxDefaultSize,
wxFNTP_USE_TEXTCTRL);
}
void FontPickerCtrlTestCase::tearDown()
{
wxDELETE(m_font);
}
void FontPickerCtrlTestCase::ColourSelection()
{
wxColour selectedColour(0xFF4269UL);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Default font picker color must be black",
m_font->GetSelectedColour(), wxColour(*wxBLACK));
m_font->SetSelectedColour(selectedColour);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Font picker did not react to color selection",
m_font->GetSelectedColour(), selectedColour);
}
#endif //wxUSE_FONTPICKERCTRL
| adouble42/nemesis-current | wxWidgets-3.1.0/tests/controls/pickertest.cpp | C++ | bsd-2-clause | 6,106 |
/*
This file is a part of libcds - Concurrent Data Structures library
See http://libcds.sourceforge.net/
(C) Copyright Maxim Khiszinsky (libcds.sf.com) 2006-2013
Distributed under the BSD license (see accompanying file license.txt)
Version 1.4.0
*/
// Linux scalability allocator test
#include "alloc/michael_allocator.h"
#include <cds/os/timer.h>
#include <cds/os/topology.h>
#include "cppunit/thread.h"
namespace memory {
static size_t s_nPassCount = 10000000 ;
static size_t s_nMaxBlockSize = 64 * 1024 - 16 ;
static size_t s_nMaxThreadCount = 64 ;
static size_t s_nPassPerThread ;
# define TEST_ALLOC(X, CLASS) void X() { test< CLASS >(false) ; }
# define TEST_ALLOC_STAT(X, CLASS) void X() { test< CLASS >(true) ; }
class Linux_Scale: public CppUnitMini::TestCase
{
template <class ALLOC>
class Thread: public CppUnitMini::TestThread
{
ALLOC& m_Alloc ;
size_t m_nSize ;
virtual Thread * clone()
{
return new Thread( *this ) ;
}
public:
public:
Thread( CppUnitMini::ThreadPool& pool, ALLOC& a, size_t nSize )
: CppUnitMini::TestThread( pool )
, m_Alloc( a )
, m_nSize( nSize )
{}
Thread( Thread& src )
: CppUnitMini::TestThread( src )
, m_Alloc( src.m_Alloc )
, m_nSize( src.m_nSize )
{}
Linux_Scale& getTest()
{
return reinterpret_cast<Linux_Scale&>( m_Pool.m_Test ) ;
}
virtual void init() { cds::threading::Manager::attachThread() ; }
virtual void fini() { cds::threading::Manager::detachThread() ; }
virtual void test()
{
for ( size_t i = 0; i < s_nPassPerThread; ++i ) {
typename ALLOC::value_type * p = m_Alloc.allocate( m_nSize / sizeof(typename ALLOC::value_type), NULL ) ;
CPPUNIT_ASSERT( p != NULL ) ;
if ( m_nSize < 32 )
memset( p, 0, m_nSize ) ;
else {
memset( p, 0, 16 ) ;
memset( ((char *)p) + m_nSize * sizeof(*p) - 16, 0, 16 ) ;
}
CPPUNIT_ASSERT( (reinterpret_cast<cds::uptr_atomic_t>(p) & (ALLOC::alignment - 1)) == 0 ) ;
m_Alloc.deallocate( p, 1 ) ;
}
}
};
template <class ALLOC>
void test( size_t nThreadCount, size_t nSize )
{
cds::OS::Timer timer ;
ALLOC alloc ;
CPPUNIT_MSG( " Block size=" << nSize ) ;
s_nPassPerThread = s_nPassCount / nThreadCount ;
CppUnitMini::ThreadPool pool( *this ) ;
pool.add( new Thread<ALLOC>( pool, alloc, nSize ), nThreadCount ) ;
pool.run() ;
CPPUNIT_MSG( " Duration=" << pool.avgDuration() ) ;
}
template <class ALLOC>
void test( size_t nThreadCount )
{
CPPUNIT_MSG( "Thread count=" << nThreadCount ) ;
for ( size_t sz = 1; sz < s_nMaxBlockSize; sz *= 2 ) {
test<ALLOC>( nThreadCount, sz ) ;
}
}
template <class ALLOC>
void test( bool bStat )
{
for ( size_t nThreadCount = 1; nThreadCount <= s_nMaxThreadCount; nThreadCount *= 2 ) {
summary_stat stBegin ;
if ( bStat )
ALLOC::stat(stBegin) ;
test<ALLOC>( nThreadCount ) ;
summary_stat stEnd ;
if ( bStat ) {
ALLOC::stat( stEnd ) ;
std::cout << "\nStatistics:\n"
<< stEnd
;
stEnd -= stBegin ;
std::cout << "\nDelta statistics:\n"
<< stEnd
;
}
}
}
void setUpParams( const CppUnitMini::TestCfg& cfg )
{
s_nPassCount = cfg.getULong( "PassCount", 10000000 ) ;
s_nMaxBlockSize = cfg.getULong( "MaxBlockSize", 64 * 1024 - 16 ) ;
s_nMaxThreadCount = cfg.getUInt( "MaxThreadCount", 64 ) ;
if ( s_nMaxThreadCount == 0 )
s_nMaxThreadCount = cds::OS::topology::processor_count() * 2 ;
}
typedef MichaelAlignHeap_Stat<char, 64> t_MichaelAlignHeap_Stat ;
typedef MichaelAlignHeap_NoStat<char,64> t_MichaelAlignHeap_NoStat ;
typedef system_aligned_allocator<char, 64> t_system_aligned_allocator ;
TEST_ALLOC_STAT( michael_heap_stat, MichaelHeap_Stat<char> )
TEST_ALLOC( michael_heap_nostat, MichaelHeap_NoStat<char> )
TEST_ALLOC( std_alloc, std_allocator<char> )
TEST_ALLOC_STAT( michael_alignheap_stat, t_MichaelAlignHeap_Stat )
TEST_ALLOC( michael_alignheap_nostat, t_MichaelAlignHeap_NoStat )
TEST_ALLOC( system_aligned_alloc, t_system_aligned_allocator )
CPPUNIT_TEST_SUITE( Linux_Scale )
CPPUNIT_TEST( michael_heap_nostat )
CPPUNIT_TEST( michael_heap_stat )
CPPUNIT_TEST( std_alloc )
CPPUNIT_TEST( system_aligned_alloc )
CPPUNIT_TEST( michael_alignheap_stat )
CPPUNIT_TEST( michael_alignheap_nostat )
CPPUNIT_TEST_SUITE_END();
};
} // namespace memory
CPPUNIT_TEST_SUITE_REGISTRATION( memory::Linux_Scale ) ;
| IMCG/CDS | tests/unit/alloc/linux_scale.cpp | C++ | bsd-2-clause | 5,776 |
using System;
using System.Linq;
using LightBDD.Core.Metadata;
using LightBDD.Core.Notification;
using LightBDD.Core.Results;
namespace LightBDD.Framework.Notification.Implementation
{
internal class ParallelProgressNotifier : IScenarioProgressNotifier, IFeatureProgressNotifier
{
private readonly ProgressManager _manager;
private int? _currentScenarioNumber;
private readonly DefaultProgressNotifier _notifier;
private readonly Action<string> _onNotify;
public ParallelProgressNotifier(ProgressManager manager, Action<string>[] onNotify)
{
if (onNotify == null || !onNotify.Any())
throw new ArgumentException("At least one on notify action required", nameof(onNotify));
_manager = manager ?? throw new ArgumentNullException(nameof(manager));
_onNotify = onNotify.Aggregate((current, next) => current + next);
_notifier = new DefaultProgressNotifier(NotifyProgress);
}
private void NotifyProgress(string message)
{
var progress = _manager.GetProgress();
var header = $"Fi={progress.FinishedScenarios:D3},Fa={progress.FailedScenarios:D3},Pe={progress.PendingScenarios:D3} #{_currentScenarioNumber,3}> ";
_onNotify(header + message.Replace(Environment.NewLine, Environment.NewLine + new string(' ', header.Length)));
}
public void NotifyFeatureStart(IFeatureInfo feature)
{
_notifier.NotifyFeatureStart(feature);
}
public void NotifyFeatureFinished(IFeatureResult feature)
{
_notifier.NotifyFeatureFinished(feature);
}
public void NotifyScenarioStart(IScenarioInfo scenario)
{
_currentScenarioNumber = _manager.StartNewScenario();
_notifier.NotifyScenarioStart(scenario);
}
public void NotifyScenarioFinished(IScenarioResult scenario)
{
_manager.CaptureScenarioResult(scenario.Status);
_notifier.NotifyScenarioFinished(scenario);
_manager.FinishScenario();
}
public void NotifyStepStart(IStepInfo step)
{
_notifier.NotifyStepStart(step);
}
public void NotifyStepFinished(IStepResult step)
{
_notifier.NotifyStepFinished(step);
}
public void NotifyStepComment(IStepInfo step, string comment)
{
_notifier.NotifyStepComment(step, comment);
}
}
} | Suremaker/LightBDD | src/LightBDD.Framework/Notification/Implementation/ParallelProgressNotifier.cs | C# | bsd-2-clause | 2,532 |
/*
json2.js
2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
define(function() {
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
});
| chop-dbhi/cilantro | src/js/json2.js | JavaScript | bsd-2-clause | 17,548 |
/*!
* OS.js - JavaScript Operating System
*
* Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Anders Evenrud <andersevenrud@gmail.com>
* @licence Simplified BSD License
*/
(function(API, Utils, _StandardDialog) {
'use strict';
/**
* Font Dialog
*
* @param Object args Options
* @param Function onClose Callback on close => fn(button, fontName, fontSize)
*
* @option args String name Default font name (optional)
* @option args int size Default font size (optional)
* @option args String background Background color (default=#ffffff)
* @option args String color Foreground color (default=#000000)
* @option args Array list List of fonts (optional)
* @option args String sizeType Font size type (default=px)
* @option args String text Text to display on preview (optional)
* @option args int minSize Minimum font size (optional)
* @option args int maxSize Maximum font size (optional)
*
* @api OSjs.Dialogs.Font
* @see OSjs.Dialogs._StandardDialog
*
* @extends _StandardDialog
* @class
*/
var FontDialog = function(args, onClose) {
args = args || {};
this.fontName = args.name || OSjs.Core.getHandler().getConfig('Fonts')['default'];
this.fontSize = args.size || 12;
this.background = args.background || '#ffffff';
this.color = args.color || '#000000';
this.fonts = args.list || OSjs.Core.getHandler().getConfig('Fonts').list;
this.sizeType = args.sizeType || 'px';
this.text = args.text || 'The quick brown fox jumps over the lazy dog';
this.minSize = typeof args.minSize === 'undefined' ? 6 : args.minSize;
this.maxSize = typeof args.maxSize === 'undefined' ? 30 : args.maxSize;
this.$selectFonts = null;
this.$selectSize = null;
_StandardDialog.apply(this, ['FontDialog', {
title: API._('DIALOG_FONT_TITLE'),
buttons: ['cancel', 'ok']
}, {width:450, height:250}, onClose]);
};
FontDialog.prototype = Object.create(_StandardDialog.prototype);
FontDialog.prototype.updateFont = function(name, size) {
var rt = this._getGUIElement('GUIRichText');
if ( name !== null && name ) {
this.fontName = name;
}
if ( size !== null && size ) {
this.fontSize = parseInt(size, 10);
}
var styles = [];
if ( this.sizeType === 'internal' ) {
styles = [
'font-family: ' + this.fontName,
'background: ' + this.background,
'color: ' + this.color
];
rt.setContent('<font size="' + this.fontSize + '" style="' + styles.join(';') + '">' + this.text + '</font>');
} else {
styles = [
'font-family: ' + this.fontName,
'font-size: ' + this.fontSize + 'px',
'background: ' + this.background,
'color: ' + this.color
];
rt.setContent('<div style="' + styles.join(';') + '">' + this.text + '</div>');
}
};
FontDialog.prototype.init = function() {
var self = this;
var root = _StandardDialog.prototype.init.apply(this, arguments);
var option;
var rt = this._addGUIElement(new OSjs.GUI.RichText('GUIRichText'), this.$element);
this.$selectFont = document.createElement('select');
this.$selectFont.className = 'SelectFont';
this.$selectFont.setAttribute('size', '7');
this.fonts.forEach(function(font, f) {
var option = document.createElement('option');
option.value = f;
option.appendChild(document.createTextNode(font));
self.$selectFont.appendChild(option);
if ( self.fontName.toLowerCase() === font.toLowerCase() ) {
self.$selectFont.selectedIndex = f;
}
});
this._addEventListener(this.$selectFont, 'change', function(ev) {
var i = this.selectedIndex;
if ( self.fonts[i] ) {
self.updateFont(self.fonts[i], null);
}
});
this.$element.appendChild(this.$selectFont);
if ( this.maxSize > 0 ) {
this.$selectSize = document.createElement('select');
this.$selectSize.className = 'SelectSize';
this.$selectSize.setAttribute('size', '7');
var i = 0;
for ( var s = this.minSize; s <= this.maxSize; s++ ) {
option = document.createElement('option');
option.value = s;
option.innerHTML = s;
this.$selectSize.appendChild(option);
if ( this.fontSize === s ) {
this.$selectSize.selectedIndex = i;
}
i++;
}
this._addEventListener(this.$selectSize, 'change', function(ev) {
var i = this.selectedIndex;
var o = this.options[i];
if ( o ) {
self.updateFont(null, o.value);
}
});
this.$element.appendChild(this.$selectSize);
} else {
this.$element.className += ' NoFontSizes';
}
return root;
};
FontDialog.prototype._inited = function() {
_StandardDialog.prototype._inited.apply(this, arguments);
this.updateFont();
};
FontDialog.prototype.onButtonClick = function(btn, ev) {
if ( btn === 'ok' ) {
if ( this.buttons[btn] ) {
this.end('ok', this.fontName, this.fontSize);
}
return;
}
_StandardDialog.prototype.onButtonClick.apply(this, arguments);
};
/////////////////////////////////////////////////////////////////////////////
// EXPORTS
/////////////////////////////////////////////////////////////////////////////
OSjs.Dialogs.Font = FontDialog;
})(OSjs.API, OSjs.Utils, OSjs.Dialogs._StandardDialog);
| nelug/OS.js-v2 | src/javascript/dialogs/font.js | JavaScript | bsd-2-clause | 7,099 |
// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package testblas
import (
"fmt"
"math/cmplx"
"testing"
"golang.org/x/exp/rand"
"gonum.org/v1/gonum/blas"
)
type Zhemmer interface {
Zhemm(side blas.Side, uplo blas.Uplo, m, n int, alpha complex128, a []complex128, lda int, b []complex128, ldb int, beta complex128, c []complex128, ldc int)
}
func ZhemmTest(t *testing.T, impl Zhemmer) {
for _, side := range []blas.Side{blas.Left, blas.Right} {
for _, uplo := range []blas.Uplo{blas.Lower, blas.Upper} {
name := sideString(side) + "-" + uploString(uplo)
t.Run(name, func(t *testing.T) {
for _, m := range []int{0, 1, 2, 3, 4, 5} {
for _, n := range []int{0, 1, 2, 3, 4, 5} {
zhemmTest(t, impl, side, uplo, m, n)
}
}
})
}
}
}
func zhemmTest(t *testing.T, impl Zhemmer, side blas.Side, uplo blas.Uplo, m, n int) {
const tol = 1e-13
rnd := rand.New(rand.NewSource(1))
nA := m
if side == blas.Right {
nA = n
}
for _, lda := range []int{max(1, nA), nA + 2} {
for _, ldb := range []int{max(1, n), n + 3} {
for _, ldc := range []int{max(1, n), n + 4} {
for _, alpha := range []complex128{0, 1, complex(0.7, -0.9)} {
for _, beta := range []complex128{0, 1, complex(1.3, -1.1)} {
for _, nanC := range []bool{false, true} {
if nanC && beta != 0 {
// Skip tests with C containing NaN values
// unless beta would zero out the NaNs.
continue
}
// Allocate the matrix A and fill it with random numbers.
a := make([]complex128, nA*lda)
for i := range a {
a[i] = rndComplex128(rnd)
}
// Create a copy of A for checking that
// Zhemm does not modify its triangle
// opposite to uplo.
aCopy := make([]complex128, len(a))
copy(aCopy, a)
// Create a copy of A expanded into a
// full hermitian matrix for computing
// the expected result using zmm.
aHem := make([]complex128, len(a))
copy(aHem, a)
if uplo == blas.Upper {
for i := 0; i < nA; i++ {
aHem[i*lda+i] = complex(real(aHem[i*lda+i]), 0)
for j := i + 1; j < nA; j++ {
aHem[j*lda+i] = cmplx.Conj(aHem[i*lda+j])
}
}
} else {
for i := 0; i < nA; i++ {
for j := 0; j < i; j++ {
aHem[j*lda+i] = cmplx.Conj(aHem[i*lda+j])
}
aHem[i*lda+i] = complex(real(aHem[i*lda+i]), 0)
}
}
// Allocate the matrix B and fill it with random numbers.
b := make([]complex128, m*ldb)
for i := range b {
b[i] = rndComplex128(rnd)
}
// Create a copy of B for checking that
// Zhemm does not modify B.
bCopy := make([]complex128, len(b))
copy(bCopy, b)
// Allocate the matrix C and fill it with random numbers.
c := make([]complex128, m*ldc)
for i := range c {
c[i] = rndComplex128(rnd)
}
if nanC {
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
c[i+j*ldc] = cmplx.NaN()
}
}
}
// Compute the expected result using an internal Zgemm implementation.
var want []complex128
if side == blas.Left {
want = zmm(blas.NoTrans, blas.NoTrans, m, n, m, alpha, aHem, lda, b, ldb, beta, c, ldc)
} else {
want = zmm(blas.NoTrans, blas.NoTrans, m, n, n, alpha, b, ldb, aHem, lda, beta, c, ldc)
}
// Compute the result using Zhemm.
impl.Zhemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
prefix := fmt.Sprintf("m=%v,n=%v,lda=%v,ldb=%v,ldc=%v,alpha=%v,beta=%v", m, n, lda, ldb, ldc, alpha, beta)
if !zsame(a, aCopy) {
t.Errorf("%v: unexpected modification of A", prefix)
continue
}
if !zsame(b, bCopy) {
t.Errorf("%v: unexpected modification of B", prefix)
continue
}
if !zEqualApprox(c, want, tol) {
t.Errorf("%v: unexpected result", prefix)
}
}
}
}
}
}
}
}
| gonum/gonum | blas/testblas/zhemm.go | GO | bsd-3-clause | 4,172 |
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/v8_snapshot_writer.h"
#include "vm/dart.h"
#include "vm/os.h"
namespace dart {
const V8SnapshotProfileWriter::ObjectId
V8SnapshotProfileWriter::kArtificialRootId{IdSpace::kArtificial, 0};
#if defined(DART_PRECOMPILER)
V8SnapshotProfileWriter::V8SnapshotProfileWriter(Zone* zone)
: zone_(zone),
nodes_(zone_),
node_types_(zone_),
edge_types_(zone_),
strings_(zone_),
roots_(zone_) {
intptr_t idx = edge_types_.Add("context");
ASSERT_EQUAL(idx, static_cast<intptr_t>(Edge::Type::kContext));
idx = edge_types_.Add("element");
ASSERT_EQUAL(idx, static_cast<intptr_t>(Edge::Type::kElement));
idx = edge_types_.Add("property");
ASSERT_EQUAL(idx, static_cast<intptr_t>(Edge::Type::kProperty));
idx = edge_types_.Add("internal");
ASSERT_EQUAL(idx, static_cast<intptr_t>(Edge::Type::kInternal));
SetObjectTypeAndName(kArtificialRootId, "ArtificialRoot",
"<artificial root>");
}
void V8SnapshotProfileWriter::SetObjectTypeAndName(const ObjectId& object_id,
const char* type,
const char* name) {
ASSERT(type != nullptr);
NodeInfo* info = EnsureId(object_id);
const intptr_t type_index = node_types_.Add(type);
if (info->type != kInvalidString && info->type != type_index) {
FATAL("Attempting to assign mismatching type %s to node %s", type,
info->ToCString(this, zone_));
}
info->type = type_index;
// Don't overwrite any existing name.
if (info->name == kInvalidString) {
info->name = strings_.Add(name);
}
}
void V8SnapshotProfileWriter::AttributeBytesTo(const ObjectId& object_id,
size_t num_bytes) {
EnsureId(object_id)->self_size += num_bytes;
}
void V8SnapshotProfileWriter::AttributeReferenceTo(
const ObjectId& from_object_id,
const Reference& reference,
const ObjectId& to_object_id) {
ASSERT(reference.IsElement() ? reference.offset >= 0
: reference.name != nullptr);
EnsureId(to_object_id);
const Edge edge(this, reference);
EnsureId(from_object_id)->AddEdge(edge, to_object_id);
}
void V8SnapshotProfileWriter::AttributeDroppedReferenceTo(
const ObjectId& from_object_id,
const Reference& reference,
const ObjectId& to_object_id,
const ObjectId& replacement_object_id) {
ASSERT(to_object_id.IsArtificial());
ASSERT(!replacement_object_id.IsArtificial());
ASSERT(reference.IsElement() ? reference.offset >= 0
: reference.name != nullptr);
// The target node is added normally.
AttributeReferenceTo(from_object_id, reference, to_object_id);
EnsureId(replacement_object_id);
// Put the replacement node at an invalid offset or name that can still be
// associated with the real one. For offsets, this is the negative offset.
// For names, it's the name prefixed with ":replacement_".
Reference replacement_reference =
reference.IsElement() ? Reference::Element(-reference.offset)
: Reference::Property(OS::SCreate(
zone_, ":replacement_%s", reference.name));
const Edge replacement_edge(this, replacement_reference);
EnsureId(from_object_id)->AddEdge(replacement_edge, replacement_object_id);
}
bool V8SnapshotProfileWriter::HasId(const ObjectId& object_id) {
return nodes_.HasKey(object_id);
}
V8SnapshotProfileWriter::NodeInfo* V8SnapshotProfileWriter::EnsureId(
const ObjectId& object_id) {
if (!HasId(object_id)) {
nodes_.Insert(NodeInfo(this, object_id));
}
return nodes_.Lookup(object_id);
}
const char* V8SnapshotProfileWriter::NodeInfo::ToCString(
V8SnapshotProfileWriter* profile_writer,
Zone* zone) const {
JSONWriter writer;
WriteDebug(profile_writer, &writer);
return OS::SCreate(zone, "%s", writer.buffer()->buffer());
}
void V8SnapshotProfileWriter::NodeInfo::Write(
V8SnapshotProfileWriter* profile_writer,
JSONWriter* writer) const {
ASSERT(id.space() != IdSpace::kInvalid);
if (type == kInvalidString) {
FATAL("No type given for node %s", id.ToCString(profile_writer->zone_));
}
writer->PrintValue(type);
if (name != kInvalidString) {
writer->PrintValue(name);
} else {
ASSERT(profile_writer != nullptr);
// If we don't already have a name for the node, we lazily create a default
// one. This is safe since the strings table is written out after the nodes.
const intptr_t name = profile_writer->strings_.AddFormatted(
"Unnamed [%s] (nil)", profile_writer->node_types_.At(type));
writer->PrintValue(name);
}
id.Write(writer);
writer->PrintValue(self_size);
writer->PrintValue64(edges->Length());
}
void V8SnapshotProfileWriter::NodeInfo::WriteDebug(
V8SnapshotProfileWriter* profile_writer,
JSONWriter* writer) const {
writer->OpenObject();
if (type != kInvalidString) {
writer->PrintProperty("type", profile_writer->node_types_.At(type));
}
if (name != kInvalidString) {
writer->PrintProperty("name", profile_writer->strings_.At(name));
}
id.WriteDebug(writer, "id");
writer->PrintProperty("self_size", self_size);
edges->WriteDebug(profile_writer, writer, "edges");
writer->CloseObject();
}
const char* V8SnapshotProfileWriter::ObjectId::ToCString(Zone* zone) const {
JSONWriter writer;
WriteDebug(&writer);
return OS::SCreate(zone, "%s", writer.buffer()->buffer());
}
void V8SnapshotProfileWriter::ObjectId::Write(JSONWriter* writer,
const char* property) const {
if (property != nullptr) {
writer->PrintProperty64(property, encoded_);
} else {
writer->PrintValue64(encoded_);
}
}
void V8SnapshotProfileWriter::ObjectId::WriteDebug(JSONWriter* writer,
const char* property) const {
writer->OpenObject(property);
writer->PrintProperty("space", IdSpaceToCString(space()));
writer->PrintProperty64("nonce", nonce());
writer->CloseObject();
}
const char* V8SnapshotProfileWriter::ObjectId::IdSpaceToCString(IdSpace space) {
switch (space) {
case IdSpace::kInvalid:
return "Invalid";
case IdSpace::kSnapshot:
return "Snapshot";
case IdSpace::kVmText:
return "VmText";
case IdSpace::kIsolateText:
return "IsolateText";
case IdSpace::kVmData:
return "VmData";
case IdSpace::kIsolateData:
return "IsolateData";
case IdSpace::kArtificial:
return "Artificial";
default:
UNREACHABLE();
}
}
const char* V8SnapshotProfileWriter::EdgeMap::ToCString(
V8SnapshotProfileWriter* profile_writer,
Zone* zone) const {
JSONWriter writer;
WriteDebug(profile_writer, &writer);
return OS::SCreate(zone, "%s", writer.buffer()->buffer());
}
void V8SnapshotProfileWriter::EdgeMap::WriteDebug(
V8SnapshotProfileWriter* profile_writer,
JSONWriter* writer,
const char* property) const {
writer->OpenArray(property);
auto edge_it = GetIterator();
while (auto const pair = edge_it.Next()) {
pair->edge.WriteDebug(profile_writer, writer, pair->target);
}
writer->CloseArray();
}
void V8SnapshotProfileWriter::Edge::Write(
V8SnapshotProfileWriter* profile_writer,
JSONWriter* writer,
const ObjectId& target_id) const {
ASSERT(type != Type::kInvalid);
writer->PrintValue64(static_cast<intptr_t>(type));
writer->PrintValue64(name_or_offset);
auto const target = profile_writer->nodes_.LookupValue(target_id);
writer->PrintValue64(target.offset());
}
void V8SnapshotProfileWriter::Edge::WriteDebug(
V8SnapshotProfileWriter* profile_writer,
JSONWriter* writer,
const ObjectId& target_id) const {
writer->OpenObject();
if (type != Type::kInvalid) {
writer->PrintProperty(
"type", profile_writer->edge_types_.At(static_cast<intptr_t>(type)));
}
if (type == Type::kProperty) {
writer->PrintProperty("name", profile_writer->strings_.At(name_or_offset));
} else {
writer->PrintProperty64("offset", name_or_offset);
}
auto const target = profile_writer->nodes_.LookupValue(target_id);
target.id.WriteDebug(writer, "target");
writer->CloseObject();
}
void V8SnapshotProfileWriter::AddRoot(const ObjectId& object_id,
const char* name) {
// HeapSnapshotWorker.HeapSnapshot.calculateDistances (from HeapSnapshot.js)
// assumes that the root does not have more than one edge to any other node
// (most likely an oversight).
if (roots_.HasKey(object_id)) return;
roots_.Insert(object_id);
auto const str_index = strings_.Add(name);
auto const root = nodes_.Lookup(kArtificialRootId);
ASSERT(root != nullptr);
root->AddEdge(str_index != kInvalidString
? Edge(this, Edge::Type::kProperty, str_index)
: Edge(this, Edge::Type::kInternal, root->edges->Length()),
object_id);
}
intptr_t V8SnapshotProfileWriter::StringsTable::Add(const char* str) {
if (str == nullptr) return kInvalidString;
if (auto const kv = index_map_.Lookup(str)) {
return kv->value;
}
const char* new_str = OS::SCreate(zone_, "%s", str);
const intptr_t index = strings_.length();
strings_.Add(new_str);
index_map_.Insert({new_str, index});
return index;
}
intptr_t V8SnapshotProfileWriter::StringsTable::AddFormatted(const char* fmt,
...) {
va_list args;
va_start(args, fmt);
const char* str = OS::VSCreate(zone_, fmt, args);
va_end(args);
if (auto const kv = index_map_.Lookup(str)) {
return kv->value;
}
const intptr_t index = strings_.length();
strings_.Add(str);
index_map_.Insert({str, index});
return index;
}
const char* V8SnapshotProfileWriter::StringsTable::At(intptr_t index) const {
if (index > strings_.length()) return nullptr;
return strings_[index];
}
void V8SnapshotProfileWriter::StringsTable::Write(JSONWriter* writer,
const char* property) const {
writer->OpenArray(property);
for (auto const str : strings_) {
writer->PrintValue(str);
writer->PrintNewline();
}
writer->CloseArray();
}
void V8SnapshotProfileWriter::Write(JSONWriter* writer) {
writer->OpenObject();
writer->OpenObject("snapshot");
{
writer->OpenObject("meta");
{
writer->OpenArray("node_fields");
writer->PrintValue("type");
writer->PrintValue("name");
writer->PrintValue("id");
writer->PrintValue("self_size");
writer->PrintValue("edge_count");
writer->CloseArray();
}
{
writer->OpenArray("node_types");
node_types_.Write(writer);
writer->CloseArray();
}
{
writer->OpenArray("edge_fields");
writer->PrintValue("type");
writer->PrintValue("name_or_index");
writer->PrintValue("to_node");
writer->CloseArray();
}
{
writer->OpenArray("edge_types");
edge_types_.Write(writer);
writer->CloseArray();
}
writer->CloseObject();
writer->PrintProperty64("node_count", nodes_.Size());
{
intptr_t edge_count = 0;
auto nodes_it = nodes_.GetIterator();
while (auto const info = nodes_it.Next()) {
// All nodes should have an edge map, though it may be empty.
ASSERT(info->edges != nullptr);
edge_count += info->edges->Length();
}
writer->PrintProperty64("edge_count", edge_count);
}
}
writer->CloseObject();
{
writer->OpenArray("nodes");
// Always write the information for the artificial root first.
auto const root = nodes_.Lookup(kArtificialRootId);
ASSERT(root != nullptr);
intptr_t offset = 0;
root->set_offset(offset);
root->Write(this, writer);
offset += kNumNodeFields;
auto nodes_it = nodes_.GetIterator();
for (auto entry = nodes_it.Next(); entry != nullptr;
entry = nodes_it.Next()) {
if (entry->id == kArtificialRootId) continue;
entry->set_offset(offset);
entry->Write(this, writer);
offset += kNumNodeFields;
}
writer->CloseArray();
}
{
auto write_edges = [&](const NodeInfo& info) {
auto edges_it = info.edges->GetIterator();
while (auto const pair = edges_it.Next()) {
pair->edge.Write(this, writer, pair->target);
}
};
writer->OpenArray("edges");
// Always write the information for the artificial root first.
auto const root = nodes_.Lookup(kArtificialRootId);
ASSERT(root != nullptr);
write_edges(*root);
auto nodes_it = nodes_.GetIterator();
while (auto const entry = nodes_it.Next()) {
if (entry->id == kArtificialRootId) continue;
write_edges(*entry);
}
writer->CloseArray();
}
// Must happen after any calls to WriteNodeInfo, as those calls may add more
// strings.
strings_.Write(writer, "strings");
writer->CloseObject();
}
void V8SnapshotProfileWriter::Write(const char* filename) {
JSONWriter json;
Write(&json);
auto file_open = Dart::file_open_callback();
auto file_write = Dart::file_write_callback();
auto file_close = Dart::file_close_callback();
if ((file_open == nullptr) || (file_write == nullptr) ||
(file_close == nullptr)) {
OS::PrintErr("warning: Could not access file callbacks.");
return;
}
auto file = file_open(filename, /*write=*/true);
if (file == nullptr) {
OS::PrintErr("warning: Failed to write snapshot profile: %s\n", filename);
} else {
char* output = nullptr;
intptr_t output_length = 0;
json.Steal(&output, &output_length);
file_write(output, output_length, file);
free(output);
file_close(file);
}
}
#endif
} // namespace dart
| dart-lang/sdk | runtime/vm/v8_snapshot_writer.cc | C++ | bsd-3-clause | 14,028 |
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.PMD;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Match implements Comparable<Match> {
private int tokenCount;
private int lineCount;
private Set<TokenEntry> markSet = new TreeSet<TokenEntry>();
private String code;
private String label;
public static final Comparator<Match> MatchesComparator = new Comparator<Match>() {
public int compare(Match ma, Match mb) {
return mb.getMarkCount() - ma.getMarkCount();
}
};
public static final Comparator<Match> LinesComparator = new Comparator<Match>() {
public int compare(Match ma, Match mb) {
return mb.getLineCount() - ma.getLineCount();
}
};
public static final Comparator<Match> LabelComparator = new Comparator<Match>() {
public int compare(Match ma, Match mb) {
if (ma.getLabel() == null) {
return 1;
}
if (mb.getLabel() == null) {
return -1;
}
return mb.getLabel().compareTo(ma.getLabel());
}
};
public static final Comparator<Match> LENGTH_COMPARATOR = new Comparator<Match>() {
public int compare(Match ma, Match mb) {
return mb.getLineCount() - ma.getLineCount();
}
};
public Match(int tokenCount, TokenEntry first, TokenEntry second) {
markSet.add(first);
markSet.add(second);
this.tokenCount = tokenCount;
}
public int getMarkCount() {
return markSet.size();
}
public void setLineCount(int lineCount) {
this.lineCount = lineCount;
}
public int getLineCount() {
return this.lineCount;
}
public int getTokenCount() {
return this.tokenCount;
}
public String getSourceCodeSlice() {
return this.code;
}
public void setSourceCodeSlice(String code) {
this.code = code;
}
public Iterator<TokenEntry> iterator() {
return markSet.iterator();
}
public int compareTo(Match other) {
int diff = other.getTokenCount() - getTokenCount();
if (diff != 0) {
return diff;
}
return getFirstMark().getIndex() - other.getFirstMark().getIndex();
}
public TokenEntry getFirstMark() {
return getMark(0);
}
public TokenEntry getSecondMark() {
return getMark(1);
}
public String toString() {
return "Match: " + PMD.EOL + "tokenCount = " + tokenCount + PMD.EOL + "marks = " + markSet.size();
}
public Set<TokenEntry> getMarkSet() {
return markSet;
}
public int getEndIndex() {
return getMark(0).getIndex() + getTokenCount() - 1;
}
public void setMarkSet(Set<TokenEntry> markSet) {
this.markSet = markSet;
}
public void setLabel(String aLabel) {
label = aLabel;
}
public String getLabel() {
return label;
}
public void addTokenEntry(TokenEntry entry){
markSet.add(entry);
}
private TokenEntry getMark(int index) {
TokenEntry result = null;
int i = 0;
for (Iterator<TokenEntry> it = markSet.iterator(); it.hasNext() && i < index + 1; ){
result = it.next();
}
return result;
}
} | pscadiz/pmd-4.2.6-gds | src/net/sourceforge/pmd/cpd/Match.java | Java | bsd-3-clause | 3,478 |
// Copyright 2020 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.
const {assert} = chai;
import * as SurveyLink from '../../../../../front_end/ui/components/survey_link/survey_link.js';
import * as Common from '../../../../../front_end/core/common/common.js';
import {assertNotNullOrUndefined} from '../../../../../front_end/core/platform/platform.js';
import {assertShadowRoot, renderElementIntoDOM} from '../../helpers/DOMHelpers.js';
function canShowSuccessfulCallback(trigger: string, callback: SurveyLink.SurveyLink.CanShowSurveyCallback) {
callback({canShowSurvey: true});
}
function showSuccessfulCallback(trigger: string, callback: SurveyLink.SurveyLink.ShowSurveyCallback) {
callback({surveyShown: true});
}
function canShowFailureCallback(trigger: string, callback: SurveyLink.SurveyLink.CanShowSurveyCallback) {
callback({canShowSurvey: false});
}
function showFailureCallback(trigger: string, callback: SurveyLink.SurveyLink.ShowSurveyCallback) {
callback({surveyShown: false});
}
const empty = Common.UIString.LocalizedEmptyString;
describe('SurveyLink', async () => {
it('shows no link when canShowSurvey is still pending', () => {
const link = new SurveyLink.SurveyLink.SurveyLink();
link.data = {trigger: 'test trigger', promptText: empty, canShowSurvey: () => {}, showSurvey: () => {}};
renderElementIntoDOM(link);
assertShadowRoot(link.shadowRoot);
assert.strictEqual(link.shadowRoot.childElementCount, 0);
});
it('shows no link when canShowSurvey is false', () => {
const link = new SurveyLink.SurveyLink.SurveyLink();
link.data =
{trigger: 'test trigger', promptText: empty, canShowSurvey: canShowFailureCallback, showSurvey: () => {}};
renderElementIntoDOM(link);
assertShadowRoot(link.shadowRoot);
assert.strictEqual(link.shadowRoot.childElementCount, 0);
});
it('shows a link when canShowSurvey is true', () => {
const link = new SurveyLink.SurveyLink.SurveyLink();
link.data =
{trigger: 'test trigger', promptText: empty, canShowSurvey: canShowSuccessfulCallback, showSurvey: () => {}};
renderElementIntoDOM(link);
assertShadowRoot(link.shadowRoot);
const linkNode = link.shadowRoot.querySelector('button');
assert.isNotNull(linkNode);
});
it('shows a pending state when trying to show the survey', () => {
const link = new SurveyLink.SurveyLink.SurveyLink();
link.data =
{trigger: 'test trigger', promptText: empty, canShowSurvey: canShowSuccessfulCallback, showSurvey: () => {}};
renderElementIntoDOM(link);
assertShadowRoot(link.shadowRoot);
const linkNode = link.shadowRoot.querySelector('button');
assertNotNullOrUndefined(linkNode);
assert.notInclude(linkNode.textContent?.trim(), '…');
linkNode.click();
// The only output signal we have is the link text which we don't want to assert exactly, so we
// assume that the pending state has an elipsis.
const pendingLink = link.shadowRoot.querySelector('button');
assertNotNullOrUndefined(pendingLink);
assert.include(pendingLink.textContent?.trim(), '…');
});
it('shows a successful state after showing the survey', () => {
const link = new SurveyLink.SurveyLink.SurveyLink();
link.data = {
trigger: 'test trigger',
promptText: empty,
canShowSurvey: canShowSuccessfulCallback,
showSurvey: showSuccessfulCallback,
};
renderElementIntoDOM(link);
assertShadowRoot(link.shadowRoot);
const linkNode = link.shadowRoot.querySelector('button');
assertNotNullOrUndefined(linkNode);
linkNode.click();
const successLink = link.shadowRoot.querySelector('button');
assertNotNullOrUndefined(successLink);
assert.include(successLink.textContent?.trim(), 'Thank you');
});
it('shows a failure state when failing to show the survey', () => {
const link = new SurveyLink.SurveyLink.SurveyLink();
link.data = {
trigger: 'test trigger',
promptText: empty,
canShowSurvey: canShowSuccessfulCallback,
showSurvey: showFailureCallback,
};
renderElementIntoDOM(link);
assertShadowRoot(link.shadowRoot);
const linkNode = link.shadowRoot.querySelector('button');
assertNotNullOrUndefined(linkNode);
linkNode.click();
const successLink = link.shadowRoot.querySelector('button');
assertNotNullOrUndefined(successLink);
assert.include(successLink.textContent?.trim(), 'error');
});
});
| ChromeDevTools/devtools-frontend | test/unittests/front_end/ui/components/SurveyLink_test.ts | TypeScript | bsd-3-clause | 4,566 |
require 'spec_helper'
describe Spree::Promotion::Rules::OneUsePerUser do
let(:rule) { described_class.new }
describe '#eligible?(order)' do
subject { rule.eligible?(order) }
let(:order) { double Spree::Order, user: user }
let(:user) { double Spree::LegacyUser }
let(:promotion) { stub_model Spree::Promotion, used_by?: used_by }
let(:used_by) { false }
before { rule.promotion = promotion }
context 'when the order is assigned to a user' do
context 'when the user has used this promotion before' do
let(:used_by) { true }
it { should be false }
end
context 'when the user has not used this promotion before' do
it { should be true }
end
end
context 'when the order is not assigned to a user' do
let(:user) { nil }
it { should be false }
end
end
end
| Mayvenn/spree | core/spec/models/spree/promotion/rules/one_use_per_user_spec.rb | Ruby | bsd-3-clause | 862 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_PDF
* @subpackage Zend_PDF_Action
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @namespace
*/
namespace Zend\Pdf\Action;
/**
* PDF 'Updates the display of a document, using a transition dictionary' action
* PDF 1.5+ feature
*
* @uses \Zend\Pdf\Action\AbstractAction
* @package Zend_PDF
* @subpackage Zend_PDF_Action
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Trans extends AbstractAction
{
}
| Techlightenment/zf2 | library/Zend/Pdf/Action/Trans.php | PHP | bsd-3-clause | 1,177 |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import tempfile
import os
import unittest
from telemetry import benchmark
from telemetry.core import bitmap
from telemetry.core import util
# This is a simple base64 encoded 2x2 PNG which contains, in order, a single
# Red, Yellow, Blue, and Green pixel.
test_png = """
iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91
JpzAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACx
MBAJqcGAAAABZJREFUCNdj/M/AwPCfgYGB4T/DfwY
AHAAD/iOWZXsAAAAASUVORK5CYII=
"""
test_png_path = os.path.join(util.GetUnittestDataDir(), 'test_png.png')
test_png_2_path = os.path.join(util.GetUnittestDataDir(), 'test_png_2.png')
class HistogramDistanceTest(unittest.TestCase):
def testNoData(self):
hist1 = []
hist2 = []
self.assertRaises(
ValueError, lambda: bitmap.HistogramDistance(hist1, hist2))
hist1 = [0, 0, 0]
hist2 = [0, 0, 0]
self.assertRaises(
ValueError, lambda: bitmap.HistogramDistance(hist1, hist2))
def testWrongSizes(self):
hist1 = [1]
hist2 = [1, 0]
self.assertRaises(
ValueError, lambda: bitmap.HistogramDistance(hist1, hist2))
def testNoDistance(self):
hist1 = [2, 4, 1, 8, 0, -1]
hist2 = [2, 4, 1, 8, 0, -1]
self.assertEqual(bitmap.HistogramDistance(hist1, hist2), 0)
def testNormalizeCounts(self):
hist1 = [0, 0, 1, 0, 0]
hist2 = [0, 0, 0, 0, 7]
self.assertEqual(bitmap.HistogramDistance(hist1, hist2), 2)
self.assertEqual(bitmap.HistogramDistance(hist2, hist1), 2)
def testDistance(self):
hist1 = [2, 0, 1, 3, 4]
hist2 = [3, 1, 2, 4, 0]
self.assertEqual(bitmap.HistogramDistance(hist1, hist2), 1)
self.assertEqual(bitmap.HistogramDistance(hist2, hist1), 1)
hist1 = [0, 1, 3, 1]
hist2 = [2, 2, 1, 0]
self.assertEqual(bitmap.HistogramDistance(hist1, hist2), 1.2)
self.assertEqual(bitmap.HistogramDistance(hist2, hist1), 1.2)
class BitmapTest(unittest.TestCase):
# pylint: disable=C0324
def testReadFromBase64Png(self):
bmp = bitmap.Bitmap.FromBase64Png(test_png)
self.assertEquals(2, bmp.width)
self.assertEquals(2, bmp.height)
bmp.GetPixelColor(0, 0).AssertIsRGB(255, 0, 0)
bmp.GetPixelColor(1, 1).AssertIsRGB(0, 255, 0)
bmp.GetPixelColor(0, 1).AssertIsRGB(0, 0, 255)
bmp.GetPixelColor(1, 0).AssertIsRGB(255, 255, 0)
def testReadFromPngFile(self):
file_bmp = bitmap.Bitmap.FromPngFile(test_png_path)
self.assertEquals(2, file_bmp.width)
self.assertEquals(2, file_bmp.height)
file_bmp.GetPixelColor(0, 0).AssertIsRGB(255, 0, 0)
file_bmp.GetPixelColor(1, 1).AssertIsRGB(0, 255, 0)
file_bmp.GetPixelColor(0, 1).AssertIsRGB(0, 0, 255)
file_bmp.GetPixelColor(1, 0).AssertIsRGB(255, 255, 0)
def testWritePngToPngFile(self):
orig = bitmap.Bitmap.FromPngFile(test_png_path)
temp_file = tempfile.NamedTemporaryFile().name
orig.WritePngFile(temp_file)
new_file = bitmap.Bitmap.FromPngFile(temp_file)
self.assertTrue(orig.IsEqual(new_file))
@benchmark.Disabled
def testWriteCroppedBmpToPngFile(self):
pixels = [255,0,0, 255,255,0, 0,0,0,
255,255,0, 0,255,0, 0,0,0]
orig = bitmap.Bitmap(3, 3, 2, pixels)
orig.Crop(0, 0, 2, 2)
temp_file = tempfile.NamedTemporaryFile().name
orig.WritePngFile(temp_file)
new_file = bitmap.Bitmap.FromPngFile(temp_file)
self.assertTrue(orig.IsEqual(new_file))
def testIsEqual(self):
bmp = bitmap.Bitmap.FromBase64Png(test_png)
file_bmp = bitmap.Bitmap.FromPngFile(test_png_path)
self.assertTrue(bmp.IsEqual(file_bmp))
def testDiff(self):
file_bmp = bitmap.Bitmap.FromPngFile(test_png_path)
file_bmp_2 = bitmap.Bitmap.FromPngFile(test_png_2_path)
diff_bmp = file_bmp.Diff(file_bmp)
self.assertEquals(2, diff_bmp.width)
self.assertEquals(2, diff_bmp.height)
diff_bmp.GetPixelColor(0, 0).AssertIsRGB(0, 0, 0)
diff_bmp.GetPixelColor(1, 1).AssertIsRGB(0, 0, 0)
diff_bmp.GetPixelColor(0, 1).AssertIsRGB(0, 0, 0)
diff_bmp.GetPixelColor(1, 0).AssertIsRGB(0, 0, 0)
diff_bmp = file_bmp.Diff(file_bmp_2)
self.assertEquals(3, diff_bmp.width)
self.assertEquals(3, diff_bmp.height)
diff_bmp.GetPixelColor(0, 0).AssertIsRGB(0, 255, 255)
diff_bmp.GetPixelColor(1, 1).AssertIsRGB(255, 0, 255)
diff_bmp.GetPixelColor(0, 1).AssertIsRGB(255, 255, 0)
diff_bmp.GetPixelColor(1, 0).AssertIsRGB(0, 0, 255)
diff_bmp.GetPixelColor(0, 2).AssertIsRGB(255, 255, 255)
diff_bmp.GetPixelColor(1, 2).AssertIsRGB(255, 255, 255)
diff_bmp.GetPixelColor(2, 0).AssertIsRGB(255, 255, 255)
diff_bmp.GetPixelColor(2, 1).AssertIsRGB(255, 255, 255)
diff_bmp.GetPixelColor(2, 2).AssertIsRGB(255, 255, 255)
@benchmark.Disabled
def testGetBoundingBox(self):
pixels = [0,0,0, 0,0,0, 0,0,0, 0,0,0,
0,0,0, 1,0,0, 1,0,0, 0,0,0,
0,0,0, 0,0,0, 0,0,0, 0,0,0]
bmp = bitmap.Bitmap(3, 4, 3, pixels)
box, count = bmp.GetBoundingBox(bitmap.RgbaColor(1, 0, 0))
self.assertEquals(box, (1, 1, 2, 1))
self.assertEquals(count, 2)
box, count = bmp.GetBoundingBox(bitmap.RgbaColor(0, 1, 0))
self.assertEquals(box, None)
self.assertEquals(count, 0)
@benchmark.Disabled
def testCrop(self):
pixels = [0,0,0, 1,0,0, 2,0,0, 3,0,0,
0,1,0, 1,1,0, 2,1,0, 3,1,0,
0,2,0, 1,2,0, 2,2,0, 3,2,0]
bmp = bitmap.Bitmap(3, 4, 3, pixels)
bmp.Crop(1, 2, 2, 1)
self.assertEquals(bmp.width, 2)
self.assertEquals(bmp.height, 1)
bmp.GetPixelColor(0, 0).AssertIsRGB(1, 2, 0)
bmp.GetPixelColor(1, 0).AssertIsRGB(2, 2, 0)
self.assertEquals(bmp.pixels, bytearray([1,2,0, 2,2,0]))
@benchmark.Disabled
def testHistogram(self):
pixels = [1,2,3, 1,2,3, 1,2,3, 1,2,3,
1,2,3, 8,7,6, 5,4,6, 1,2,3,
1,2,3, 8,7,6, 5,4,6, 1,2,3]
bmp = bitmap.Bitmap(3, 4, 3, pixels)
bmp.Crop(1, 1, 2, 2)
histogram = bmp.ColorHistogram()
for i in xrange(3):
self.assertEquals(sum(histogram[i]), bmp.width * bmp.height)
self.assertEquals(histogram.r[1], 0)
self.assertEquals(histogram.r[5], 2)
self.assertEquals(histogram.r[8], 2)
self.assertEquals(histogram.g[2], 0)
self.assertEquals(histogram.g[4], 2)
self.assertEquals(histogram.g[7], 2)
self.assertEquals(histogram.b[3], 0)
self.assertEquals(histogram.b[6], 4)
@benchmark.Disabled
def testHistogramIgnoreColor(self):
pixels = [1,2,3, 1,2,3, 1,2,3, 1,2,3,
1,2,3, 8,7,6, 5,4,6, 1,2,3,
1,2,3, 8,7,6, 5,4,6, 1,2,3]
bmp = bitmap.Bitmap(3, 4, 3, pixels)
histogram = bmp.ColorHistogram(ignore_color=bitmap.RgbaColor(1, 2, 3))
self.assertEquals(histogram.r[1], 0)
self.assertEquals(histogram.r[5], 2)
self.assertEquals(histogram.r[8], 2)
self.assertEquals(histogram.g[2], 0)
self.assertEquals(histogram.g[4], 2)
self.assertEquals(histogram.g[7], 2)
self.assertEquals(histogram.b[3], 0)
self.assertEquals(histogram.b[6], 4)
@benchmark.Disabled
def testHistogramIgnoreColorTolerance(self):
pixels = [1,2,3, 4,5,6,
7,8,9, 8,7,6]
bmp = bitmap.Bitmap(3, 2, 2, pixels)
histogram = bmp.ColorHistogram(ignore_color=bitmap.RgbaColor(0, 1, 2),
tolerance=1)
self.assertEquals(histogram.r[1], 0)
self.assertEquals(histogram.r[4], 1)
self.assertEquals(histogram.r[7], 1)
self.assertEquals(histogram.r[8], 1)
self.assertEquals(histogram.g[2], 0)
self.assertEquals(histogram.g[5], 1)
self.assertEquals(histogram.g[7], 1)
self.assertEquals(histogram.g[8], 1)
self.assertEquals(histogram.b[3], 0)
self.assertEquals(histogram.b[6], 2)
self.assertEquals(histogram.b[9], 1)
@benchmark.Disabled
def testHistogramDistanceIgnoreColor(self):
pixels = [1,2,3, 1,2,3,
1,2,3, 1,2,3]
bmp = bitmap.Bitmap(3, 2, 2, pixels)
hist1 = bmp.ColorHistogram(ignore_color=bitmap.RgbaColor(1, 2, 3))
hist2 = bmp.ColorHistogram()
self.assertEquals(hist1.Distance(hist2), 0)
| chromium2014/src | tools/telemetry/telemetry/core/bitmap_unittest.py | Python | bsd-3-clause | 8,155 |
<?php
/**
* This file is part of PHP Mess Detector.
*
* Copyright (c) Manuel Pichler <mapi@phpmd.org>.
* All rights reserved.
*
* Licensed under BSD License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @author Manuel Pichler <mapi@phpmd.org>
* @copyright Manuel Pichler. All rights reserved.
* @license https://opensource.org/licenses/bsd-license.php BSD License
* @link http://phpmd.org/
*/
class testRuleDoesNotApplyToSessionSuperGlobal
{
function testRuleDoesNotApplyToSessionSuperGlobal()
{
return $_SESSION;
}
}
| ravage84/phpmd | src/test/resources/files/Rule/UnusedLocalVariable/testRuleDoesNotApplyToSessionSuperGlobal.php | PHP | bsd-3-clause | 653 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/flow/texture_image.h"
#include "flutter/flow/open_gl.h"
#include "flutter/glue/trace_event.h"
#include "third_party/skia/include/gpu/gl/GrGLTypes.h"
namespace flow {
enum class TextureImageFormat {
Grey,
GreyAlpha,
RGB,
RGBA,
};
enum class TextureImageDataFormat {
UnsignedByte,
UnsignedShort565,
};
static inline GLint ToGLFormat(TextureImageFormat format) {
switch (format) {
case TextureImageFormat::RGBA:
return GL_RGBA;
case TextureImageFormat::RGB:
return GL_RGB;
case TextureImageFormat::Grey:
return GL_LUMINANCE;
case TextureImageFormat::GreyAlpha:
return GL_LUMINANCE_ALPHA;
}
return GL_NONE;
}
static inline GLint ToGLDataFormat(TextureImageDataFormat dataFormat) {
switch (dataFormat) {
case TextureImageDataFormat::UnsignedByte:
return GL_UNSIGNED_BYTE;
case TextureImageDataFormat::UnsignedShort565:
return GL_UNSIGNED_SHORT_5_6_5;
}
return GL_NONE;
}
static inline GrPixelConfig ToGrPixelConfig(TextureImageDataFormat dataFormat) {
switch (dataFormat) {
case TextureImageDataFormat::UnsignedByte:
return kRGBA_8888_GrPixelConfig;
case TextureImageDataFormat::UnsignedShort565:
return kRGB_565_GrPixelConfig;
}
return kUnknown_GrPixelConfig;
}
static inline SkColorType ToSkColorType(TextureImageFormat format) {
switch (format) {
case TextureImageFormat::RGBA:
return SkColorType::kRGBA_8888_SkColorType;
case TextureImageFormat::RGB:
case TextureImageFormat::Grey:
case TextureImageFormat::GreyAlpha:
// Add more specializations for greyscale images.
return SkColorType::kRGB_565_SkColorType;
}
return kRGB_565_SkColorType;
}
static sk_sp<SkImage> TextureImageCreate(GrContext* context,
TextureImageFormat format,
const SkISize& size,
TextureImageDataFormat dataFormat,
const uint8_t* data) {
TRACE_EVENT2("flutter", __func__, "width", size.width(), "height",
size.height());
if (!context)
return nullptr;
GLuint handle = GL_NONE;
// Generate the texture handle.
glGenTextures(1, &handle);
// Bind the texture.
glBindTexture(GL_TEXTURE_2D, handle);
// Specify default texture properties.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Update unpack alignment based on format.
glPixelStorei(GL_UNPACK_ALIGNMENT,
dataFormat == TextureImageDataFormat::UnsignedByte ? 4 : 2);
GLint gl_format = ToGLFormat(format);
// Upload the texture.
glTexImage2D(GL_TEXTURE_2D, // target
0, // level
gl_format, // internal format
size.fWidth, // width
size.fHeight, // height
0, // border
gl_format, // format
ToGLDataFormat(dataFormat), // format
data);
// Clear the binding. We are done.
glBindTexture(GL_TEXTURE_2D, GL_NONE);
// Flush the texture before it can be bound by another thread.
glFlush();
GrGLTextureInfo texInfo;
texInfo.fTarget = GL_TEXTURE_2D;
texInfo.fID = handle;
// Create an SkImage handle from the texture.
GrBackendTextureDesc desc;
desc.fOrigin = kTopLeft_GrSurfaceOrigin;
desc.fFlags = kNone_GrBackendTextureFlag;
desc.fWidth = size.fWidth;
desc.fHeight = size.fHeight;
desc.fTextureHandle = reinterpret_cast<GrBackendObject>(&texInfo);
desc.fConfig = ToGrPixelConfig(dataFormat);
if (auto image = SkImage::MakeFromAdoptedTexture(context, desc)) {
// Texture handle was successfully adopted by the SkImage.
return image;
}
// We could not create an SkImage from the texture. Since it could not be
// adopted, delete the handle and return null.
glDeleteTextures(1, &handle);
return nullptr;
}
static sk_sp<SkImage> TextureImageCreate(GrContext* context,
const SkBitmap& bitmap) {
if (context == nullptr) {
return nullptr;
}
if (bitmap.drawsNothing()) {
return nullptr;
}
TextureImageDataFormat dataFormat = TextureImageDataFormat::UnsignedByte;
TextureImageFormat imageFormat = TextureImageFormat::RGBA;
switch (bitmap.colorType()) {
case kRGB_565_SkColorType:
dataFormat = TextureImageDataFormat::UnsignedShort565;
imageFormat = TextureImageFormat::RGB;
break;
case kRGBA_8888_SkColorType:
dataFormat = TextureImageDataFormat::UnsignedByte;
imageFormat = TextureImageFormat::RGBA;
break;
default:
// Add more as supported.
return nullptr;
}
return TextureImageCreate(
context, // context
imageFormat, // image format
SkISize::Make(bitmap.width(), bitmap.height()), // size
dataFormat, // data format
reinterpret_cast<const uint8_t*>(bitmap.getPixels()) // data
);
}
sk_sp<SkImage> TextureImageCreate(GrContext* context,
SkImageGenerator& generator) {
if (context == nullptr) {
return nullptr;
}
const SkImageInfo& info = generator.getInfo();
if (info.isEmpty()) {
return nullptr;
}
TextureImageFormat imageFormat = TextureImageFormat::RGBA;
bool preferOpaque = SkAlphaTypeIsOpaque(info.alphaType());
if (preferOpaque) {
imageFormat = TextureImageFormat::RGB;
}
auto preferredImageInfo =
SkImageInfo::Make(info.bounds().width(), // width
info.bounds().height(), // height
ToSkColorType(imageFormat), // color type
preferOpaque ? SkAlphaType::kOpaque_SkAlphaType
: SkAlphaType::kPremul_SkAlphaType);
SkBitmap bitmap;
{
TRACE_EVENT1("flutter", "DecodePrimaryPreferrence", "Type",
preferOpaque ? "RGB565" : "RGBA8888");
// Try our preferred config.
if (generator.tryGenerateBitmap(&bitmap, preferredImageInfo, nullptr)) {
// Our got our preferred bitmap.
return TextureImageCreate(context, bitmap);
}
}
{
TRACE_EVENT0("flutter", "DecodeRecommended");
// Try the guessed config.
if (generator.tryGenerateBitmap(&bitmap)) {
return TextureImageCreate(context, bitmap);
}
}
return nullptr;
}
} // namespace flow
| mpcomplete/engine | flow/texture_image_gles2.cc | C++ | bsd-3-clause | 7,038 |
/*
* Tangram
* Copyright 2009 Baidu Inc. All rights reserved.
*/
///import baidu.array;
///import baidu.array.indexOf;
/**
* 判断一个数组中是否包含给定元素
* @name baidu.array.contains
* @function
* @grammar baidu.array.contains(source, obj)
* @param {Array} source 需要判断的数组.
* @param {Any} obj 要查找的元素.
* @return {boolean} 判断结果.
* @author berg
*/
baidu.array.contains = function(source, obj) {
return (baidu.array.indexOf(source, obj) >= 0);
};
| BaiduFE/Tangram-base | src/baidu/array/contains.js | JavaScript | bsd-3-clause | 511 |
/**
* Copyright (c) 2014, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.ucla.wise.admin;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import edu.ucla.wise.client.web.WiseHttpRequestParameters;
/**
* XsltViewServlet is a class used when user tries to print an overview list of
* the pages in a survey
*
*/
public class XsltViewServlet extends HttpServlet {
public static final Logger LOGGER = Logger.getLogger(XsltViewServlet.class);
static final long serialVersionUID = 1000;
/**
* Generates an xslt version of the survey.
*
* @param req
* HTTP Request.
* @param res
* HTTP Response.
* @throws ServletException
* and IOException.
*/
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
/* get information from java session */
String path = request.getContextPath();
HttpSession session = request.getSession(true);
if (session.isNew()) {
response.sendRedirect(path + "/index.htm");
return;
}
String surveyName = request.getParameter("FileName");
WiseHttpRequestParameters parameters = new WiseHttpRequestParameters(request);
/* check if the session is still valid */
AdminUserSession adminUserSession = parameters.getAdminUserSessionFromHttpSession();
if ((surveyName == null) || (adminUserSession == null)) {
LOGGER.error("Wise Admin - XSLT View Error: can't get the admin info", null);
return;
}
/* get the file xml and processor xslt */
String fXml = adminUserSession.getStudyXmlPath() + surveyName;
String fXslt = "/CME/WISE_pages/style/survey_all_pg.xslt";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(fXml);
/* use a Transformer for output */
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(fXslt));
/* reserve the DOCTYPE setting in XML file */
if (document.getDoctype() != null) {
String systemValue = (new File(document.getDoctype().getSystemId())).getName();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemValue);
}
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(response.getOutputStream());
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
System.out.println(" " + e.getMessage());
LOGGER.error("Wise Admin - XSLT View Error: " + e.getMessage(), e);
} catch (SAXException e) {
System.out.println(" " + e.getMessage());
LOGGER.error("Wise Admin - XSLT View Error: " + e.getMessage(), e);
} catch (TransformerConfigurationException e) {
System.out.println(" " + e.getMessage());
LOGGER.error("Wise Admin - XSLT View Error: " + e.getMessage(), e);
} catch (TransformerException e) {
System.out.println(" " + e.getMessage());
LOGGER.error("Wise Admin - XSLT View Error: " + e.getMessage(), e);
}
}
}
| ctsidev/SecureWise | wise/src/edu/ucla/wise/admin/XsltViewServlet.java | Java | bsd-3-clause | 5,893 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
MAST Utils
==========
Miscellaneous functions used throughout the MAST module.
"""
import numpy as np
import requests
import json
from urllib import parse
import astropy.coordinates as coord
from ..version import version
from ..exceptions import ResolverError, InvalidQueryError
from ..utils import commons
from . import conf
__all__ = []
def parse_type(dbtype):
"""
Takes a data type as returned by a database call and regularizes it into a
triplet of the form (human readable datatype, python datatype, default value).
Parameters
----------
dbtype : str
A data type, as returned by a database call (ex. 'char').
Returns
-------
response : tuple
Regularized type tuple of the form (human readable datatype, python datatype, default value).
For example:
_parse_type("short")
('integer', np.int64, -999)
"""
dbtype = dbtype.lower()
return {
'char': ('string', str, ""),
'string': ('string', str, ""),
'datetime': ('string', str, ""), # TODO: handle datetimes correctly
'date': ('string', str, ""), # TODO: handle datetimes correctly
'double': ('float', np.float64, np.nan),
'float': ('float', np.float64, np.nan),
'decimal': ('float', np.float64, np.nan),
'int': ('integer', np.int64, -999),
'short': ('integer', np.int64, -999),
'long': ('integer', np.int64, -999),
'number': ('integer', np.int64, -999),
'boolean': ('boolean', bool, None),
'binary': ('boolean', bool, None),
'unsignedbyte': ('byte', np.ubyte, -999)
}.get(dbtype, (dbtype, dbtype, dbtype))
def _simple_request(url, params):
"""
Light wrapper on requests.session().get basically to make monkey patched testing easier/more effective.
"""
session = requests.session()
headers = {"User-Agent": "astroquery/{} {}".format(version, session.headers['User-Agent']),
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
response = requests.get(url, params=params, headers=headers)
response.raise_for_status()
return response
def resolve_object(objectname):
"""
Resolves an object name to a position on the sky.
Parameters
----------
objectname : str
Name of astronomical object to resolve.
Returns
-------
response : `~astropy.coordinates.SkyCoord`
The sky position of the given object.
"""
request_args = {"service": "Mast.Name.Lookup",
"params": {'input': objectname, 'format': 'json'}}
request_string = 'request={}'.format(parse.quote(json.dumps(request_args)))
response = _simple_request("{}/api/v0/invoke".format(conf.server), request_string)
result = response.json()
if len(result['resolvedCoordinate']) == 0:
raise ResolverError("Could not resolve {} to a sky position.".format(objectname))
ra = result['resolvedCoordinate'][0]['ra']
dec = result['resolvedCoordinate'][0]['decl']
coordinates = coord.SkyCoord(ra, dec, unit="deg")
return coordinates
def parse_input_location(coordinates=None, objectname=None):
"""
Convenience function to parse user input of coordinates and objectname.
Parameters
----------
coordinates : str or `astropy.coordinates` object, optional
The target around which to search. It may be specified as a
string or as the appropriate `astropy.coordinates` object.
One and only one of coordinates and objectname must be supplied.
objectname : str, optional
The target around which to search, by name (objectname="M104")
or TIC ID (objectname="TIC 141914082").
One and only one of coordinates and objectname must be supplied.
Returns
-------
response : `~astropy.coordinates.SkyCoord`
The given coordinates, or object's location as an `~astropy.coordinates.SkyCoord` object.
"""
# Checking for valid input
if objectname and coordinates:
raise InvalidQueryError("Only one of objectname and coordinates may be specified.")
if not (objectname or coordinates):
raise InvalidQueryError("One of objectname and coordinates must be specified.")
if objectname:
obj_coord = resolve_object(objectname)
if coordinates:
obj_coord = commons.parse_coordinates(coordinates)
return obj_coord
def mast_relative_path(mast_uri):
"""
Given a MAST dataURI, return the associated relative path.
Parameters
----------
mast_uri : str
The MAST uri.
Returns
-------
response : str
The associated relative path.
"""
response = _simple_request("https://mast.stsci.edu/api/v0.1/path_lookup/",
{"uri": mast_uri})
result = response.json()
uri_result = result.get(mast_uri)
return uri_result["path"]
| imbasimba/astroquery | astroquery/mast/utils.py | Python | bsd-3-clause | 5,016 |
# Generated by Django 2.2.5 on 2020-08-03 10:37
import django.core.files.storage
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_dataprovider_attribute_class'),
('tasks', '0005_dataprovidertaskrecord_preview'),
]
operations = [
migrations.AddField(
model_name='dataprovidertaskrecord',
name='provider',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='task_record_providers', to='jobs.DataProvider'),
),
migrations.AlterField(
model_name='exportrun',
name='deleted',
field=models.BooleanField(db_index=True, default=False),
),
migrations.CreateModel(
name='RunZipFile',
fields=[
('created_at', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
('updated_at', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
('started_at', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
('finished_at', models.DateTimeField(editable=False, null=True)),
('id', models.AutoField(editable=False, primary_key=True, serialize=False)),
('uid', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, unique=True)),
('data_provider_task_records', models.ManyToManyField(to='tasks.DataProviderTaskRecord')),
('downloadable_file', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='tasks.FileProducingTaskResult')),
('run', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='zip_files', to='tasks.ExportRun')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ExportRunFile',
fields=[
('created_at', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
('updated_at', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
('id', models.AutoField(editable=False, primary_key=True, serialize=False)),
('uid', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, unique=True)),
('file', models.FileField(storage=django.core.files.storage.FileSystemStorage(base_url='/export_run_files/', location='/var/lib/eventkit/exports_stage/export_run_files'), upload_to='', verbose_name='File')),
('directory', models.CharField(blank=True, help_text='An optional directory name to store the file in.', max_length=100, null=True)),
('provider', models.ForeignKey(blank=True, help_text='An optional data provider to associate the file with.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='file_provider', to='jobs.DataProvider')),
],
options={
'abstract': False,
},
),
]
| venicegeo/eventkit-cloud | eventkit_cloud/tasks/migrations/0006_auto_20200803_1037.py | Python | bsd-3-clause | 3,280 |
package org.petuum.jbosen.common.msg;
public class MsgType {
public static final int CLIENT_CONNECT = 0;
public static final int SERVER_CONNECT = 1;
public static final int ROW_REQUEST = 2;
public static final int ROW_REQUEST_REPLY = 3;
public static final int SERVER_ROW_REQUEST_REPLY = 4;
public static final int BG_CLOCK = 5;
public static final int BG_SEND_OP_LOG = 6;
public static final int CLIENT_SEND_OP_LOG = 7;
public static final int CONNECT_SERVER = 8;
public static final int CLIENT_START = 9;
public static final int WORKER_THREAD_REG = 10;
public static final int WORKER_THREAD_REG_REPLY = 11;
public static final int WORKER_THREAD_DEREG = 12;
public static final int CLIENT_SHUT_DOWN = 13;
public static final int SERVER_SHUTDOWN_ACK = 14;
public static final int SERVER_PUSH_ROW = 15;
public static final int GLOBAL_BARRIER = 16;
public static final int GLOBAL_BARRIER_REPLY = 17;
}
| codeaudit/jbosen | jbosen/src/main/java/org/petuum/jbosen/common/msg/MsgType.java | Java | bsd-3-clause | 973 |
<?php
// phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
// phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
class QualityNominationTest extends \OmegaUp\Test\ControllerTestCase {
public function setUp(): void {
parent::setUp();
\OmegaUp\Test\Factories\QualityNomination::initQualityReviewers();
\OmegaUp\Test\Factories\QualityNomination::initTopicTags();
}
/**
* A PHPUnit data provider for all the tests that can accept a status.
*
* @return list<array{0: string, 1: int}>
*/
public function qualityNominationsDemotionStatusProvider(): array {
return [
['banned', \OmegaUp\ProblemParams::VISIBILITY_PUBLIC_BANNED],
['warning', \OmegaUp\ProblemParams::VISIBILITY_PUBLIC_WARNING],
];
}
public function testGetNominationsHasAuthorAndNominatorSet() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
$login = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
$response = \OmegaUp\Controllers\QualityNomination::apiList(new \OmegaUp\Request([
'auth_token' => $login->auth_token
]));
self::assertArrayHasKey('author', $response['nominations'][0]);
self::assertArrayHasKey('nominator', $response['nominations'][0]);
}
public function testGetByIdHasAuthorAndNominatorSet() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$result = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
$nomination = \OmegaUp\DAO\QualityNominations::getById(
$result['qualitynomination_id']
);
self::assertArrayHasKey('author', $nomination);
self::assertArrayHasKey('nominator', $nomination);
self::assertEquals(
$identity->username,
$nomination['nominator']['username']
);
}
public function testApiDetailsReturnsFieldsRequiredByUI() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$contents = json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]);
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => $contents,
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$request = new \OmegaUp\Request(
[
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id']]
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails($request);
$this->assertEquals(
'demotion',
$details['nomination'],
'Should have set demotion'
);
$this->assertEquals(
$identity->username,
$details['nominator']['username'],
'Should have set user'
);
$this->assertEquals(
$problemData['request']['problem_alias'],
$details['problem']['alias'],
'Should have set problem'
);
$this::assertArrayHasKey('author', $details);
$this->assertEquals(
json_decode(
$contents,
true
),
$details['contents'],
'Should have set contents'
);
$this->assertEquals(
true,
$details['reviewer'],
'Should have set reviewer'
);
$this->assertEquals(
$qualitynomination['qualitynomination_id'],
$details['qualitynomination_id'],
'Should have set qualitynomination_id'
);
}
/**
* Basic test. Check that before nominating a problem for quality, the user
* must have solved it first.
*/
public function testMustSolveBeforeNominatingItForPromotion() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
$login = self::login($identity);
$r = new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'promotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'source' => 'omegaUp',
'tags' => [],
]),
]);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate($r);
$this->fail('Should not have been able to nominate the problem');
} catch (\OmegaUp\Exceptions\PreconditionFailedException $e) {
// still expected.
}
\OmegaUp\Test\Factories\Run::gradeRun($runData);
\OmegaUp\Controllers\QualityNomination::apiCreate($r);
$response = \OmegaUp\Controllers\QualityNomination::apiMyList(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
]));
$this->assertEquals(1, count($response['nominations']));
$nomination = $response['nominations'][0];
$this->assertEquals(
$problemData['request']['problem_alias'],
$nomination['problem']['alias']
);
$this->assertEquals(
$problemData['request']['problem_alias'],
$nomination['problem']['alias']
);
$this->assertEquals(
\OmegaUp\Controllers\QualityNomination::REVIEWERS_PER_NOMINATION,
count($nomination['votes'])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'qualitynomination_id' => $nomination['qualitynomination_id'],
]));
$this->assertEquals(
$identity->username,
$details['nominator']['username']
);
$this->assertNotNull($details['original_contents']);
}
/**
* Check if only a category tag is allowed for a nomination of
* type 'quality tag'.
*/
public function testCategoryTagOnQualityTagNomination() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevelAdvancedCompetitiveProgramming',
'tags' => ['problemTagFunctions', 'problemTagRecursion'],
]),
]));
$this->fail('The user must be a reviewer.');
} catch (\OmegaUp\Exceptions\ForbiddenAccessException $e) {
$this->assertEquals('userNotAllowed', $e->getMessage());
}
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevel',
'tags' => ['problemTagFunctions', 'problemTagRecursion'],
]),
]));
$this->fail('The tag should be one of the level tags group.');
} catch (\OmegaUp\Exceptions\InvalidParameterException $e) {
$this->assertEquals('parameterInvalid', $e->getMessage());
}
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevelAdvancedCompetitiveProgramming',
'tags' => ['problemTopic'],
]),
]));
$this->fail('The tag should be one of the public tags group.');
} catch (\OmegaUp\Exceptions\InvalidParameterException $e) {
$this->assertEquals('parameterInvalid', $e->getMessage());
}
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevelAdvancedCompetitiveProgramming',
]),
]));
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevelAdvancedCompetitiveProgramming',
]),
]));
$this->fail(
'Reviewer can not send again a nomination for the same problem'
);
} catch (\Omegaup\Exceptions\PreconditionFailedException $e) {
$this->assertEquals(
'qualityNominationReviewerHasAlreadySentNominationForProblem',
$e->getMessage()
);
}
}
/**
* Check that before suggesting improvements to a problem, the user must
* have solved it first.
*/
public function testMustSolveBeforeSuggesting() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
$login = self::login($identity);
$r = new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'suggestion',
'contents' => json_encode([
// No difficulty!
'quality' => 3,
'tags' => [],
]),
]);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate($r);
$this->fail(
'Should not have been able to make suggestion about the problem'
);
} catch (\OmegaUp\Exceptions\PreconditionFailedException $e) {
// still expected.
}
\OmegaUp\Test\Factories\Run::gradeRun($runData);
$response = \OmegaUp\Controllers\QualityNomination::apiCreate($r);
$r['qualitynomination_id'] = $response['qualitynomination_id'];
$nomination = \OmegaUp\Controllers\QualityNomination::apiDetails($r);
$this->assertEquals(
$problemData['request']['problem_alias'],
$nomination['problem']['alias']
);
}
/**
* Basic test. Check that before nominating a problem for demotion, the
* user might not have solved it first.
*/
public function testNominatingForDemotion() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
}
public function testExtractAliasFromArgument() {
$inputAndExpectedOutput =
['http://localhost:8001/arena/prueba/#problems/sumas' => 'sumas',
'http://localhost:8001/arena/prueba/practice/#problems/sumas' => 'sumas',
'http://localhost:8001/arena/problem/sumas#problems' => 'sumas',
'http://localhost:8001/course/prueba/assignment/prueba/#problems/sumas' => 'sumas',
'http://localhost:8001/arena/prueba/#problems/sumas29187' => 'sumas29187',
'http://localhost:8001/arena/prueba/practice/#problems/sumas_29187' => 'sumas_29187',
'http://localhost:8001/arena/problem/_sumas29187-#problems' => '_sumas29187-',
'http://localhost:8001/course/prueba/assignment/prueba/#problems/___asd_-_23-2-_' => '___asd_-_23-2-_'];
foreach ($inputAndExpectedOutput as $input => $expectedOutput) {
$actualOutput = \OmegaUp\Controllers\QualityNomination::extractAliasFromArgument(
$input
);
$this->assertEquals(
$expectedOutput,
$actualOutput,
'Incorrect alias was extracted from URL.'
);
}
}
/**
* Check that a non-reviewer user cannot change the status of a demotion qualitynomination.
* @dataProvider qualityNominationsDemotionStatusProvider
*/
public function testDemotionCannotBeResolvedByRegularUser(string $status) {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
try {
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'status' => $status,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew plus something else'
])
);
$this->fail("Normal user shouldn't be able to resolve demotion");
} catch (\OmegaUp\Exceptions\ForbiddenAccessException $e) {
// Expected.
}
}
/**
* Check that a demotion can be banned or warning and then reverted by a reviewer.
* @dataProvider qualityNominationsDemotionStatusProvider
*/
public function testDemotionCanBeResolvedAndLaterRevertedByReviewer(
string $status,
int $visibility
) {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew plus something else',
])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
]));
$this->assertEquals(
$status,
$details['nomination_status'],
"qualitynomination should have been marked as {$status}"
);
$problem = \OmegaUp\Controllers\Problem::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
]));
$this->assertEquals(
$visibility,
$problem['visibility'],
"Problem should have been public {$status}"
);
// Revert ban.
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => 'resolved',
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew'
])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
]));
$this->assertEquals(
'resolved',
$details['nomination_status'],
'qualitynomination should have been marked as resolved'
);
$problem = \OmegaUp\Controllers\Problem::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
]));
$this->assertEquals(
\OmegaUp\ProblemParams::VISIBILITY_PUBLIC,
$problem['visibility'],
'Problem should have been made public'
);
}
/**
* Check that multiple demotion can be banned or warning and then reverted by a reviewer.
* @dataProvider qualityNominationsDemotionStatusProvider
*/
public function testMultipleDemotionCanBeResolvedAndLaterRevertedByReviewer(
string $status,
int $visibility
) {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
$qualitynomination1 = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew plus something else',
'all' => true,
])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
]));
$this->assertEquals(
$status,
$details['nomination_status'],
"qualitynomination should have been marked as {$status}"
);
$details1 = \OmegaUp\Controllers\QualityNomination::apiDetails(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination1['qualitynomination_id'],
])
);
$this->assertEquals(
$status,
$details1['nomination_status'],
"qualitynomination should have been marked as {$status}"
);
$problem = \OmegaUp\Controllers\Problem::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
]));
$this->assertEquals(
$visibility,
$problem['visibility'],
"Problem should have been public {$status}"
);
// Revert ban.
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => 'resolved',
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew',
'all' => true,
])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
]));
$this->assertEquals(
'resolved',
$details['nomination_status'],
'qualitynomination should have been marked as resolved'
);
$details1 = \OmegaUp\Controllers\QualityNomination::apiDetails(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination1['qualitynomination_id'],
])
);
$this->assertEquals(
'resolved',
$details1['nomination_status'],
'qualitynomination should have been marked as resolved'
);
$problem = \OmegaUp\Controllers\Problem::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
]));
$this->assertEquals(
\OmegaUp\ProblemParams::VISIBILITY_PUBLIC,
$problem['visibility'],
'Problem should have been made public'
);
}
/**
* Check that a demotion banned or warning by a reviewer sends an email to the problem creator.
* @dataProvider qualityNominationsDemotionStatusProvider
*/
public function testDemotionResolvedByReviewerAndSendMail(string $status) {
$emailSender = new \OmegaUp\Test\FakeEmailSender();
$scopedSender = new \OmegaUp\Test\ScopedEmailSender($emailSender);
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'qwert',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'qwert plus something else'
])
);
$this->assertCount(1, $emailSender->listEmails);
$this->assertStringContainsString(
$problemData['problem']->title,
$emailSender->listEmails[0]['subject']
);
$this->assertStringContainsString(
$problemData['author']->name,
$emailSender->listEmails[0]['body']
);
$this->assertStringContainsString(
'qwert',
$emailSender->listEmails[0]['body']
);
$this->assertStringContainsString(
'something else',
$emailSender->listEmails[0]['body']
);
}
/**
* Check that a multiple demotion banned or warning by a reviewer sends an email to the problem creator.
* @dataProvider qualityNominationsDemotionStatusProvider
*/
public function testMultipleDemotionResolvedByReviewerAndSendMail(string $status) {
$emailSender = new \OmegaUp\Test\FakeEmailSender();
$scopedSender = new \OmegaUp\Test\ScopedEmailSender($emailSender);
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'qwert',
'reason' => 'offensive',
]),
]));
$qualitynomination1 = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'qwert',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'qwert plus something else',
'all' => true,
])
);
$this->assertCount(1, $emailSender->listEmails);
$this->assertStringContainsString(
$problemData['problem']->title,
$emailSender->listEmails[0]['subject']
);
$this->assertStringContainsString(
$problemData['author']->name,
$emailSender->listEmails[0]['body']
);
$this->assertStringContainsString(
'qwert',
$emailSender->listEmails[0]['body']
);
$this->assertStringContainsString(
'something else',
$emailSender->listEmails[0]['body']
);
}
/**
* Check that a demotion's logs is saved correctly.
* @dataProvider qualityNominationsDemotionStatusProvider
*/
public function testDemotionLogsSavedCorrectly(
string $status,
int $visibility
) {
['identity' => $author] = \OmegaUp\Test\Factories\User::createUser(new \OmegaUp\Test\Factories\UserParams(
[
'username' => 'user_test_author'
]
));
$problemData = \OmegaUp\Test\Factories\Problem::createProblem(new \OmegaUp\Test\Factories\ProblemParams(
[
'author' => $author,
'title' => 'problem_1'
]
));
['identity' => $nominator] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($nominator);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$rationale = 'rationale';
\OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => $rationale,
])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
]));
$this->assertEquals($rationale, $details['contents']['rationale']);
$logs = \OmegaUp\DAO\QualityNominationLog::getAllLogsForNomination(
$qualitynomination['qualitynomination_id']
);
$this->assertCount(1, $logs);
$this->assertEquals(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]->user_id,
$logs[0]->user_id
);
$this->assertEquals('open', $logs[0]->from_status);
$this->assertEquals($status, $logs[0]->to_status);
$this->assertEquals($rationale, $logs[0]->rationale);
// Revert ban.
$rationale = 'problem solved';
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => 'resolved',
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => $rationale
])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
]));
$this->assertEquals($rationale, $details['contents']['rationale']);
$logs = \OmegaUp\DAO\QualityNominationLog::getAllLogsForNomination(
$qualitynomination['qualitynomination_id']
);
$this->assertCount(2, $logs);
$this->assertEquals(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]->user_id,
$logs[1]->user_id
);
$this->assertEquals($status, $logs[1]->from_status);
$this->assertEquals('resolved', $logs[1]->to_status);
$this->assertEquals($rationale, $logs[1]->rationale);
}
/**
* Check that a demotion can be resolved by a reviewer.
*/
public function testDemotionCanBeBannedByReviewer() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem(new \OmegaUp\Test\Factories\ProblemParams([
'visibility' => 'public'
]));
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and deny ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$request = new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => 'resolved',
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew'
]);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
$request
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails($request);
$this->assertEquals(
'resolved',
$details['nomination_status'],
'qualitynomination should have been marked as resolved'
);
$problem = \OmegaUp\Controllers\Problem::apiDetails($request);
$this->assertEquals(
\OmegaUp\ProblemParams::VISIBILITY_PUBLIC,
$problem['visibility'],
'Problem should have remained public'
);
}
/**
* A PHPUnit data provider for all the tests that can accept a column for search nominations.
*
* @return list<array{0: string, 1:string, 2: int}>
*/
public function qualityNominationsDemotionSearchColumnsProvider(): array {
return [
['problem_alias', 'problem_1', 1],
['author_username', 'user_test_author', 1],
['nominator_username', 'user_test_nominator',1],
['nominator_username', 'invalid_user_test_nominator', 0],
];
}
/**
* Check that can search nominations.
* @dataProvider qualityNominationsDemotionSearchColumnsProvider
*/
public function testSearchNominations(
string $column,
string $query,
int $valueExpected
) {
['identity' => $author] = \OmegaUp\Test\Factories\User::createUser(new \OmegaUp\Test\Factories\UserParams(
[
'username' => 'user_test_author'
]
));
$problemData = \OmegaUp\Test\Factories\Problem::createProblem(new \OmegaUp\Test\Factories\ProblemParams(
[
'author' => $author,
'title' => 'problem_1'
]
));
['identity' => $identity] = \OmegaUp\Test\Factories\User::createUser(new \OmegaUp\Test\Factories\UserParams(
[
'username' => 'user_test_nominator'
]
));
$login = self::login($identity);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'qwert',
'reason' => 'offensive',
]),
]));
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$response = \OmegaUp\Controllers\QualityNomination::apiList(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
])
);
$this->assertCount(1, $response['nominations']);
// Search for $column
$response = \OmegaUp\Controllers\QualityNomination::apiList(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'query' => $query,
'column' => $column
])
);
$this->assertCount($valueExpected, $response['nominations']);
}
/**
* @dataProvider qualityNominationsDemotionStatusProvider
* Check that a demotion can be banned and then reopned by a reviewer.
*/
public function testDemotionCanBeResolvedAndThenReopenedByReviewer(
$status,
$visibility
) {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$request = new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew plus something else'
]);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
$request
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails($request);
$this->assertEquals(
$status,
$details['nomination_status'],
'qualitynomination should have been marked as banned'
);
$problem = \OmegaUp\Controllers\Problem::apiDetails($request);
$this->assertEquals(
$visibility,
$problem['visibility'],
"Problem should have been public {$status}"
);
// Reopen demotion request.
$request = new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => 'open',
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew'
]);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
$request
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails($request);
$this->assertEquals(
'open',
$details['nomination_status'],
'qualitynomination should have been re-opened'
);
$problem = \OmegaUp\Controllers\Problem::apiDetails($request);
$this->assertEquals(
$visibility,
$problem['visibility'],
"Problem should have remained public {$status}"
);
}
/**
* Check that a demotion of a private problem can be banned and
* then resolved, and it keeps its original visibility
* @dataProvider qualityNominationsDemotionStatusProvider
*/
public function testDemotionOfPrivateProblemResolvedAndThenBannedKeepsItsOriginalVisibility(
string $status,
int $visibility
) {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem(new \OmegaUp\Test\Factories\ProblemParams([
'visibility' => 'private'
]));
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$request = new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew plus something else'
]);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
$request
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails($request);
$this->assertEquals(
$status,
$details['nomination_status'],
"qualitynomination should have been marked as {$status}"
);
$problem = \OmegaUp\Controllers\Problem::apiDetails($request);
$this->assertEquals(
// To transform from public to private (banned or warning).
$visibility == \OmegaUp\ProblemParams::VISIBILITY_PUBLIC_BANNED ? \OmegaUp\ProblemParams::VISIBILITY_PRIVATE_BANNED : \OmegaUp\ProblemParams::VISIBILITY_PRIVATE_WARNING,
$problem['visibility'],
'Problem should have been private resolved'
);
// Reopen demotion request.
$request = new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => 'resolved',
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew'
]);
$response = \OmegaUp\Controllers\QualityNomination::apiResolve(
$request
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails($request);
$this->assertEquals(
'resolved',
$details['nomination_status'],
'qualitynomination should have been re-opened'
);
$problem = \OmegaUp\Controllers\Problem::apiDetails($request);
$this->assertEquals(
\OmegaUp\ProblemParams::VISIBILITY_PRIVATE,
$problem['visibility'],
'Problem should have been private'
);
}
/**
* User who tried a problem but couldn't solve it yet (non AC, CE, JE verdicts),
* should be able to send a dismissal or suggestion for it adding the before_ac
* flag on nomination contents.
*/
public function testBeforeAcNomination() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'suggestion',
'contents' => json_encode([
'quality' => 3,
'tags' => ['problemTopicGraphTheory', 'problemTopicGreedy', 'problemTopicBinarySearch'],
'before_ac' => true,
]),
]));
$this->fail('Must have tried to solve the problem first.');
} catch (\OmegaUp\Exceptions\PreconditionFailedException $e) {
$this->assertEquals(
$e->getMessage(),
'qualityNominationMustHaveTriedToSolveProblem'
);
}
// Now TRY to solve the problem
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
\OmegaUp\Test\Factories\Run::gradeRun($runData, 0, 'WA', 60);
$login = self::login($identity);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'suggestion',
'contents' => json_encode([
'quality' => 3,
'tags' => ['problemTopicGraphTheory', 'problemTopicGreedy'],
'before_ac' => true,
]),
]));
// Dismissals could be sent before AC also
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'dismissal',
'contents' => json_encode([
'before_ac' => true
]),
]));
// Now solve the problem, it must not be allowed to send a before AC
// nomination, as the problem is already solved
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
$login = self::login($identity);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'suggestion',
'contents' => json_encode([
'quality' => 3,
'tags' => ['problemTopicGreedy', 'problemTopicMath'],
'before_ac' => true,
]),
]));
$this->fail('Must not have solved the problem.');
} catch (\OmegaUp\Exceptions\PreconditionFailedException $e) {
$this->assertEquals(
$e->getMessage(),
'qualityNominationMustNotHaveSolvedProblem'
);
}
}
/**
* Check that before a duplicate nomination needs to have a valid original problem.
*/
public function testNominatingForDuplicate() {
$originalProblemData = \OmegaUp\Test\Factories\Problem::createProblem();
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'ew',
'reason' => 'duplicate',
]),
]));
$this->fail('Missing "original" should have been caught');
} catch (\OmegaUp\Exceptions\InvalidParameterException $e) {
// Expected.
}
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'otro sumas',
'reason' => 'duplicate',
'original' => '$invalid problem alias$',
]),
]));
$this->fail('Invalid "original" should have been caught');
} catch (\OmegaUp\Exceptions\NotFoundException $e) {
// Expected.
}
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'otro sumas',
'reason' => 'duplicate',
'original' => $originalProblemData['request']['problem_alias'],
]),
]));
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'otro sumas',
'reason' => 'duplicate',
'original' => 'https://omegaup.com/arena/problem/' . $originalProblemData['request']['problem_alias'] . '#problems',
]),
]));
}
/**
* Nomination list test.
*/
public function testNominationList() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
$login = self::login($identity);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'promotion',
'contents' => json_encode([
'rationale' => 'cool!',
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'source' => 'omegaUp',
'tags' => ['problemTopicSorting'],
]),
]));
// Login as an arbitrary reviewer.
$login = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$response = \OmegaUp\Controllers\QualityNomination::apiList(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
]));
$nomination = $this->findByPredicate(
$response['nominations'],
fn ($nomination) => $nomination['problem']['alias'] == $problemData['request']['problem_alias']
);
$this->assertNotNull($nomination);
$this->assertEquals(
\OmegaUp\Controllers\QualityNomination::REVIEWERS_PER_NOMINATION,
count($nomination['votes'])
);
// Login as one of the reviewers of that nomination.
$reviewer = $this->findByPredicate(
\OmegaUp\Test\Factories\QualityNomination::$reviewers,
fn ($reviewer) => $reviewer->username == $nomination['votes'][0]['user']['username']
);
$this->assertNotNull($reviewer);
$login = self::login($reviewer);
$response = \OmegaUp\Controllers\QualityNomination::apiMyAssignedList(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
]));
$this->assertArrayContainsWithPredicate(
$response['nominations'],
fn ($nomination) => $nomination['problem']['alias'] == $problemData['request']['problem_alias']
);
}
/**
* Duplicate tag test.
*/
public function testTagsForDuplicate() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
$login = self::login($identity);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'promotion',
'contents' => json_encode([
'rationale' => 'cool!',
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'source' => 'omegaUp',
'tags' => ['problemTopicSorting', 'problemTopicMath', 'problemTopicMath'],
]),
]));
$this->fail('Duplicate tags should be caught.');
} catch (\OmegaUp\Exceptions\DuplicatedEntryInArrayException $e) {
// Expected.
}
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'suggestion',
'contents' => json_encode([
// No difficulty!
'quality' => 3,
'tags' => ['problemTopicSorting', 'problemTopicMath', 'problemTopicMath'],
]),
]));
$this->fail('Duplicate tags should be caught.');
} catch (\OmegaUp\Exceptions\DuplicatedEntryInArrayException $e) {
// Expected.
}
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'promotion',
'contents' => json_encode([
'rationale' => 'cool!',
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'source' => 'omegaUp',
'tags' => ['problemTopicSorting', 'problemTopicMath'],
]),
]));
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'suggestion',
'contents' => json_encode([
// No difficulty!
'quality' => 3,
'tags' => ['problemTopicSorting', 'problemTopicMath'],
]),
]));
}
public function testIncorrectTag() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
$login = self::login($identity);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'promotion',
'contents' => json_encode([
'rationale' => 'cool!',
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'source' => 'omegaUp',
'tags' => ['ez', 'ez-pz'],
]),
]));
$this->fail('Incorrect tags should be caught.');
} catch (\OmegaUp\Exceptions\InvalidParameterException $e) {
// Expected.
}
try {
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'suggestion',
'contents' => json_encode([
// No difficulty!
'quality' => 3,
'tags' => ['ez', 'ez-pz'],
]),
]));
$this->fail('Incorrect tags should be caught.');
} catch (\OmegaUp\Exceptions\InvalidParameterException $e) {
// Expected.
}
}
/**
* Test that nomination list by default only shows promotions or demotions.
* All other nomination types should not appear on this list.
*/
public function testNominationListDoesntShowSuggestionsOrDismisssal() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
// Create promotion nomination.
$login = self::login($identity);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'promotion',
'contents' => json_encode([
'rationale' => 'cool!',
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'source' => 'omegaUp',
'tags' => ['problemTopicSorting'],
]),
]));
// Create demotion nomination.
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Create dismissal nomination.
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'dismissal',
'contents' => json_encode([]),
]));
// Create dismissal nomination.
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identity,
$problemData['request']['problem_alias'],
null,
1,
['problemTopicDynamicProgramming', 'problemTopicMath'],
false
);
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
$list = \OmegaUp\Controllers\QualityNomination::apiList(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
]));
$this->assertGreaterThanOrEqual(
2,
count(
$list['nominations']
),
"List didn't return enough nominations"
);
foreach ($list['nominations'] as $nomination) {
$isPromotion = ($nomination['nomination'] == 'promotion');
$isDemotion = ($nomination['nomination'] == 'demotion');
$this->assertTrue(
$isPromotion || $isDemotion,
'Found a nomination of type ' . $nomination['nomination'] . '. Only promotion and demotion should be shown.'
);
}
}
/**
* Check that before discard a problem, the user must
* have solved it first.
*/
public function testMustSolveBeforeDismissed() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
['user' => $contestant, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData,
$identity
);
$login = self::login($identity);
$r = new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'dismissal',
'contents' => json_encode([]),
]);
try {
\OmegaUp\Controllers\QualityNomination::apiCreate($r);
$this->fail('Should not have been able to dismissed the problem');
} catch (\OmegaUp\Exceptions\PreconditionFailedException $e) {
// Expected.
}
$problem = \OmegaUp\DAO\Problems::getByAlias($r['problem_alias']);
if (is_null($problem)) {
throw new \OmegaUp\Exceptions\NotFoundException('problemNotFound');
}
$problemDismissed = \OmegaUp\DAO\QualityNominations::getByUserAndProblem(
$r->user->user_id,
$problem->problem_id,
$r['nomination'],
json_encode([]), // re-encoding it for normalization.
'open'
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
try {
$this->assertEquals(
0,
count(
$problemDismissed
),
'Should not have been able to dismiss the problem'
);
} catch (\OmegaUp\Exceptions\PreconditionFailedException $e) {
// Expected.
}
try {
\OmegaUp\Controllers\QualityNomination::apiCreate($r);
$pd = \OmegaUp\DAO\QualityNominations::getByUserAndProblem(
$r->user->user_id,
$problem->problem_id,
$r['nomination'],
json_encode([]), // re-encoding it for normalization.
'open'
);
$this->assertGreaterThan(
0,
count(
$pd
),
'The problem should have been dismissed'
);
} catch (\OmegaUp\Exceptions\PreconditionFailedException $e) {
// Expected.
}
}
public function testGetGlobalDifficultyAndQuality() {
$problemData[0] = \OmegaUp\Test\Factories\Problem::createProblem();
$problemData[1] = \OmegaUp\Test\Factories\Problem::createProblem();
self::setUpSyntheticSuggestions($problemData);
$globalContents = \OmegaUp\DAO\QualityNominations::getAllNominations();
$actualGlobals = \OmegaUp\DAO\QualityNominations::calculateGlobalDifficultyAndQuality(
$globalContents
);
$expectedGlobals = [23 / 13 /*quality*/, 54 / 16 /*difficulty*/];
$this->assertEquals($expectedGlobals, $actualGlobals);
}
public function testGetSuggestionRowMap() {
$problemData[0] = \OmegaUp\Test\Factories\Problem::createProblem();
$problemData[1] = \OmegaUp\Test\Factories\Problem::createProblem();
self::setUpSyntheticSuggestions($problemData);
$contents[0] = \OmegaUp\DAO\QualityNominations::getAllSuggestionsPerProblem(
$problemData[0]['problem']->problem_id
);
$actualResult[0] = \OmegaUp\DAO\QualityNominations::calculateProblemSuggestionAggregates(
$contents[0]
);
$contents[1] = \OmegaUp\DAO\QualityNominations::getAllSuggestionsPerProblem(
$problemData[1]['problem']->problem_id
);
$actualResult[1] = \OmegaUp\DAO\QualityNominations::calculateProblemSuggestionAggregates(
$contents[1]
);
$expectedResult[0] = [
'quality_sum' => 13,
'quality_n' => 7,
'difficulty_sum' => 25,
'difficulty_n' => 7,
'tags_n' => 15,
'tags' => [
'problemTopicDynamicProgramming' => 6,
'problemTopicMath' => 6,
'problemTopicMatrices' => 1,
'problemTopicGreedy' => 2,
]
];
$expectedResult[1] = [
'quality_sum' => 10,
'quality_n' => 6,
'difficulty_sum' => 29,
'difficulty_n' => 9,
'tags_n' => 15,
'tags' => [
'problemTopicSorting' => 6,
'problemTopicGeometry' => 4,
'problemTopicMatrices' => 1,
'problemTopicMath' => 2,
'problemTopicDynamicProgramming' => 2,
],
];
$this->assertEquals($expectedResult, $actualResult);
}
/*
Creates 5 problems and 5 users.
- The first time the cronjob is executed, the problems are voted by
users as unranked users (with vote weight = 2)
- The second time, the problems are voted by ranked users according to
the number of problems they solved
*/
public function testAggregateFeedback() {
for ($i = 0; $i < 5; $i++) {
$problemData[$i] = \OmegaUp\Test\Factories\Problem::createProblem();
}
$userData = [];
$identityData = [];
for ($i = 0; $i < 5; $i++) {
['user' => $userData[$i], 'identity' => $identityData[$i]] = \OmegaUp\Test\Factories\User::createUser();
}
self::setUpRankForUsers($problemData, $identityData, true);
// Create and extra user and send a before_ac nomination
// that should not affect the current results.
$beforeACUser = \OmegaUp\Test\Factories\User::createUser();
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData[0],
$beforeACUser['identity']
);
\OmegaUp\Test\Factories\Run::gradeRun($runData, 0, 'WA');
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$beforeACUser['identity'],
$problemData[0]['request']['problem_alias'],
4, /* difficulty */
4, /* quality */
['problemTopicDynamicProgramming', 'problemTopicMath'],
true
);
\OmegaUp\Test\Utils::runAggregateFeedback();
$newProblem[0] = \OmegaUp\DAO\Problems::getByAlias(
$problemData[0]['request']['problem_alias']
);
$this->assertEqualsWithDelta(
2.971428571,
$newProblem[0]->difficulty,
0.001,
'Wrong difficulty.'
);
$this->assertEqualsWithDelta(
2.2,
$newProblem[0]->quality,
0.001,
'Wrong quality.'
);
$this->assertEquals(
'[0, 0, 2, 2, 1]',
$newProblem[0]->difficulty_histogram,
'Wrong difficulty histogram'
);
$this->assertEquals(
'[1, 1, 0, 1, 2]',
$newProblem[0]->quality_histogram,
'Wrong quality histogram'
);
$newProblem[2] = \OmegaUp\DAO\Problems::getByAlias(
$problemData[2]['request']['problem_alias']
);
$this->assertEqualsWithDelta(
0,
$newProblem[2]->difficulty,
0.001,
'Wrong difficulty'
);
$this->assertEqualsWithDelta(
0,
$newProblem[2]->quality,
0.001,
'Wrong quality'
);
$tagArrayForProblem1 = \OmegaUp\DAO\ProblemsTags::getProblemTags(
$newProblem[0],
false /* public_only */,
true /* includeVoted */
);
$tagArrayForProblem3 = \OmegaUp\DAO\ProblemsTags::getProblemTags(
$newProblem[2],
false /* public_only */,
true /* includeVoted */
);
$extractName = fn ($tag) => $tag['name'];
$tags1 = array_map($extractName, $tagArrayForProblem1);
$this->assertEqualsCanonicalizing(
$tags1,
[
'problemLevelBasicIntroductionToProgramming',
'problemRestrictedTagLanguage',
'problemTopicDynamicProgramming',
'problemTopicGreedy',
'problemTopicMath',
'problemTopicMatrices'
]
);
$tags3 = array_map($extractName, $tagArrayForProblem3);
$this->assertEqualsCanonicalizing(
$tags3,
[
'problemLevelBasicIntroductionToProgramming',
'problemRestrictedTagLanguage',
'problemTopicDynamicProgramming',
'problemTopicGreedy',
'problemTopicGeometry',
'problemTopicSorting'
]
);
\OmegaUp\Test\Utils::runUpdateRanks();
\OmegaUp\Test\Utils::runAggregateFeedback();
$newProblem[0] = \OmegaUp\DAO\Problems::getByAlias(
$problemData[0]['request']['problem_alias']
);
$this->assertEqualsWithDelta(
2.895384615,
$newProblem[0]->difficulty,
0.001,
'Wrong difficulty.'
);
$this->assertEqualsWithDelta(
2.538378378,
$newProblem[0]->quality,
0.001,
'Wrong quality.'
);
$newProblem[1] = \OmegaUp\DAO\Problems::getByAlias(
$problemData[1]['request']['problem_alias']
);
$this->assertEqualsWithDelta(
3.446886447,
$newProblem[1]->difficulty,
0.001,
'Wrong difficulty.'
);
$this->assertEqualsWithDelta(
0,
$newProblem[1]->quality,
0.001,
'Wrong quality.'
);
$newProblem[2] = \OmegaUp\DAO\Problems::getByAlias(
$problemData[2]['request']['problem_alias']
);
$this->assertEqualsWithDelta(
2.684981685,
$newProblem[2]->difficulty,
0.001,
'Wrong difficulty'
);
$this->assertEqualsWithDelta(
1.736164736,
$newProblem[2]->quality,
0.001,
'Wrong quality'
);
$tagArrayForProblem1 = \OmegaUp\DAO\ProblemsTags::getProblemTags(
$newProblem[0],
false /* public_only */,
true /* includeVoted */
);
$tagArrayForProblem3 = \OmegaUp\DAO\ProblemsTags::getProblemTags(
$newProblem[2],
false /* public_only */,
true /* includeVoted */
);
$tags1 = array_map($extractName, $tagArrayForProblem1);
$this->assertEqualsCanonicalizing(
$tags1,
[
'problemLevelBasicIntroductionToProgramming',
'problemTopicDynamicProgramming',
'problemTopicGreedy',
'problemTopicMath',
'problemRestrictedTagLanguage'
]
);
$tags3 = array_map($extractName, $tagArrayForProblem3);
$this->assertEqualsCanonicalizing(
$tags3,
[
'problemLevelBasicIntroductionToProgramming',
'problemTopicDynamicProgramming',
'problemTopicGreedy',
'problemTopicGeometry',
'problemTopicSorting',
'problemRestrictedTagLanguage'
]
);
}
/**
* Test if the problem's quality_seal sets to true after receiving
* the feedback of reviewers.
*/
public function testReviewersFeedbackPostive() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => true,
'tag' => 'problemLevelBasicKarel',
'tags' => ['problemTagBitManipulation', 'problemTagRecursion'],
]),
]));
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[1]
);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => true,
'tag' => 'problemLevelBasicKarel',
'tags' => ['problemTagBitManipulation', 'problemTagRecursion'],
]),
]));
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[2]
);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevelAdvancedSpecializedTopics',
]),
]));
\OmegaUp\Test\Utils::runAggregateFeedback();
$problem = \OmegaUp\DAO\Problems::getByPK(
$problemData['problem']->problem_id
);
$this->assertTrue($problem->quality_seal);
}
/**
* Test if the problem's quality_seal remains as false after receiving
* the feedback of reviewers.
*/
public function testReviewersFeedbackNegative() {
$problemData = \OmegaUp\Test\Factories\Problem::createProblem();
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevelAdvancedSpecializedTopics',
]),
]));
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[1]
);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => false,
'tag' => 'problemLevelBasicIntroductionToProgramming',
]),
]));
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[2]
);
\OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'quality_tag',
'contents' => json_encode([
'quality_seal' => true,
'tag' => 'problemLevelBasicIntroductionToProgramming',
'tags' => ['problemTagQueues', 'problemTagRecursion'],
]),
]));
\OmegaUp\Test\Utils::runAggregateFeedback();
$problem = \OmegaUp\DAO\Problems::getByPK(
$problemData['problem']->problem_id
);
$this->assertFalse($problem->quality_seal);
}
public function setUpRankForUsers(
$problems,
$users,
$withSuggestions = false
) {
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j <= $i; $j++) {
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problems[$j],
$users[$i]
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
}
}
if ($withSuggestions) {
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[0],
$problems[0]['request']['problem_alias'],
2, /* difficulty */
1, /* quality */
['problemTopicDynamicProgramming', 'problemTopicMath'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[1],
$problems[0]['request']['problem_alias'],
3, /* difficulty */
3, /* quality */
['problemTopicMatrices', 'problemTopicMath'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[2],
$problems[0]['request']['problem_alias'],
4, /* difficulty */
0, /* quality */
['problemTopicMath', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[3],
$problems[0]['request']['problem_alias'],
2, /* difficulty */
4, /* quality */
['problemTopicDynamicProgramming', 'problemTopicMath', 'problemTopicGreedy'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[4],
$problems[0]['request']['problem_alias'],
3, /* difficulty */
4, /* quality */
['problemTopicGreedy', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[1],
$problems[1]['request']['problem_alias'],
3, /* difficulty */
null, /* quality */
['problemTopicMatrices', 'problemTopicMath'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[2],
$problems[1]['request']['problem_alias'],
null, /* difficulty */
1, /* quality */
['problemTopicMath', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[3],
$problems[1]['request']['problem_alias'],
4, /* difficulty */
null, /* quality */
['problemTopicDynamicProgramming', 'problemTopicMath', 'problemTopicGreedy'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[4],
$problems[1]['request']['problem_alias'],
4, /* difficulty */
0, /* quality */
['problemTopicGreedy', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[2],
$problems[2]['request']['problem_alias'],
4, /* difficulty */
4, /* quality */
['problemTopicSorting', 'problemTopicDynamicProgramming', 'problemTopicGreedy'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[3],
$problems[2]['request']['problem_alias'],
4, /* difficulty */
1, /* quality */
['problemTopicGeometry', 'problemTopicDynamicProgramming', 'problemTopicSorting', 'problemTopicGreedy'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[4],
$problems[2]['request']['problem_alias'],
1, /* difficulty */
1, /* quality */
['problemTopicSorting', 'problemTopicGreedy'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[3],
$problems[3]['request']['problem_alias'],
4, /* difficulty */
3, /* quality */
['problemTopicDynamicProgramming', 'problemTopicMath', 'problemTopicGreedy'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[4],
$problems[3]['request']['problem_alias'],
3, /* difficulty */
null, /* quality */
['problemTopicGreedy', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$users[4],
$problems[4]['request']['problem_alias'],
3, /* difficulty */
null, /* quality */
['problemTopicGreedy', 'problemTopicDynamicProgramming'],
false
);
}
}
// Creates 4 problems:
// * An easy one with low quality.
// * An easy one with high quality.
// * A hard one with very high quality.
// * A hard one with low quality.
// The problem of the week should be the second one because we choose the highest-quality one
// with difficulty < 2.
public function testUpdateProblemOfTheWeek() {
$syntheticProblems = self::setUpSyntheticSuggestionsForProblemOfTheWeek();
\OmegaUp\Test\Utils::runAggregateFeedback();
$problemOfTheWeek = \OmegaUp\DAO\ProblemOfTheWeek::getByDifficulty(
'easy'
);
$this->assertCount(1, $problemOfTheWeek);
$this->assertEquals(
$syntheticProblems[1]['problem']->problem_id,
$problemOfTheWeek[0]->problem_id
);
// TODO(heduenas): Make assertation for hard problem of the week when that gets implmented.
}
public function setUpSyntheticSuggestionsForProblemOfTheWeek() {
// Setup synthetic data.
$numberOfProblems = 4;
for ($i = 0; $i < $numberOfProblems; $i++) {
$problemData[$i] = \OmegaUp\Test\Factories\Problem::createProblem();
}
$identities = [];
for ($i = 0; $i < 10; $i++) {
['identity' => $identities[]] = \OmegaUp\Test\Factories\User::createUser();
for ($j = 0; $j < $numberOfProblems; $j++) {
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData[$j],
$identities[$i]
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
}
}
// Easy problem with low quality.
$difficultyRatings[0] = [0, 0, 0, 1, 0, 0, 1, 0, 1, 2]; // Average = 0.5.
$qualityRatings[0] = [0, 2, 3, 2, 2, 2, 1, 2, 1, 1]; // Average = 1.6.
// Easy problem with high quality.
$difficultyRatings[1] = [0, 1, 2, 1, 0, 0, 0, 1, 2, 2]; // Average = 0.9
$qualityRatings[1] = [4, 4, 3, 3, 4, 3, 4, 2, 4, 3]; // Average = 3.4.
// Hard problem with very high quality.
$difficultyRatings[2] = [4, 3, 1, 1, 4, 4, 4, 3, 4, 4]; // Average = 3.2.
$qualityRatings[2] = [4, 4, 4, 4, 3, 4, 4, 3, 4, 4]; // Average = 3.8.
// Hard problem with low quality.
$difficultyRatings[3] = [3, 2, 4, 4, 4, 4, 2, 4, 3, 4]; // Average = 3.4
$qualityRatings[3] = [0, 2, 2, 3, 1, 2, 2, 1, 1, 2]; // Average = 1.6
for ($problemIdx = 0; $problemIdx < $numberOfProblems; $problemIdx++) {
for ($userIdx = 0; $userIdx < 10; $userIdx++) {
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[$userIdx],
$problemData[$problemIdx]['request']['problem_alias'],
$difficultyRatings[$problemIdx][$userIdx],
$qualityRatings[$problemIdx][$userIdx],
[], // No tags.
false
);
}
}
// Set date for all quality nominations as 1 week ago, so that they are eligible for
// current problem of the week.
$dateOneWeekAgo = (new DateTime())
->setTimestamp(\OmegaUp\Time::get())
->sub(new DateInterval('P7D'))
->format('Y-m-d H:i:s');
\OmegaUp\MySQLConnection::getInstance()->Execute(
'UPDATE `QualityNominations` SET `time` = ?',
[$dateOneWeekAgo]
);
return $problemData;
}
public function testAutogeneratedTagsWithConflicts() {
$problemData[0] = \OmegaUp\Test\Factories\Problem::createProblem();
$problemData[1] = \OmegaUp\Test\Factories\Problem::createProblem();
self::setUpSyntheticSuggestions($problemData);
// Manually add one tag.
\OmegaUp\Test\Factories\Problem::addTag(
$problemData[0],
'problemTopicDynamicProgramming',
1 /* public */
);
$tags = array_map(
fn ($tag) => $tag['name'],
\OmegaUp\DAO\ProblemsTags::getProblemTags(
$problemData[0]['problem'],
false /* public_only */,
true /* includeVoted */
)
);
$this->assertEqualsCanonicalizing(
$tags,
[
'problemLevelBasicIntroductionToProgramming',
'problemTopicDynamicProgramming',
'problemRestrictedTagLanguage'
]
);
\OmegaUp\Test\Utils::runAggregateFeedback();
$tags = array_map(
fn ($tag) => $tag['name'],
\OmegaUp\DAO\ProblemsTags::getProblemTags(
$problemData[0]['problem'],
false /* public_only */,
true /* includeVoted */
)
);
$this->assertEqualsCanonicalizing(
$tags,
[
'problemLevelBasicIntroductionToProgramming',
'problemTopicDynamicProgramming',
'problemTopicGreedy',
'problemTopicMath',
'problemRestrictedTagLanguage'
]
);
}
public function setUpSyntheticSuggestions($problemData) {
// Setup synthetic data.
$contestants = [];
$identities = [];
for ($i = 0; $i < 10; $i++) {
['user' => $contestants[], 'identity' => $identities[]] = \OmegaUp\Test\Factories\User::createUser();
for ($j = 0; $j < 2; $j++) {
$runData = \OmegaUp\Test\Factories\Run::createRunToProblem(
$problemData[$j],
$identities[$i]
);
\OmegaUp\Test\Factories\Run::gradeRun($runData);
}
}
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[0],
$problemData[0]['request']['problem_alias'],
null,
1,
['problemTopicDynamicProgramming', 'problemTopicMath'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[1],
$problemData[0]['request']['problem_alias'],
3,
3,
['problemTopicMath', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[2],
$problemData[0]['request']['problem_alias'],
4,
0,
['problemTopicMatrices', 'problemTopicMath'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[3],
$problemData[0]['request']['problem_alias'],
null,
null,
['problemTopicMath'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[4],
$problemData[0]['request']['problem_alias'],
3,
4,
['problemTopicDynamicProgramming', 'problemTopicMath', 'problemTopicGreedy'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[5],
$problemData[0]['request']['problem_alias'],
3,
null,
[],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[6],
$problemData[0]['request']['problem_alias'],
null,
1,
[],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[7],
$problemData[0]['request']['problem_alias'],
4,
null,
['problemTopicGreedy', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[8],
$problemData[0]['request']['problem_alias'],
4,
0,
['problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[9],
$problemData[0]['request']['problem_alias'],
4,
4,
['problemTopicDynamicProgramming', 'problemTopicMath'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[0],
$problemData[1]['request']['problem_alias'],
4,
1,
['problemTopicSorting', 'problemTopicGeometry'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[1],
$problemData[1]['request']['problem_alias'],
1,
1,
['problemTopicSorting', 'problemTopicGeometry'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[2],
$problemData[1]['request']['problem_alias'],
4,
3,
['problemTopicMatrices', 'problemTopicSorting'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[3],
$problemData[1]['request']['problem_alias'],
3,
null,
['problemTopicSorting'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[4],
$problemData[1]['request']['problem_alias'],
3,
null,
['problemTopicSorting', 'problemTopicMath', 'problemTopicGeometry'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[5],
$problemData[1]['request']['problem_alias'],
3,
null,
[],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[6],
$problemData[1]['request']['problem_alias'],
null,
1,
[],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[7],
$problemData[1]['request']['problem_alias'],
3,
null,
['problemTopicSorting', 'problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[8],
$problemData[1]['request']['problem_alias'],
4,
1,
['problemTopicDynamicProgramming'],
false
);
\OmegaUp\Test\Factories\QualityNomination::createSuggestion(
$identities[9],
$problemData[1]['request']['problem_alias'],
4,
3,
['problemTopicGeometry', 'problemTopicMath'],
false
);
}
public function testMostVotedTags() {
$tags = [
'problemTopicDynamicProgramming' => 15,
'problemTopicGraphTheory' => 10,
'problemTopicBinarySearch' => 5,
'problemTopicMath' => 2,
'problemTopicGreedy' => 1,
];
$this->assertEquals(
\OmegaUp\DAO\QualityNominations::mostVotedTags($tags, 0.25),
['problemTopicDynamicProgramming', 'problemTopicGraphTheory', 'problemTopicBinarySearch']
);
$this->assertEquals(
\OmegaUp\DAO\QualityNominations::mostVotedTags($tags, 0.5),
['problemTopicDynamicProgramming', 'problemTopicGraphTheory']
);
$this->assertEquals(
\OmegaUp\DAO\QualityNominations::mostVotedTags($tags, 0.9),
['problemTopicDynamicProgramming']
);
$this->assertEquals(
\OmegaUp\DAO\QualityNominations::mostVotedTags($tags, 0.9),
['problemTopicDynamicProgramming']
);
$this->assertEquals(
\OmegaUp\DAO\QualityNominations::mostVotedTags($tags, 0.01),
['problemTopicDynamicProgramming', 'problemTopicGraphTheory', 'problemTopicBinarySearch', 'problemTopicMath', 'problemTopicGreedy']
);
$tagsWithLittleVotes = [
'problemTopicDynamicProgramming' => 2,
'problemTopicGraphTheory' => 1,
];
$this->assertEquals(
\OmegaUp\DAO\QualityNominations::mostVotedTags(
$tagsWithLittleVotes,
0.25
),
[],
'There must be at least 5 votes.'
);
$tooManyTagsWithMaxVotes = [
'T1' => 9, 'T2' => 9, 'T3' => 9, 'T4' => 9, 'T5' => 9, 'T6' => 9,
'T7' => 9, 'T8' => 9, 'T9' => 9, 'T10' => 9, 'T11' => 9, 'T12' => 9];
$this->assertEquals(
\OmegaUp\DAO\QualityNominations::mostVotedTags(
$tooManyTagsWithMaxVotes,
0.25
),
[],
'There must be a maximum number of tags to be assigned.'
);
}
/**
* A PHPUnit data provider for all the tests that can accept a status.
*
* @return list<array{0: string, 1: int, 2: string, 3:array<string:boolean>, 4: boolean }>
*/
public function qualityNominationsDemotionStatusApiUpdateCaseProvider(): array {
return [
[
'warning',
\OmegaUp\ProblemParams::VISIBILITY_PUBLIC_WARNING,
'qualityNominationProblemHasWarning',
[
'private_banned' => false,
'public_banned' => false,
'private' => false,
'private_warning' => true,
'public_warning' => true,
'public' => false,
'promoted' => false
],
true
],
[
'warning',
\OmegaUp\ProblemParams::VISIBILITY_PUBLIC_WARNING,
'qualityNominationProblemHasWarning',
[
'private_banned' => true,
'public_banned' => true,
'private' => true,
'private_warning' => true,
'public_warning' => true,
'public' => true,
'promoted' => true
],
false
],
[
'banned',
\OmegaUp\ProblemParams::VISIBILITY_PUBLIC_BANNED,
'qualityNominationProblemHasBeenBanned',
[
'private_banned' => false,
'public_banned' => true,
'private' => false,
'private_warning' => false,
'public_warning' => false,
'public' => false,
'promoted' => false
],
true,
],
[
'banned',
\OmegaUp\ProblemParams::VISIBILITY_PUBLIC_BANNED,
'qualityNominationProblemHasBeenBanned',
[
'private_banned' => true,
'public_banned' => true,
'private' => true,
'private_warning' => true,
'public_warning' => true,
'public' => true,
'promoted' => true
],
false,
]
];
}
/**
* Check that a non-reviewer user cannot change the visibility that is not PRIVATE_WARNING
* or PUBLIC_WARNING of his problems with a demotion qualitynomination but only reviewer
* can change any visibility.
* @dataProvider qualityNominationsDemotionStatusApiUpdateCaseProvider
*/
public function testUserCannotUpdateProblemWithDemotionResolved(
string $status,
int $intVisibility,
string $errorMessage,
array $invalidVisibilities,
bool $loginAsAuthor
) {
['identity' => $author] = \OmegaUp\Test\Factories\User::createUser(new \OmegaUp\Test\Factories\UserParams(
[
'username' => 'user_test_author'
]
));
$problemData = \OmegaUp\Test\Factories\Problem::createProblem(new \OmegaUp\Test\Factories\ProblemParams(
[
'author' => $author,
'title' => 'problem_1'
]
));
['user' => $user, 'identity' => $identity] = \OmegaUp\Test\Factories\User::createUser();
$login = self::login($identity);
$qualitynomination = \OmegaUp\Controllers\QualityNomination::apiCreate(new \OmegaUp\Request([
'auth_token' => $login->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
'nomination' => 'demotion',
'contents' => json_encode([
'statements' => [
'es' => [
'markdown' => 'a + b',
],
],
'rationale' => 'ew',
'reason' => 'offensive',
]),
]));
// Login as a reviewer and approve ban.
$reviewerLogin = self::login(
\OmegaUp\Test\Factories\QualityNomination::$reviewers[0]
);
\OmegaUp\Controllers\QualityNomination::apiResolve(
new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'status' => $status,
'problem_alias' => $problemData['request']['problem_alias'],
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
'rationale' => 'ew plus something else',
])
);
$details = \OmegaUp\Controllers\QualityNomination::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'qualitynomination_id' => $qualitynomination['qualitynomination_id'],
]));
$this->assertEquals(
$status,
$details['nomination_status'],
"qualitynomination should have been marked as {$status}"
);
$problem = \OmegaUp\Controllers\Problem::apiDetails(new \OmegaUp\Request([
'auth_token' => $reviewerLogin->auth_token,
'problem_alias' => $problemData['request']['problem_alias'],
]));
$this->assertEquals(
$intVisibility,
$problem['visibility'],
"Problem should have been public {$status}"
);
$login = self::login($author);
foreach ($invalidVisibilities as $visibility => $shouldPass) {
try {
\OmegaUp\Controllers\Problem::apiUpdate(new \OmegaUp\Request([
'auth_token' => ($loginAsAuthor ? $login->auth_token : $reviewerLogin->auth_token),
'problem_alias' => $problemData['request']['problem_alias'],
'visibility' => $visibility,
'message' => "public {$status} -> {$visibility}",
]));
if (!$shouldPass) {
$this->fail(
"Normal user shouldn't be able to update to problem {$status} to other visibility that is not {$status}"
);
}
} catch (\OmegaUp\Exceptions\InvalidParameterException $e) {
if ($shouldPass) {
$this->fail(
"Normal user should be able to update to problem warning to other visibility {$status}"
);
}
$this->assertEquals(
$e->getMessage(),
$errorMessage
);
}
}
}
}
| samdsmx/omegaup | frontend/tests/controllers/QualityNominationTest.php | PHP | bsd-3-clause | 106,277 |
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/domdocument_cpptoc.h"
#include "libcef_dll/cpptoc/domnode_cpptoc.h"
#include "libcef_dll/ctocpp/domevent_listener_ctocpp.h"
#include "libcef_dll/transfer_util.h"
// MEMBER FUNCTIONS - Body may be edited by hand.
enum cef_dom_node_type_t CEF_CALLBACK domnode_get_type(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return DOM_NODE_TYPE_UNSUPPORTED;
// Execute
cef_dom_node_type_t _retval = CefDOMNodeCppToC::Get(self)->GetType();
// Return type: simple
return _retval;
}
int CEF_CALLBACK domnode_is_text(struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->IsText();
// Return type: bool
return _retval;
}
int CEF_CALLBACK domnode_is_element(struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->IsElement();
// Return type: bool
return _retval;
}
int CEF_CALLBACK domnode_is_editable(struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->IsEditable();
// Return type: bool
return _retval;
}
int CEF_CALLBACK domnode_is_form_control_element(struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->IsFormControlElement();
// Return type: bool
return _retval;
}
cef_string_userfree_t CEF_CALLBACK domnode_get_form_control_element_type(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefString _retval = CefDOMNodeCppToC::Get(self)->GetFormControlElementType();
// Return type: string
return _retval.DetachToUserFree();
}
int CEF_CALLBACK domnode_is_same(struct _cef_domnode_t* self,
struct _cef_domnode_t* that) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: that; type: refptr_same
DCHECK(that);
if (!that)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->IsSame(
CefDOMNodeCppToC::Unwrap(that));
// Return type: bool
return _retval;
}
cef_string_userfree_t CEF_CALLBACK domnode_get_name(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefString _retval = CefDOMNodeCppToC::Get(self)->GetName();
// Return type: string
return _retval.DetachToUserFree();
}
cef_string_userfree_t CEF_CALLBACK domnode_get_value(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefString _retval = CefDOMNodeCppToC::Get(self)->GetValue();
// Return type: string
return _retval.DetachToUserFree();
}
int CEF_CALLBACK domnode_set_value(struct _cef_domnode_t* self,
const cef_string_t* value) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: value; type: string_byref_const
DCHECK(value);
if (!value)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->SetValue(
CefString(value));
// Return type: bool
return _retval;
}
cef_string_userfree_t CEF_CALLBACK domnode_get_as_markup(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefString _retval = CefDOMNodeCppToC::Get(self)->GetAsMarkup();
// Return type: string
return _retval.DetachToUserFree();
}
cef_domdocument_t* CEF_CALLBACK domnode_get_document(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefDOMDocument> _retval = CefDOMNodeCppToC::Get(self)->GetDocument(
);
// Return type: refptr_same
return CefDOMDocumentCppToC::Wrap(_retval);
}
struct _cef_domnode_t* CEF_CALLBACK domnode_get_parent(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefDOMNode> _retval = CefDOMNodeCppToC::Get(self)->GetParent();
// Return type: refptr_same
return CefDOMNodeCppToC::Wrap(_retval);
}
struct _cef_domnode_t* CEF_CALLBACK domnode_get_previous_sibling(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefDOMNode> _retval = CefDOMNodeCppToC::Get(
self)->GetPreviousSibling();
// Return type: refptr_same
return CefDOMNodeCppToC::Wrap(_retval);
}
struct _cef_domnode_t* CEF_CALLBACK domnode_get_next_sibling(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefDOMNode> _retval = CefDOMNodeCppToC::Get(self)->GetNextSibling();
// Return type: refptr_same
return CefDOMNodeCppToC::Wrap(_retval);
}
int CEF_CALLBACK domnode_has_children(struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->HasChildren();
// Return type: bool
return _retval;
}
struct _cef_domnode_t* CEF_CALLBACK domnode_get_first_child(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefDOMNode> _retval = CefDOMNodeCppToC::Get(self)->GetFirstChild();
// Return type: refptr_same
return CefDOMNodeCppToC::Wrap(_retval);
}
struct _cef_domnode_t* CEF_CALLBACK domnode_get_last_child(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefDOMNode> _retval = CefDOMNodeCppToC::Get(self)->GetLastChild();
// Return type: refptr_same
return CefDOMNodeCppToC::Wrap(_retval);
}
void CEF_CALLBACK domnode_add_event_listener(struct _cef_domnode_t* self,
const cef_string_t* eventType, struct _cef_domevent_listener_t* listener,
int useCapture) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: eventType; type: string_byref_const
DCHECK(eventType);
if (!eventType)
return;
// Verify param: listener; type: refptr_diff
DCHECK(listener);
if (!listener)
return;
// Execute
CefDOMNodeCppToC::Get(self)->AddEventListener(
CefString(eventType),
CefDOMEventListenerCToCpp::Wrap(listener),
useCapture?true:false);
}
cef_string_userfree_t CEF_CALLBACK domnode_get_element_tag_name(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefString _retval = CefDOMNodeCppToC::Get(self)->GetElementTagName();
// Return type: string
return _retval.DetachToUserFree();
}
int CEF_CALLBACK domnode_has_element_attributes(struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->HasElementAttributes();
// Return type: bool
return _retval;
}
int CEF_CALLBACK domnode_has_element_attribute(struct _cef_domnode_t* self,
const cef_string_t* attrName) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: attrName; type: string_byref_const
DCHECK(attrName);
if (!attrName)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->HasElementAttribute(
CefString(attrName));
// Return type: bool
return _retval;
}
cef_string_userfree_t CEF_CALLBACK domnode_get_element_attribute(
struct _cef_domnode_t* self, const cef_string_t* attrName) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Verify param: attrName; type: string_byref_const
DCHECK(attrName);
if (!attrName)
return NULL;
// Execute
CefString _retval = CefDOMNodeCppToC::Get(self)->GetElementAttribute(
CefString(attrName));
// Return type: string
return _retval.DetachToUserFree();
}
void CEF_CALLBACK domnode_get_element_attributes(struct _cef_domnode_t* self,
cef_string_map_t attrMap) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: attrMap; type: string_map_single_byref
DCHECK(attrMap);
if (!attrMap)
return;
// Translate param: attrMap; type: string_map_single_byref
std::map<CefString, CefString> attrMapMap;
transfer_string_map_contents(attrMap, attrMapMap);
// Execute
CefDOMNodeCppToC::Get(self)->GetElementAttributes(
attrMapMap);
// Restore param: attrMap; type: string_map_single_byref
cef_string_map_clear(attrMap);
transfer_string_map_contents(attrMapMap, attrMap);
}
int CEF_CALLBACK domnode_set_element_attribute(struct _cef_domnode_t* self,
const cef_string_t* attrName, const cef_string_t* value) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: attrName; type: string_byref_const
DCHECK(attrName);
if (!attrName)
return 0;
// Verify param: value; type: string_byref_const
DCHECK(value);
if (!value)
return 0;
// Execute
bool _retval = CefDOMNodeCppToC::Get(self)->SetElementAttribute(
CefString(attrName),
CefString(value));
// Return type: bool
return _retval;
}
cef_string_userfree_t CEF_CALLBACK domnode_get_element_inner_text(
struct _cef_domnode_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefString _retval = CefDOMNodeCppToC::Get(self)->GetElementInnerText();
// Return type: string
return _retval.DetachToUserFree();
}
// CONSTRUCTOR - Do not edit by hand.
CefDOMNodeCppToC::CefDOMNodeCppToC(CefDOMNode* cls)
: CefCppToC<CefDOMNodeCppToC, CefDOMNode, cef_domnode_t>(cls) {
struct_.struct_.get_type = domnode_get_type;
struct_.struct_.is_text = domnode_is_text;
struct_.struct_.is_element = domnode_is_element;
struct_.struct_.is_editable = domnode_is_editable;
struct_.struct_.is_form_control_element = domnode_is_form_control_element;
struct_.struct_.get_form_control_element_type =
domnode_get_form_control_element_type;
struct_.struct_.is_same = domnode_is_same;
struct_.struct_.get_name = domnode_get_name;
struct_.struct_.get_value = domnode_get_value;
struct_.struct_.set_value = domnode_set_value;
struct_.struct_.get_as_markup = domnode_get_as_markup;
struct_.struct_.get_document = domnode_get_document;
struct_.struct_.get_parent = domnode_get_parent;
struct_.struct_.get_previous_sibling = domnode_get_previous_sibling;
struct_.struct_.get_next_sibling = domnode_get_next_sibling;
struct_.struct_.has_children = domnode_has_children;
struct_.struct_.get_first_child = domnode_get_first_child;
struct_.struct_.get_last_child = domnode_get_last_child;
struct_.struct_.add_event_listener = domnode_add_event_listener;
struct_.struct_.get_element_tag_name = domnode_get_element_tag_name;
struct_.struct_.has_element_attributes = domnode_has_element_attributes;
struct_.struct_.has_element_attribute = domnode_has_element_attribute;
struct_.struct_.get_element_attribute = domnode_get_element_attribute;
struct_.struct_.get_element_attributes = domnode_get_element_attributes;
struct_.struct_.set_element_attribute = domnode_set_element_attribute;
struct_.struct_.get_element_inner_text = domnode_get_element_inner_text;
}
#ifndef NDEBUG
template<> long CefCppToC<CefDOMNodeCppToC, CefDOMNode,
cef_domnode_t>::DebugObjCt = 0;
#endif
| hernad/CEF3 | libcef_dll/cpptoc/domnode_cpptoc.cc | C++ | bsd-3-clause | 13,205 |
require 'spec_helper'
describe String do
describe '#binary?' do
context 'when the content is' do
context 'binary' do
it 'returns true' do
"\ff\ff\ff".binary?.should be_true
end
end
context 'text' do
it 'returns false' do
'test'.binary?.should be_false
end
end
end
end
end
| firebitsbr/raptor-io | spec/raptor-io/ruby/string_spec.rb | Ruby | bsd-3-clause | 363 |
<?php
declare(strict_types=1);
namespace Sabre\CalDAV\Subscriptions;
use Sabre\DAV\PropPatch;
use Sabre\DAV\Xml\Property\Href;
class SubscriptionTest extends \PHPUnit\Framework\TestCase
{
protected $backend;
public function getSub($override = [])
{
$caldavBackend = new \Sabre\CalDAV\Backend\MockSubscriptionSupport([], []);
$info = [
'{http://calendarserver.org/ns/}source' => new Href('http://example.org/src', false),
'lastmodified' => date('2013-04-06 11:40:00'), // tomorrow is my birthday!
'{DAV:}displayname' => 'displayname',
];
$id = $caldavBackend->createSubscription('principals/user1', 'uri', array_merge($info, $override));
$subInfo = $caldavBackend->getSubscriptionsForUser('principals/user1');
$this->assertEquals(1, count($subInfo));
$subscription = new Subscription($caldavBackend, $subInfo[0]);
$this->backend = $caldavBackend;
return $subscription;
}
public function testValues()
{
$sub = $this->getSub();
$this->assertEquals('uri', $sub->getName());
$this->assertEquals(date('2013-04-06 11:40:00'), $sub->getLastModified());
$this->assertEquals([], $sub->getChildren());
$this->assertEquals(
[
'{DAV:}displayname' => 'displayname',
'{http://calendarserver.org/ns/}source' => new Href('http://example.org/src', false),
],
$sub->getProperties(['{DAV:}displayname', '{http://calendarserver.org/ns/}source'])
);
$this->assertEquals('principals/user1', $sub->getOwner());
$this->assertNull($sub->getGroup());
$acl = [
[
'privilege' => '{DAV:}all',
'principal' => 'principals/user1',
'protected' => true,
],
[
'privilege' => '{DAV:}all',
'principal' => 'principals/user1/calendar-proxy-write',
'protected' => true,
],
[
'privilege' => '{DAV:}read',
'principal' => 'principals/user1/calendar-proxy-read',
'protected' => true,
],
];
$this->assertEquals($acl, $sub->getACL());
$this->assertNull($sub->getSupportedPrivilegeSet());
}
public function testValues2()
{
$sub = $this->getSub([
'lastmodified' => null,
]);
$this->assertEquals(null, $sub->getLastModified());
}
/**
* @expectedException \Sabre\DAV\Exception\Forbidden
*/
public function testSetACL()
{
$sub = $this->getSub();
$sub->setACL([]);
}
public function testDelete()
{
$sub = $this->getSub();
$sub->delete();
$this->assertEquals([], $this->backend->getSubscriptionsForUser('principals1/user1'));
}
public function testUpdateProperties()
{
$sub = $this->getSub();
$propPatch = new PropPatch([
'{DAV:}displayname' => 'foo',
]);
$sub->propPatch($propPatch);
$this->assertTrue($propPatch->commit());
$this->assertEquals(
'foo',
$this->backend->getSubscriptionsForUser('principals/user1')[0]['{DAV:}displayname']
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testBadConstruct()
{
$caldavBackend = new \Sabre\CalDAV\Backend\MockSubscriptionSupport([], []);
new Subscription($caldavBackend, []);
}
}
| PVince81/sabre-dav | tests/Sabre/CalDAV/Subscriptions/SubscriptionTest.php | PHP | bsd-3-clause | 3,610 |