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
|
---|---|---|---|---|---|
/**
* Licensed to the Rhiot under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The 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 io.rhiot.component.pi4j.i2c.driver;
/**
*
*/
public class BMP180Value {
private int pressure;
private double temperature;
public int getPressure() {
return pressure;
}
public void setPressure(int pressure) {
this.pressure = pressure;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public String toString() {
return "[temperature:" + temperature + ",pressure:" + pressure + "]";
}
}
| jasonchaffee/camel-labs | gateway/components/camel-pi4j/src/main/java/io/rhiot/component/pi4j/i2c/driver/BMP180Value.java | Java | apache-2.0 | 1,355 |
# Copyright 2014, Rackspace, US, 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.
from django.conf import urls
urlpatterns = []
# to register the URLs for your API endpoints, decorate the view class with
# @register below, and the import the endpoint module in the
# rest_api/__init__.py module
def register(view):
"""Register API views to respond to a regex pattern.
``url_regex`` on a wrapped view class is used as the regex pattern.
The view should be a standard Django class-based view implementing an
as_view() method. The url_regex attribute of the view should be a standard
Django URL regex pattern.
"""
p = urls.url(view.url_regex, view.as_view())
urlpatterns.append(p)
return view
| BiznetGIO/horizon | openstack_dashboard/api/rest/urls.py | Python | apache-2.0 | 1,231 |
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.boot.build.test;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.testing.Test;
import org.gradle.language.base.plugins.LifecycleBasePlugin;
import org.gradle.plugins.ide.eclipse.EclipsePlugin;
import org.gradle.plugins.ide.eclipse.model.EclipseModel;
/**
* A {@link Plugin} to configure integration testing support in a {@link Project}.
*
* @author Andy Wilkinson
*/
public class IntegrationTestPlugin implements Plugin<Project> {
/**
* Name of the {@code intTest} task.
*/
public static String INT_TEST_TASK_NAME = "intTest";
/**
* Name of the {@code intTest} source set.
*/
public static String INT_TEST_SOURCE_SET_NAME = "intTest";
@Override
public void apply(Project project) {
project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> configureIntegrationTesting(project));
}
private void configureIntegrationTesting(Project project) {
SourceSet intTestSourceSet = createSourceSet(project);
Test intTest = createTestTask(project, intTestSourceSet);
project.getTasks().getByName(LifecycleBasePlugin.CHECK_TASK_NAME).dependsOn(intTest);
project.getPlugins().withType(EclipsePlugin.class, (eclipsePlugin) -> {
EclipseModel eclipse = project.getExtensions().getByType(EclipseModel.class);
eclipse.classpath((classpath) -> classpath.getPlusConfigurations().add(
project.getConfigurations().getByName(intTestSourceSet.getRuntimeClasspathConfigurationName())));
});
}
private SourceSet createSourceSet(Project project) {
SourceSetContainer sourceSets = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets();
SourceSet intTestSourceSet = sourceSets.create(INT_TEST_SOURCE_SET_NAME);
SourceSet main = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME);
intTestSourceSet.setCompileClasspath(intTestSourceSet.getCompileClasspath().plus(main.getOutput()));
intTestSourceSet.setRuntimeClasspath(intTestSourceSet.getRuntimeClasspath().plus(main.getOutput()));
return intTestSourceSet;
}
private Test createTestTask(Project project, SourceSet intTestSourceSet) {
Test intTest = project.getTasks().create(INT_TEST_TASK_NAME, Test.class);
intTest.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
intTest.setDescription("Runs integration tests.");
intTest.setTestClassesDirs(intTestSourceSet.getOutput().getClassesDirs());
intTest.setClasspath(intTestSourceSet.getRuntimeClasspath());
intTest.shouldRunAfter(JavaPlugin.TEST_TASK_NAME);
return intTest;
}
}
| spring-projects/spring-boot | buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java | Java | apache-2.0 | 3,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 gobblin.writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.base.Optional;
import gobblin.source.extractor.CheckpointableWatermark;
/**
* A helper class that tracks committed and uncommitted watermarks.
* Useful for implementing {@link WatermarkAwareWriter}s that wrap other {@link WatermarkAwareWriter}s.
*
* Note: The current implementation is not meant to be used in a high-throughput scenario
* (e.g. in the path of a write or a callback). See {@link LastWatermarkTracker}.
*/
public class MultiWriterWatermarkTracker implements WatermarkTracker {
private final ConcurrentHashMap<String, Set<CheckpointableWatermark>> candidateCommittables = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Set<CheckpointableWatermark>> unacknowledgedWatermarks = new ConcurrentHashMap<>();
/**
* Reset current state
*/
public synchronized void reset() {
candidateCommittables.clear();
unacknowledgedWatermarks.clear();
}
private synchronized Set<CheckpointableWatermark> getOrCreate(Map<String, Set<CheckpointableWatermark>> map, String key) {
if (map.containsKey(key)) {
return map.get(key);
} else {
Set<CheckpointableWatermark> set = new TreeSet<>();
map.put(key, set);
return set;
}
}
@Override
public void committedWatermarks(Map<String, CheckpointableWatermark> committedMap) {
committedWatermarks(committedMap.values());
}
public void committedWatermarks(Iterable<CheckpointableWatermark> committedStream) {
for (CheckpointableWatermark committed: committedStream) {
committedWatermark(committed);
}
}
@Override
public void committedWatermark(CheckpointableWatermark committed) {
getOrCreate(candidateCommittables, committed.getSource()).add(committed);
}
@Override
public void unacknowledgedWatermark(CheckpointableWatermark unacked) {
getOrCreate(unacknowledgedWatermarks, unacked.getSource()).add(unacked);
}
@Override
public void unacknowledgedWatermarks(Map<String, CheckpointableWatermark> unackedMap) {
for (CheckpointableWatermark unacked: unackedMap.values()) {
unacknowledgedWatermark(unacked);
}
}
@Override
public Map<String, CheckpointableWatermark> getAllCommitableWatermarks() {
Map<String, CheckpointableWatermark> commitables = new HashMap<>(candidateCommittables.size());
for (String source: candidateCommittables.keySet()) {
Optional<CheckpointableWatermark> commitable = getCommittableWatermark(source);
if (commitable.isPresent()) {
commitables.put(commitable.get().getSource(), commitable.get());
}
}
return commitables;
}
@Override
public Map<String, CheckpointableWatermark> getAllUnacknowledgedWatermarks() {
Map<String, CheckpointableWatermark> unackedMap = new HashMap<>(unacknowledgedWatermarks.size());
for (String source: unacknowledgedWatermarks.keySet()) {
Optional<CheckpointableWatermark> unacked = getUnacknowledgedWatermark(source);
if (unacked.isPresent()) {
unackedMap.put(unacked.get().getSource(), unacked.get());
}
}
return unackedMap;
}
public Optional<CheckpointableWatermark> getCommittableWatermark(String source) {
Set<CheckpointableWatermark> unacked = unacknowledgedWatermarks.get(source);
CheckpointableWatermark
minUnacknowledgedWatermark = (unacked == null || unacked.isEmpty())? null: unacked.iterator().next();
CheckpointableWatermark highestCommitableWatermark = null;
for (CheckpointableWatermark commitableWatermark : candidateCommittables.get(source)) {
if ((minUnacknowledgedWatermark == null) || (commitableWatermark.compareTo(minUnacknowledgedWatermark) < 0)) {
// commitableWatermark < minUnacknowledgedWatermark
highestCommitableWatermark = commitableWatermark;
}
}
if (highestCommitableWatermark == null) {
return Optional.absent();
} else {
return Optional.of(highestCommitableWatermark);
}
}
public Optional<CheckpointableWatermark> getUnacknowledgedWatermark(String source) {
Set<CheckpointableWatermark> unacked = unacknowledgedWatermarks.get(source);
if (unacked.isEmpty()) {
return Optional.absent();
} else {
return Optional.of(unacked.iterator().next());
}
}
}
| ydai1124/gobblin-1 | gobblin-core-base/src/main/java/gobblin/writer/MultiWriterWatermarkTracker.java | Java | apache-2.0 | 5,266 |
/*
* 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.mnemonic.service.memory.internal;
import java.nio.ByteBuffer;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
public class BufferBlockInfo {
long bufferBlockBaseAddress = 0L;
int bufferBlockSize;
ByteBuffer bufferBlock = null;
BitSet bufferBlockChunksMap = null;
Map<Long, Integer> chunkSizeMap = new HashMap<>();
public ByteBuffer getBufferBlock() {
return bufferBlock;
}
public void setBufferBlock(ByteBuffer byteBufferBlock) {
this.bufferBlock = byteBufferBlock;
}
public BitSet getBufferBlockChunksMap() {
return bufferBlockChunksMap;
}
public void setBufferBlockChunksMap(BitSet chunksMap) {
this.bufferBlockChunksMap = chunksMap;
}
public long getBufferBlockBaseAddress() {
return bufferBlockBaseAddress;
}
public void setBufferBlockBaseAddress(long bufferBlockBaseAddress) {
this.bufferBlockBaseAddress = bufferBlockBaseAddress;
}
public int getBufferBlockSize() {
return bufferBlockSize;
}
public void setBufferBlockSize(int blockSize) {
this.bufferBlockSize = blockSize;
}
public Map<Long, Integer> getChunkSizeMap() {
return chunkSizeMap;
}
public void setChunkSizeMap(long chunkHandler, int chunkSize) {
chunkSizeMap.put(chunkHandler, chunkSize);
}
}
| lql5083psu/incubator-mnemonic | mnemonic-memory-services/mnemonic-java-vmem-service/src/main/java/org/apache/mnemonic/service/memory/internal/BufferBlockInfo.java | Java | apache-2.0 | 2,204 |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 integration
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apiextensions-apiserver/test/integration/fixtures"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
)
func TestFinalization(t *testing.T) {
tearDown, apiExtensionClient, dynamicClient, err := fixtures.StartDefaultServerWithClients(t)
require.NoError(t, err)
defer tearDown()
noxuDefinition := fixtures.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped)
noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient)
require.NoError(t, err)
ns := "not-the-default"
name := "foo123"
noxuResourceClient := newNamespacedCustomResourceClient(ns, dynamicClient, noxuDefinition)
instance := fixtures.NewNoxuInstance(ns, name)
instance.SetFinalizers([]string{"noxu.example.com/finalizer"})
createdNoxuInstance, err := instantiateCustomResource(t, instance, noxuResourceClient, noxuDefinition)
require.NoError(t, err)
uid := createdNoxuInstance.GetUID()
err = noxuResourceClient.Delete(name, &metav1.DeleteOptions{
Preconditions: &metav1.Preconditions{
UID: &uid,
},
})
require.NoError(t, err)
// Deleting something with a finalizer sets deletion timestamp to a not-nil value but does not
// remove the object from the API server. Here we read it to confirm this.
gottenNoxuInstance, err := noxuResourceClient.Get(name, metav1.GetOptions{})
require.NoError(t, err)
require.NotNil(t, gottenNoxuInstance.GetDeletionTimestamp())
// Trying to delete it again to confirm it will not remove the object because finalizer is still there.
err = noxuResourceClient.Delete(name, &metav1.DeleteOptions{
Preconditions: &metav1.Preconditions{
UID: &uid,
},
})
require.NoError(t, err)
// Removing the finalizers to allow the following delete remove the object.
// This step will fail if previous delete wrongly removed the object. The
// object will be deleted as part of the finalizer update.
for {
gottenNoxuInstance.SetFinalizers(nil)
_, err = noxuResourceClient.Update(gottenNoxuInstance, metav1.UpdateOptions{})
if err == nil {
break
}
if !errors.IsConflict(err) {
require.NoError(t, err) // Fail on unexpected error
}
gottenNoxuInstance, err = noxuResourceClient.Get(name, metav1.GetOptions{})
require.NoError(t, err)
}
// Check that the object is actually gone.
_, err = noxuResourceClient.Get(name, metav1.GetOptions{})
require.Error(t, err)
require.True(t, errors.IsNotFound(err), "%#v", err)
}
func TestFinalizationAndDeletion(t *testing.T) {
tearDown, apiExtensionClient, dynamicClient, err := fixtures.StartDefaultServerWithClients(t)
require.NoError(t, err)
defer tearDown()
// Create a CRD.
noxuDefinition := fixtures.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped)
noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient)
require.NoError(t, err)
// Create a CR with a finalizer.
ns := "not-the-default"
name := "foo123"
noxuResourceClient := newNamespacedCustomResourceClient(ns, dynamicClient, noxuDefinition)
instance := fixtures.NewNoxuInstance(ns, name)
instance.SetFinalizers([]string{"noxu.example.com/finalizer"})
createdNoxuInstance, err := instantiateCustomResource(t, instance, noxuResourceClient, noxuDefinition)
require.NoError(t, err)
// Delete a CR. Because there's a finalizer, it will not get deleted now.
uid := createdNoxuInstance.GetUID()
err = noxuResourceClient.Delete(name, &metav1.DeleteOptions{
Preconditions: &metav1.Preconditions{
UID: &uid,
},
})
require.NoError(t, err)
// Check is the CR scheduled for deletion.
gottenNoxuInstance, err := noxuResourceClient.Get(name, metav1.GetOptions{})
require.NoError(t, err)
require.NotNil(t, gottenNoxuInstance.GetDeletionTimestamp())
// Delete the CRD.
fixtures.DeleteCustomResourceDefinition(noxuDefinition, apiExtensionClient)
// Check is CR still there after the CRD deletion.
gottenNoxuInstance, err = noxuResourceClient.Get(name, metav1.GetOptions{})
require.NoError(t, err)
// Update the CR to remove the finalizer.
for {
gottenNoxuInstance.SetFinalizers(nil)
_, err = noxuResourceClient.Update(gottenNoxuInstance, metav1.UpdateOptions{})
if err == nil {
break
}
if !errors.IsConflict(err) {
require.NoError(t, err) // Fail on unexpected error
}
gottenNoxuInstance, err = noxuResourceClient.Get(name, metav1.GetOptions{})
require.NoError(t, err)
}
// Verify the CR is gone.
// It should return the NonFound error.
_, err = noxuResourceClient.Get(name, metav1.GetOptions{})
if !errors.IsNotFound(err) {
t.Fatalf("unable to delete cr: %v", err)
}
err = wait.Poll(500*time.Millisecond, wait.ForeverTestTimeout, func() (bool, error) {
_, err = apiExtensionClient.ApiextensionsV1beta1().CustomResourceDefinitions().Get(context.TODO(), noxuDefinition.Name, metav1.GetOptions{})
return errors.IsNotFound(err), err
})
if !errors.IsNotFound(err) {
t.Fatalf("unable to delete crd: %v", err)
}
}
| jfrazelle/kubernetes | staging/src/k8s.io/apiextensions-apiserver/test/integration/finalization_test.go | GO | apache-2.0 | 5,811 |
// Code generated by counterfeiter. DO NOT EDIT.
package mock
import (
"sync"
)
type Writer struct {
WriteFileStub func(string, string, []byte) error
writeFileMutex sync.RWMutex
writeFileArgsForCall []struct {
arg1 string
arg2 string
arg3 []byte
}
writeFileReturns struct {
result1 error
}
writeFileReturnsOnCall map[int]struct {
result1 error
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *Writer) WriteFile(arg1 string, arg2 string, arg3 []byte) error {
var arg3Copy []byte
if arg3 != nil {
arg3Copy = make([]byte, len(arg3))
copy(arg3Copy, arg3)
}
fake.writeFileMutex.Lock()
ret, specificReturn := fake.writeFileReturnsOnCall[len(fake.writeFileArgsForCall)]
fake.writeFileArgsForCall = append(fake.writeFileArgsForCall, struct {
arg1 string
arg2 string
arg3 []byte
}{arg1, arg2, arg3Copy})
fake.recordInvocation("WriteFile", []interface{}{arg1, arg2, arg3Copy})
fake.writeFileMutex.Unlock()
if fake.WriteFileStub != nil {
return fake.WriteFileStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.writeFileReturns
return fakeReturns.result1
}
func (fake *Writer) WriteFileCallCount() int {
fake.writeFileMutex.RLock()
defer fake.writeFileMutex.RUnlock()
return len(fake.writeFileArgsForCall)
}
func (fake *Writer) WriteFileCalls(stub func(string, string, []byte) error) {
fake.writeFileMutex.Lock()
defer fake.writeFileMutex.Unlock()
fake.WriteFileStub = stub
}
func (fake *Writer) WriteFileArgsForCall(i int) (string, string, []byte) {
fake.writeFileMutex.RLock()
defer fake.writeFileMutex.RUnlock()
argsForCall := fake.writeFileArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *Writer) WriteFileReturns(result1 error) {
fake.writeFileMutex.Lock()
defer fake.writeFileMutex.Unlock()
fake.WriteFileStub = nil
fake.writeFileReturns = struct {
result1 error
}{result1}
}
func (fake *Writer) WriteFileReturnsOnCall(i int, result1 error) {
fake.writeFileMutex.Lock()
defer fake.writeFileMutex.Unlock()
fake.WriteFileStub = nil
if fake.writeFileReturnsOnCall == nil {
fake.writeFileReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.writeFileReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *Writer) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.writeFileMutex.RLock()
defer fake.writeFileMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *Writer) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
| stemlending/fabric | internal/peer/lifecycle/chaincode/mock/writer.go | GO | apache-2.0 | 3,051 |
/*
* 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.ode.karaf.commands;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.management.*;
import org.apache.felix.karaf.shell.console.OsgiCommandSupport;
import org.apache.ode.bpel.pmapi.*;
import org.apache.ode.jbi.OdeContext;
public abstract class OdeCommandsBase extends OsgiCommandSupport {
protected static String COMPONENT_NAME = "org.apache.servicemix:Type=Component,Name=OdeBpelEngine,SubType=Management";
protected static final String LIST_ALL_PROCESSES = "listAllProcesses";
protected static final String LIST_ALL_INSTANCES = "listAllInstances";
protected static final String TERMINATE = "terminate";
protected MBeanServer getMBeanServer() {
OdeContext ode = OdeContext.getInstance();
if (ode != null) {
return ode.getContext().getMBeanServer();
}
return null;
}
/**
* Invokes an operation on the ODE MBean server
*
* @param <T>
* @param operationName
* @param args
* @param T
* @return
*/
@SuppressWarnings("unchecked")
protected <T> T invoke(final String operationName, final Object[] params,
final String[] signature, Class<?> T, long timeoutInSeconds)
throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<T> callable = new Callable<T>() {
public T call() throws Exception {
MBeanServer server = getMBeanServer();
if (server != null) {
return (T) server.invoke(new ObjectName(COMPONENT_NAME),
operationName, params, signature);
}
return null;
}
};
Future<T> future = executor.submit(callable);
executor.shutdown();
return future.get(timeoutInSeconds, TimeUnit.SECONDS);
}
protected List<TProcessInfo> getProcesses(long timeoutInSeconds)
throws Exception {
ProcessInfoListDocument result = invoke(LIST_ALL_PROCESSES, null, null,
ProcessInfoListDocument.class, timeoutInSeconds);
if (result != null) {
return result.getProcessInfoList().getProcessInfoList();
}
return null;
}
protected List<TInstanceInfo> getActiveInstances(long timeoutInSeconds)
throws Exception {
InstanceInfoListDocument instances = invoke(LIST_ALL_INSTANCES, null,
null, InstanceInfoListDocument.class, timeoutInSeconds);
if (instances != null) {
return instances.getInstanceInfoList().getInstanceInfoList();
}
return null;
}
protected void terminate(Long iid, long timeoutInSeconds) throws Exception {
invoke(TERMINATE, new Long[] { iid }, new String[] { Long.class
.getName() }, InstanceInfoDocument.class, timeoutInSeconds);
}
}
| firzhan/wso2-ode | jbi-karaf-commands/src/main/java/org/apache/ode/karaf/commands/OdeCommandsBase.java | Java | apache-2.0 | 3,894 |
package com.taobao.zeus.jobs.sub;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.ToolRunner;
import com.taobao.zeus.jobs.JobContext;
import com.taobao.zeus.jobs.sub.conf.ConfUtil;
import com.taobao.zeus.jobs.sub.main.MapReduceMain;
import com.taobao.zeus.jobs.sub.tool.DownloadHdfsFileJob;
import com.taobao.zeus.store.HierarchyProperties;
import com.taobao.zeus.util.RunningJobKeys;
public class MapReduceJob extends JavaJob{
public MapReduceJob(JobContext jobContext) {
super(jobContext);
String main=getJavaClass();
String args=getMainArguments();
String classpath=getClassPaths();
jobContext.getProperties().setProperty(RunningJobKeys.RUN_JAVA_MAIN_CLASS, "com.taobao.zeus.jobs.sub.main.MapReduceMain");
classpath=getMRClassPath(classpath);
jobContext.getProperties().setProperty(RunningJobKeys.RUN_CLASSPATH, classpath+
File.pathSeparator+getSourcePathFromClass(MapReduceMain.class));
jobContext.getProperties().setProperty(RunningJobKeys.RUN_JAVA_MAIN_ARGS, main+" "+args);
jobContext.getProperties().setProperty(RunningJobKeys.JOB_RUN_TYPE, "MapReduceJob");
}
//hadoop2依赖的JAR包,Apache需要的jar在${HADOOP_HOME}/libs/目录下,其他版本可能在${HADOOP_HOME}/lib
public String getMRClassPath(String classpath){
StringBuilder sb=new StringBuilder(classpath);
String hadoophome=System.getenv("HADOOP_HOME");
if(hadoophome!=null && !"".equals(hadoophome)){
File f1=new File(hadoophome+"/libs");
if(f1.exists()){
sb.append(File.pathSeparator);
sb.append(hadoophome);
sb.append("/libs/*");
}
File f2=new File(hadoophome+"/lib");
if(f2.exists()){
sb.append(File.pathSeparator);
sb.append(hadoophome);
sb.append("/lib/*");
}
}
return sb.toString();
}
@Override
public Integer run() throws Exception {
List<Map<String, String>> resources=jobContext.getResources();
if(resources!=null && !resources.isEmpty()){
StringBuffer sb=new StringBuffer();
for(Map<String, String> map:jobContext.getResources()){
if(map.get("uri")!=null){
String uri=map.get("uri");
if(uri.startsWith("hdfs://") && uri.endsWith(".jar")){
sb.append(uri.substring("hdfs://".length())).append(",");
}
}
}
jobContext.getProperties().setProperty("core-site.tmpjars", sb.toString().substring(0, sb.toString().length()-1));
}
return super.run();
}
public static void main(String[] args) {
JobContext context=JobContext.getTempJobContext(JobContext.SYSTEM_RUN);
Map<String, String> map=new HashMap<String, String>();
map.put("hadoop.ugi.name", "uginame");
HierarchyProperties properties=new HierarchyProperties(map);
context.setProperties(properties);
new MapReduceJob(context);
}
}
| wwzhe/dataworks-zeus | web/.externalToolBuilders/schedule/src/main/java/com/taobao/zeus/jobs/sub/MapReduceJob.java | Java | apache-2.0 | 3,072 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.operator;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.trino.connector.CatalogName;
import static java.util.Objects.requireNonNull;
public class SplitOperatorInfo
implements OperatorInfo
{
private final CatalogName catalogName;
// NOTE: this deserializes to a map instead of the expected type
private final Object splitInfo;
@JsonCreator
public SplitOperatorInfo(
@JsonProperty("catalogName") CatalogName catalogName,
@JsonProperty("splitInfo") Object splitInfo)
{
this.catalogName = requireNonNull(catalogName, "catalogName is null");
this.splitInfo = splitInfo;
}
@Override
public boolean isFinal()
{
return true;
}
@JsonProperty
public Object getSplitInfo()
{
return splitInfo;
}
@JsonProperty
public CatalogName getCatalogName()
{
return catalogName;
}
}
| electrum/presto | core/trino-main/src/main/java/io/trino/operator/SplitOperatorInfo.java | Java | apache-2.0 | 1,565 |
package org.grobid.core.utilities;
/**
* This class contains all the keys of the properties files.
*
* @author Damien Ridereau
*/
public interface GrobidPropertyKeys {
public static final String PROP_GROBID_IS_CONTEXT_SERVER = "grobid.is.context.server";
public static final String PROP_TMP_PATH = "grobid.temp.path";
// public static final String PROP_BIN_PATH = "grobid.bin.path";
public static final String PROP_NATIVE_LIB_PATH = "grobid.nativelibrary.path";
public static final String PROP_3RD_PARTY_PDF2XML = "grobid.3rdparty.pdf2xml.path";
public static final String PROP_3RD_PARTY_PDF2XML_MEMORY_LIMIT = "grobid.3rdparty.pdf2xml.memory.limit.mb";
public static final String PROP_GROBID_CRF_ENGINE = "grobid.crf.engine";
public static final String PROP_USE_LANG_ID = "grobid.use_language_id";
public static final String PROP_LANG_DETECTOR_FACTORY = "grobid.language_detector_factory";
public static final String PROP_CROSSREF_ID = "grobid.crossref_id";
public static final String PROP_CROSSREF_PW = "grobid.crossref_pw";
public static final String PROP_CROSSREF_HOST = "grobid.crossref_host";
public static final String PROP_CROSSREF_PORT = "grobid.crossref_port";
public static final String PROP_MYSQL_HOST = "grobid.mysql_host";
public static final String PROP_MYSQL_PORT = "grobid.mysql_port";
public static final String PROP_MYSQL_USERNAME = "grobid.mysql_username";
public static final String PROP_MYSQL_PW = "grobid.mysql_passwd";
public static final String PROP_MYSQL_DB_NAME = "grobid.mysql_db_name";
public static final String PROP_PROXY_HOST = "grobid.proxy_host";
public static final String PROP_PROXY_PORT = "grobid.proxy_port";
public static final String PROP_NB_THREADS = "grobid.nb_threads";
public static final String PROP_GROBID_MAX_CONNECTIONS = "org.grobid.max.connections";
public static final String PROP_GROBID_POOL_MAX_WAIT = "org.grobid.pool.max.wait";
/**
* Determines if properties like the firstnames, lastnames country codes and
* dictionaries are supposed to be read from $GROBID_HOME path or not
* (possible values (true|false) default is false)
*/
public static final String PROP_RESOURCE_INHOME = "grobid.resources.inHome";
/**
* The name of the env-entry located in the web.xml, via which the
* grobid-service.propeties path is set.
*/
public static final String PROP_GROBID_HOME = "org.grobid.home";
/**
* The name of the env-entry located in the web.xml, via which the
* grobid.propeties path is set.
*/
public static final String PROP_GROBID_PROPERTY = "org.grobid.property";
/**
* The name of the system property, via which the grobid home folder can be
* located.
*/
public static final String PROP_GROBID_SERVICE_PROPERTY = "org.grobid.property.service";
/**
* name of the property setting the admin password
*/
public static final String PROP_GROBID_SERVICE_ADMIN_PW = "org.grobid.service.admin.pw";
/**
* If set to true, parallel execution will be done, else a queuing of
* requests will be done.
*/
public static final String PROP_GROBID_SERVICE_IS_PARALLEL_EXEC = "org.grobid.service.is.parallel.execution";
/**
* The defined paths to create.
*/
public static final String[] PATHES_TO_CREATE = {PROP_TMP_PATH};
}
| Lilykos/grobid | grobid-core/src/main/java/org/grobid/core/utilities/GrobidPropertyKeys.java | Java | apache-2.0 | 3,430 |
/*
* Copyright 2012 Red Hat, Inc. 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 org.drools.workbench.screens.dtablexls.backend.server.conversion.builders;
import org.drools.decisiontable.parser.ActionType;
import org.drools.workbench.models.datamodel.rule.Attribute;
import org.drools.workbench.models.guided.dtable.shared.conversion.ConversionResult;
import org.drools.workbench.models.guided.dtable.shared.model.AttributeCol52;
import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52;
import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52;
/**
* Builder for ActivationGroup Attribute columns
*/
public class GuidedDecisionTableActivationGroupBuilder extends AbstractGuidedDecisionTableAttributeBuilder {
public GuidedDecisionTableActivationGroupBuilder( final int row,
final int column,
final ConversionResult conversionResult ) {
super( row,
column,
ActionType.Code.ACTIVATIONGROUP,
conversionResult );
}
@Override
public void populateDecisionTable( final GuidedDecisionTable52 dtable,
final int maxRowCount ) {
final AttributeCol52 column = new AttributeCol52();
column.setAttribute(Attribute.ACTIVATION_GROUP.getAttributeName());
dtable.getAttributeCols().add( column );
if ( this.values.size() < maxRowCount ) {
for ( int iRow = this.values.size(); iRow < maxRowCount; iRow++ ) {
this.values.add( new DTCellValue52( "" ) );
}
}
addColumnData( dtable,
column );
}
@Override
public void addCellValue( final int row,
final int column,
final String value ) {
final DTCellValue52 dcv = new DTCellValue52( value );
this.values.add( dcv );
}
}
| mbiarnes/drools-wb | drools-wb-screens/drools-wb-dtable-xls-editor/drools-wb-dtable-xls-editor-backend/src/main/java/org/drools/workbench/screens/dtablexls/backend/server/conversion/builders/GuidedDecisionTableActivationGroupBuilder.java | Java | apache-2.0 | 2,570 |
/*
* 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.ignite.internal.processors.cache.distributed;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
import org.apache.ignite.internal.processors.cache.GridCacheFuture;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.GridLeanMap;
import org.apache.ignite.internal.util.future.GridCompoundIdentityFuture;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteUuid;
import org.jetbrains.annotations.Nullable;
/**
* Future verifying that all remote transactions related to transaction were prepared or committed.
*/
public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolean> implements GridCacheFuture<Boolean> {
/** */
private static final long serialVersionUID = 0L;
/** Logger reference. */
private static final AtomicReference<IgniteLogger> logRef = new AtomicReference<>();
/** Logger. */
private static IgniteLogger log;
/** Trackable flag. */
private boolean trackable = true;
/** Context. */
private final GridCacheSharedContext<?, ?> cctx;
/** Future ID. */
private final IgniteUuid futId = IgniteUuid.randomUuid();
/** Transaction. */
private final IgniteInternalTx tx;
/** All involved nodes. */
private final Map<UUID, ClusterNode> nodes;
/** ID of failed node started transaction. */
private final UUID failedNodeId;
/** Transaction nodes mapping. */
private final Map<UUID, Collection<UUID>> txNodes;
/** */
private final boolean nearTxCheck;
/**
* @param cctx Context.
* @param tx Transaction.
* @param failedNodeId ID of failed node started transaction.
* @param txNodes Transaction mapping.
*/
@SuppressWarnings("ConstantConditions")
public GridCacheTxRecoveryFuture(GridCacheSharedContext<?, ?> cctx,
IgniteInternalTx tx,
UUID failedNodeId,
Map<UUID, Collection<UUID>> txNodes)
{
super(cctx.kernalContext(), CU.boolReducer());
this.cctx = cctx;
this.tx = tx;
this.txNodes = txNodes;
this.failedNodeId = failedNodeId;
if (log == null)
log = U.logger(cctx.kernalContext(), logRef, GridCacheTxRecoveryFuture.class);
nodes = new GridLeanMap<>();
UUID locNodeId = cctx.localNodeId();
for (Map.Entry<UUID, Collection<UUID>> e : tx.transactionNodes().entrySet()) {
if (!locNodeId.equals(e.getKey()) && !failedNodeId.equals(e.getKey()) && !nodes.containsKey(e.getKey())) {
ClusterNode node = cctx.discovery().node(e.getKey());
if (node != null)
nodes.put(node.id(), node);
else if (log.isDebugEnabled())
log.debug("Transaction node left (will ignore) " + e.getKey());
}
for (UUID nodeId : e.getValue()) {
if (!locNodeId.equals(nodeId) && !failedNodeId.equals(nodeId) && !nodes.containsKey(nodeId)) {
ClusterNode node = cctx.discovery().node(nodeId);
if (node != null)
nodes.put(node.id(), node);
else if (log.isDebugEnabled())
log.debug("Transaction node left (will ignore) " + e.getKey());
}
}
}
UUID nearNodeId = tx.eventNodeId();
nearTxCheck = !failedNodeId.equals(nearNodeId) && cctx.discovery().alive(nearNodeId);
}
/**
* Initializes future.
*/
@SuppressWarnings("ConstantConditions")
public void prepare() {
if (nearTxCheck) {
UUID nearNodeId = tx.eventNodeId();
if (cctx.localNodeId().equals(nearNodeId)) {
IgniteInternalFuture<Boolean> fut = cctx.tm().txCommitted(tx.nearXidVersion());
fut.listen(new CI1<IgniteInternalFuture<Boolean>>() {
@Override public void apply(IgniteInternalFuture<Boolean> fut) {
try {
onDone(fut.get());
}
catch (IgniteCheckedException e) {
onDone(e);
}
}
});
}
else {
MiniFuture fut = new MiniFuture(tx.eventNodeId());
add(fut);
GridCacheTxRecoveryRequest req = new GridCacheTxRecoveryRequest(
tx,
0,
true,
futureId(),
fut.futureId());
try {
cctx.io().send(nearNodeId, req, tx.ioPolicy());
}
catch (ClusterTopologyCheckedException ignore) {
fut.onNodeLeft();
}
catch (IgniteCheckedException e) {
fut.onError(e);
}
markInitialized();
}
return;
}
// First check transactions on local node.
int locTxNum = nodeTransactions(cctx.localNodeId());
if (locTxNum > 1) {
IgniteInternalFuture<Boolean> fut = cctx.tm().txsPreparedOrCommitted(tx.nearXidVersion(), locTxNum);
if (fut == null || fut.isDone()) {
boolean prepared;
try {
prepared = fut == null ? true : fut.get();
}
catch (IgniteCheckedException e) {
U.error(log, "Check prepared transaction future failed: " + e, e);
prepared = false;
}
if (!prepared) {
onDone(false);
markInitialized();
return;
}
}
else {
fut.listen(new CI1<IgniteInternalFuture<Boolean>>() {
@Override public void apply(IgniteInternalFuture<Boolean> fut) {
boolean prepared;
try {
prepared = fut.get();
}
catch (IgniteCheckedException e) {
U.error(log, "Check prepared transaction future failed: " + e, e);
prepared = false;
}
if (!prepared) {
onDone(false);
markInitialized();
}
else
proceedPrepare();
}
});
return;
}
}
proceedPrepare();
}
/**
* Process prepare after local check.
*/
private void proceedPrepare() {
for (Map.Entry<UUID, Collection<UUID>> entry : txNodes.entrySet()) {
UUID nodeId = entry.getKey();
// Skip left nodes and local node.
if (!nodes.containsKey(nodeId) && nodeId.equals(cctx.localNodeId()))
continue;
/*
* If primary node failed then send message to all backups, otherwise
* send message only to primary node.
*/
if (nodeId.equals(failedNodeId)) {
for (UUID id : entry.getValue()) {
// Skip backup node if it is local node or if it is also was mapped as primary.
if (txNodes.containsKey(id) || id.equals(cctx.localNodeId()))
continue;
MiniFuture fut = new MiniFuture(id);
add(fut);
GridCacheTxRecoveryRequest req = new GridCacheTxRecoveryRequest(tx,
nodeTransactions(id),
false,
futureId(),
fut.futureId());
try {
cctx.io().send(id, req, tx.ioPolicy());
}
catch (ClusterTopologyCheckedException ignored) {
fut.onNodeLeft();
}
catch (IgniteCheckedException e) {
fut.onError(e);
break;
}
}
}
else {
MiniFuture fut = new MiniFuture(nodeId);
add(fut);
GridCacheTxRecoveryRequest req = new GridCacheTxRecoveryRequest(
tx,
nodeTransactions(nodeId),
false,
futureId(),
fut.futureId());
try {
cctx.io().send(nodeId, req, tx.ioPolicy());
}
catch (ClusterTopologyCheckedException ignored) {
fut.onNodeLeft();
}
catch (IgniteCheckedException e) {
fut.onError(e);
break;
}
}
}
markInitialized();
}
/**
* @param nodeId Node ID.
* @return Number of transactions on node.
*/
private int nodeTransactions(UUID nodeId) {
int cnt = txNodes.containsKey(nodeId) ? 1 : 0; // +1 if node is primary.
for (Collection<UUID> backups : txNodes.values()) {
for (UUID backup : backups) {
if (backup.equals(nodeId)) {
cnt++; // +1 if node is backup.
break;
}
}
}
return cnt;
}
/**
* @param nodeId Node ID.
* @param res Response.
*/
public void onResult(UUID nodeId, GridCacheTxRecoveryResponse res) {
if (!isDone()) {
for (IgniteInternalFuture<Boolean> fut : pending()) {
if (isMini(fut)) {
MiniFuture f = (MiniFuture)fut;
if (f.futureId().equals(res.miniId())) {
assert f.nodeId().equals(nodeId);
f.onResult(res);
break;
}
}
}
}
}
/** {@inheritDoc} */
@Override public IgniteUuid futureId() {
return futId;
}
/** {@inheritDoc} */
@Override public GridCacheVersion version() {
return tx.xidVersion();
}
/** {@inheritDoc} */
@Override public Collection<? extends ClusterNode> nodes() {
return nodes.values();
}
/** {@inheritDoc} */
@Override public boolean onNodeLeft(UUID nodeId) {
for (IgniteInternalFuture<?> fut : futures())
if (isMini(fut)) {
MiniFuture f = (MiniFuture)fut;
if (f.nodeId().equals(nodeId))
f.onNodeLeft();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean trackable() {
return trackable;
}
/** {@inheritDoc} */
@Override public void markNotTrackable() {
trackable = false;
}
/** {@inheritDoc} */
@Override public boolean onDone(@Nullable Boolean res, @Nullable Throwable err) {
if (super.onDone(res, err)) {
cctx.mvcc().removeFuture(this);
if (err == null) {
assert res != null;
cctx.tm().finishTxOnRecovery(tx, res);
}
else {
if (err instanceof ClusterTopologyCheckedException && nearTxCheck) {
if (log.isDebugEnabled())
log.debug("Failed to check transaction on near node, " +
"ignoring [err=" + err + ", tx=" + tx + ']');
}
else {
if (log.isDebugEnabled())
log.debug("Failed to check prepared transactions, " +
"invalidating transaction [err=" + err + ", tx=" + tx + ']');
cctx.tm().salvageTx(tx);
}
}
}
return false;
}
/**
* @param f Future.
* @return {@code True} if mini-future.
*/
private boolean isMini(IgniteInternalFuture<?> f) {
return f.getClass().equals(MiniFuture.class);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheTxRecoveryFuture.class, this, "super", super.toString());
}
/**
*
*/
private class MiniFuture extends GridFutureAdapter<Boolean> {
/** */
private static final long serialVersionUID = 0L;
/** Mini future ID. */
private final IgniteUuid futId = IgniteUuid.randomUuid();
/** Node ID. */
private UUID nodeId;
/**
* @param nodeId Node ID.
*/
private MiniFuture(UUID nodeId) {
this.nodeId = nodeId;
}
/**
* @return Node ID.
*/
private UUID nodeId() {
return nodeId;
}
/**
* @return Future ID.
*/
private IgniteUuid futureId() {
return futId;
}
/**
* @param e Error.
*/
private void onError(Throwable e) {
if (log.isDebugEnabled())
log.debug("Failed to get future result [fut=" + this + ", err=" + e + ']');
onDone(e);
}
/**
*/
private void onNodeLeft() {
if (log.isDebugEnabled())
log.debug("Transaction node left grid (will ignore) [fut=" + this + ']');
if (nearTxCheck) {
// Near and originating nodes left, need initiate tx check.
cctx.tm().commitIfPrepared(tx);
onDone(new ClusterTopologyCheckedException("Transaction node left grid (will ignore)."));
}
else
onDone(true);
}
/**
* @param res Result callback.
*/
private void onResult(GridCacheTxRecoveryResponse res) {
onDone(res.success());
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MiniFuture.class, this, "done", isDone(), "err", error());
}
}
}
| dlnufox/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryFuture.java | Java | apache-2.0 | 15,947 |
/* Copyright 2015 The TensorFlow 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.
==============================================================================*/
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "tensorflow/core/kernels/reduction_gpu_kernels.cu.h"
namespace tensorflow {
namespace functor {
typedef Eigen::GpuDevice GPUDevice;
// Derive Index type. int (32-bit) or long (64-bit) depending on the
// compile-time configuration. "float" here is not relevant.
// TODO(zhifengc): Moves the definition to TTypes.
typedef TTypes<float>::Tensor::Index Index;
// T: the data type
// REDUCER: the reducer functor
// NUM_AXES: the number of axes to reduce
// IN_DIMS: the number of dimensions of the input tensor
#define DEFINE(T, REDUCER, IN_DIMS, NUM_AXES) \
template void ReduceFunctor<GPUDevice, REDUCER>::Reduce( \
OpKernelContext* ctx, TTypes<T, IN_DIMS - NUM_AXES>::Tensor out, \
TTypes<T, IN_DIMS>::ConstTensor in, \
const Eigen::array<Index, NUM_AXES>& reduction_axes, \
const REDUCER& reducer);
#define DEFINE_IDENTITY(T, REDUCER) \
template void ReduceFunctor<GPUDevice, REDUCER>::FillIdentity( \
const GPUDevice& d, TTypes<T>::Vec out, const REDUCER& reducer);
#define DEFINE_FOR_TYPE_AND_R(T, R) \
DEFINE(T, R, 1, 1); \
DEFINE(T, R, 2, 1); \
DEFINE(T, R, 3, 1); \
DEFINE(T, R, 3, 2); \
DEFINE_IDENTITY(T, R)
#define DEFINE_FOR_ALL_REDUCERS(T) \
DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::SumReducer<T>); \
DEFINE_FOR_TYPE_AND_R(T, functor::MeanReducer<T>); \
DEFINE_FOR_TYPE_AND_R(T, functor::EuclideanNormReducer<T>); \
DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::MinReducer<T>); \
DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::MaxReducer<T>); \
DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::ProdReducer<T>)
DEFINE_FOR_ALL_REDUCERS(int32);
DEFINE_FOR_ALL_REDUCERS(int64);
#undef DEFINE_FOR_ALL_REDUCERS
#undef DEFINE_FOR_TYPE_AND_R
#undef DEFINE
} // end namespace functor
} // end namespace tensorflow
#endif // GOOGLE_CUDA
| ghchinoy/tensorflow | tensorflow/core/kernels/reduction_ops_gpu_int.cu.cc | C++ | apache-2.0 | 2,716 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("OSharp.Autofac")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("柳柳软件")]
[assembly: AssemblyProduct("OSharp.Autofac")]
[assembly: AssemblyCopyright("Copyright © 柳柳软件 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("50a2b6a0-8e08-4554-9595-6801f627e16b")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.3.0")]
[assembly: AssemblyInformationalVersion("3.0.3")]
| BiaoLiu/osharp-2015.8.28 | src/OSharp.Autofac/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,374 |
/**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.sesame.graph;
/**
* Provides IDs for function instances.
* <p>
* If two functions are logically equal they will be assigned the same ID. This is used by the caching mechanism
* to allow safe sharing of values calculated by different functions.
* <p>
* Two function instances are considered to be logically equal if their {@link FunctionModelNode} instances are
* equal.
*/
public interface FunctionIdProvider {
/**
* Returns the ID of a function instance.
*
* @param fn a function
* @return the function's ID
* @throws IllegalArgumentException if the function has no known ID
*/
FunctionId getFunctionId(Object fn);
}
| jeorme/OG-Platform | sesame/sesame-engine/src/main/java/com/opengamma/sesame/graph/FunctionIdProvider.java | Java | apache-2.0 | 810 |
/*
* Copyright 2021 Red Hat, Inc. 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 org.kie.workbench.common.stunner.bpmn.project.backend.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.jboss.errai.bus.server.annotations.Service;
import org.kie.soup.commons.util.Sets;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueIndexTerm;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueResourceIndexTerm;
import org.kie.workbench.common.services.refactoring.service.RefactoringQueryService;
import org.kie.workbench.common.services.refactoring.service.ResourceType;
import org.kie.workbench.common.stunner.bpmn.project.backend.query.FindBpmnProcessIdsQuery;
import org.kie.workbench.common.stunner.bpmn.project.service.ProjectOpenReusableSubprocessService;
import org.uberfire.backend.vfs.Path;
@ApplicationScoped
@Service
public class ProjectOpenReusableSubprocessServiceImpl implements ProjectOpenReusableSubprocessService {
private final RefactoringQueryService queryService;
private final Supplier<ResourceType> resourceType;
private final Supplier<String> queryName;
private final Set<ValueIndexTerm> queryTerms;
// CDI proxy.
protected ProjectOpenReusableSubprocessServiceImpl() {
this(null);
}
@Inject
public ProjectOpenReusableSubprocessServiceImpl(final RefactoringQueryService queryService) {
this.queryService = queryService;
this.resourceType = () -> ResourceType.BPMN2;
this.queryName = () -> FindBpmnProcessIdsQuery.NAME;
this.queryTerms = new Sets.Builder<ValueIndexTerm>()
.add(new ValueResourceIndexTerm("*",
resourceType.get(),
ValueIndexTerm.TermSearchType.WILDCARD))
.build();
}
String getQueryName() {
return queryName.get();
}
Set<ValueIndexTerm> createQueryTerms() {
return queryTerms;
}
@Override
@SuppressWarnings("unchecked")
public List<String> openReusableSubprocess(String processId) {
List<String> answer = new ArrayList<>();
Map<String, Path> subprocesses = queryService
.query(getQueryName(), createQueryTerms())
.stream()
.map(row -> (Map<String, Path>) row.getValue())
.filter(row -> row.get(processId) != null)
.findFirst()
.orElse(null);
if (subprocesses == null) {
return answer;
}
answer.add(subprocesses.get(processId).getFileName());
answer.add(subprocesses.get(processId).toURI());
return answer;
}
}
| romartin/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-project-backend/src/main/java/org/kie/workbench/common/stunner/bpmn/project/backend/service/ProjectOpenReusableSubprocessServiceImpl.java | Java | apache-2.0 | 3,469 |
class SearchController < ApplicationController
using ArrayItemWrapper
def index
q, limit, type = search_params.values_at(:q, :limit, :type)
respond_with perform_search(q, limit, type).merge(q: q)
end
private
def perform_search(q, limit, *types)
types = %w(template local_image remote_image) if types.compact.empty?
{}.tap do |results|
results[:templates] = wrapped_templates(q, limit) if types.include? 'template'
results[:local_images] = wrapped_local_images(q, limit) if types.include? 'local_image'
if types.include? 'remote_image'
results[:remote_images], results[:errors] = wrapped_remote_images(q, limit)
end
end
end
def search_params
# Coerce limit to an integer
params[:limit] = params[:limit].to_i if params[:limit].present?
params.permit(:q, :type, :limit)
end
def wrapped_templates(q, limit)
Template.search(q, limit).wrap(TemplateSerializer)
end
def wrapped_local_images(q, limit)
LocalImage.search(q, limit).wrap(LocalImageSearchResultSerializer)
end
def wrapped_remote_images(q, limit)
images, errors = Registry.search(q, limit)
return images.wrap(RemoteImageSearchResultSerializer), errors
end
end
| rheinwein/panamax-api | app/controllers/search_controller.rb | Ruby | apache-2.0 | 1,231 |
/*
* Copyright 2010 Utkin Dmitry
*
* 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 file is part of the WSF Staff project.
* Please, visit http://code.google.com/p/staff for more information.
*/
#include <staff/utils/Log.h>
#include <staff/utils/SharedPtr.h>
#include <staff/utils/File.h>
#include <staff/utils/DynamicLibrary.h>
#include <staff/utils/PluginManager.h>
#include <staff/common/Runtime.h>
#include "ProviderFactory.h"
namespace staff
{
namespace das
{
class ProviderFactory::ProviderFactoryImpl
{
public:
typedef std::map<std::string, IProviderAllocator*> ProviderAllocatorMap;
public:
void Init()
{
const std::string sProvidersDir = Runtime::Inst().GetComponentHome("staff.das")
+ STAFF_PATH_SEPARATOR "providers";
StringList lsProviderDirs;
// find directories with providers
File(sProvidersDir).List(lsProviderDirs, "*", File::AttributeDirectory);
if (lsProviderDirs.size() == 0)
{
LogDebug() << "providers is not found";
}
for (StringList::const_iterator itDir = lsProviderDirs.begin();
itDir != lsProviderDirs.end(); ++itDir)
{
// finding libraries with providers
StringList lsProvidersLibs;
StringList lsProvidersNames;
const std::string& sProviderDir =
sProvidersDir + STAFF_PATH_SEPARATOR + *itDir + STAFF_PATH_SEPARATOR;
File(sProviderDir).List(lsProvidersLibs, "*" STAFF_LIBRARY_VEREXT, File::AttributeRegularFile);
for (StringList::const_iterator itProvider = lsProvidersLibs.begin();
itProvider != lsProvidersLibs.end(); ++itProvider)
{
const std::string& sProviderPluginPath = sProviderDir + *itProvider;
try
{
// loading provider
LogDebug() << "Loading DAS provider: " << sProviderPluginPath;
IProviderAllocator* pAllocator = m_tPluginManager.Load(sProviderPluginPath, true);
STAFF_ASSERT(pAllocator, "Can't get allocator for provider: " + *itProvider);
pAllocator->GetProvidersList(lsProvidersNames);
for (StringList::const_iterator itProviderName = lsProvidersNames.begin();
itProviderName != lsProvidersNames.end(); ++itProviderName)
{
LogDebug1() << "Setting DAS provider: " << *itProviderName;
m_mAllocators[*itProviderName] = pAllocator;
}
}
catch (const Exception& rEx)
{
LogWarning() << "Can't load provider: " << sProviderPluginPath << ": " << rEx.what();
continue;
}
}
}
}
public:
ProviderAllocatorMap m_mAllocators;
PluginManager<IProviderAllocator> m_tPluginManager;
};
ProviderFactory::ProviderFactory()
{
m_pImpl = new ProviderFactoryImpl;
try
{
m_pImpl->Init();
}
STAFF_CATCH_ALL
}
ProviderFactory::~ProviderFactory()
{
delete m_pImpl;
}
ProviderFactory& ProviderFactory::Inst()
{
static ProviderFactory tInst;
return tInst;
}
void ProviderFactory::GetProviders(StringList& rlsProviders)
{
rlsProviders.clear();
for (ProviderFactoryImpl::ProviderAllocatorMap::const_iterator itProvider = m_pImpl->m_mAllocators.begin();
itProvider != m_pImpl->m_mAllocators.end(); ++itProvider)
{
rlsProviders.push_back(itProvider->first);
}
}
PProvider ProviderFactory::Allocate(const std::string& sProvider)
{
ProviderFactoryImpl::ProviderAllocatorMap::iterator itProvider = m_pImpl->m_mAllocators.find(sProvider);
STAFF_ASSERT(itProvider != m_pImpl->m_mAllocators.end(), "Can't get allocator for " + sProvider);
return itProvider->second->Allocate(sProvider);
}
}
}
| gale320/staff | das/common/src/ProviderFactory.cpp | C++ | apache-2.0 | 4,315 |
/*
* This file is part of the select element layoutObject in WebCore.
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
* 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/layout/LayoutMenuList.h"
#include "core/HTMLNames.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/AXObjectCache.h"
#include "core/dom/NodeComputedStyle.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLOptGroupElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/HTMLSelectElement.h"
#include "core/layout/LayoutBR.h"
#include "core/layout/LayoutScrollbar.h"
#include "core/layout/LayoutTheme.h"
#include "core/layout/LayoutView.h"
#include "core/page/ChromeClient.h"
#include "platform/fonts/FontCache.h"
#include "platform/geometry/IntSize.h"
#include "platform/text/PlatformLocale.h"
#include <math.h>
namespace blink {
using namespace HTMLNames;
LayoutMenuList::LayoutMenuList(Element* element)
: LayoutFlexibleBox(element)
, m_buttonText(nullptr)
, m_innerBlock(nullptr)
, m_optionsChanged(true)
, m_isEmpty(false)
, m_hasUpdatedActiveOption(false)
, m_popupIsVisible(false)
, m_optionsWidth(0)
, m_lastActiveIndex(-1)
, m_indexToSelectOnCancel(-1)
{
ASSERT(isHTMLSelectElement(element));
}
LayoutMenuList::~LayoutMenuList()
{
ASSERT(!m_popup);
}
void LayoutMenuList::willBeDestroyed()
{
if (m_popup)
m_popup->disconnectClient();
m_popup = nullptr;
LayoutFlexibleBox::willBeDestroyed();
}
// FIXME: Instead of this hack we should add a ShadowRoot to <select> with no insertion point
// to prevent children from rendering.
bool LayoutMenuList::isChildAllowed(LayoutObject* object, const ComputedStyle&) const
{
return object->isAnonymous() && !object->isLayoutFullScreen();
}
void LayoutMenuList::createInnerBlock()
{
if (m_innerBlock) {
ASSERT(firstChild() == m_innerBlock);
ASSERT(!m_innerBlock->nextSibling());
return;
}
// Create an anonymous block.
ASSERT(!firstChild());
m_innerBlock = createAnonymousBlock();
m_buttonText = new LayoutText(&document(), StringImpl::empty());
// We need to set the text explicitly though it was specified in the
// constructor because LayoutText doesn't refer to the text
// specified in the constructor in a case of re-transforming.
m_buttonText->setStyle(mutableStyle());
m_innerBlock->addChild(m_buttonText);
adjustInnerStyle();
LayoutFlexibleBox::addChild(m_innerBlock);
}
void LayoutMenuList::adjustInnerStyle()
{
ComputedStyle& innerStyle = m_innerBlock->mutableStyleRef();
innerStyle.setFlexGrow(1);
innerStyle.setFlexShrink(1);
// min-width: 0; is needed for correct shrinking.
innerStyle.setMinWidth(Length(0, Fixed));
// Use margin:auto instead of align-items:center to get safe centering, i.e.
// when the content overflows, treat it the same as align-items: flex-start.
// But we only do that for the cases where html.css would otherwise use center.
if (style()->alignItemsPosition() == ItemPositionCenter) {
innerStyle.setMarginTop(Length());
innerStyle.setMarginBottom(Length());
innerStyle.setAlignSelfPosition(ItemPositionFlexStart);
}
innerStyle.setPaddingLeft(Length(LayoutTheme::theme().popupInternalPaddingLeft(styleRef()), Fixed));
innerStyle.setPaddingRight(Length(LayoutTheme::theme().popupInternalPaddingRight(styleRef()), Fixed));
innerStyle.setPaddingTop(Length(LayoutTheme::theme().popupInternalPaddingTop(styleRef()), Fixed));
innerStyle.setPaddingBottom(Length(LayoutTheme::theme().popupInternalPaddingBottom(styleRef()), Fixed));
if (m_optionStyle) {
if ((m_optionStyle->direction() != innerStyle.direction() || m_optionStyle->unicodeBidi() != innerStyle.unicodeBidi()))
m_innerBlock->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::StyleChange);
innerStyle.setTextAlign(style()->isLeftToRightDirection() ? LEFT : RIGHT);
innerStyle.setDirection(m_optionStyle->direction());
innerStyle.setUnicodeBidi(m_optionStyle->unicodeBidi());
}
}
inline HTMLSelectElement* LayoutMenuList::selectElement() const
{
return toHTMLSelectElement(node());
}
void LayoutMenuList::addChild(LayoutObject* newChild, LayoutObject* beforeChild)
{
m_innerBlock->addChild(newChild, beforeChild);
ASSERT(m_innerBlock == firstChild());
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->childrenChanged(this);
}
void LayoutMenuList::removeChild(LayoutObject* oldChild)
{
if (oldChild == m_innerBlock || !m_innerBlock) {
LayoutFlexibleBox::removeChild(oldChild);
m_innerBlock = nullptr;
} else {
m_innerBlock->removeChild(oldChild);
}
}
void LayoutMenuList::styleDidChange(StyleDifference diff, const ComputedStyle* oldStyle)
{
LayoutBlock::styleDidChange(diff, oldStyle);
if (!m_innerBlock)
createInnerBlock();
m_buttonText->setStyle(mutableStyle());
adjustInnerStyle();
bool fontChanged = !oldStyle || oldStyle->font() != style()->font();
if (fontChanged)
updateOptionsWidth();
}
void LayoutMenuList::updateOptionsWidth()
{
float maxOptionWidth = 0;
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
int size = listItems.size();
for (int i = 0; i < size; ++i) {
HTMLElement* element = listItems[i];
if (!isHTMLOptionElement(*element))
continue;
String text = toHTMLOptionElement(element)->textIndentedToRespectGroupLabel();
applyTextTransform(style(), text, ' ');
if (LayoutTheme::theme().popupOptionSupportsTextIndent()) {
// Add in the option's text indent. We can't calculate percentage values for now.
float optionWidth = 0;
if (const ComputedStyle* optionStyle = element->computedStyle())
optionWidth += minimumValueForLength(optionStyle->textIndent(), 0);
if (!text.isEmpty())
optionWidth += style()->font().width(text);
maxOptionWidth = std::max(maxOptionWidth, optionWidth);
} else if (!text.isEmpty()) {
maxOptionWidth = std::max(maxOptionWidth, style()->font().width(text));
}
}
int width = static_cast<int>(ceilf(maxOptionWidth));
if (m_optionsWidth == width)
return;
m_optionsWidth = width;
if (parent())
setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::MenuWidthChanged);
}
void LayoutMenuList::updateFromElement()
{
if (m_optionsChanged) {
updateOptionsWidth();
m_optionsChanged = false;
}
if (m_popupIsVisible)
m_popup->updateFromElement();
updateText();
}
void LayoutMenuList::setIndexToSelectOnCancel(int listIndex)
{
m_indexToSelectOnCancel = listIndex;
updateText();
}
void LayoutMenuList::updateText()
{
if (m_indexToSelectOnCancel >= 0)
setTextFromOption(selectElement()->listToOptionIndex(m_indexToSelectOnCancel));
else if (selectElement()->suggestedIndex() >= 0)
setTextFromOption(selectElement()->suggestedIndex());
else
setTextFromOption(selectElement()->selectedIndex());
}
void LayoutMenuList::setTextFromOption(int optionIndex)
{
HTMLSelectElement* select = selectElement();
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = select->listItems();
const int size = listItems.size();
String text = emptyString();
m_optionStyle.clear();
if (multiple()) {
unsigned selectedCount = 0;
int firstSelectedIndex = -1;
for (int i = 0; i < size; ++i) {
Element* element = listItems[i];
if (!isHTMLOptionElement(*element))
continue;
if (toHTMLOptionElement(element)->selected()) {
if (++selectedCount == 1)
firstSelectedIndex = i;
}
}
if (selectedCount == 1) {
ASSERT(0 <= firstSelectedIndex);
ASSERT(firstSelectedIndex < size);
HTMLOptionElement* selectedOptionElement = toHTMLOptionElement(listItems[firstSelectedIndex]);
ASSERT(selectedOptionElement->selected());
text = selectedOptionElement->textIndentedToRespectGroupLabel();
m_optionStyle = selectedOptionElement->mutableComputedStyle();
} else {
Locale& locale = select->locale();
String localizedNumberString = locale.convertToLocalizedNumber(String::number(selectedCount));
text = locale.queryString(WebLocalizedString::SelectMenuListText, localizedNumberString);
ASSERT(!m_optionStyle);
}
} else {
const int i = select->optionToListIndex(optionIndex);
if (i >= 0 && i < size) {
Element* element = listItems[i];
if (isHTMLOptionElement(*element)) {
text = toHTMLOptionElement(element)->textIndentedToRespectGroupLabel();
m_optionStyle = element->mutableComputedStyle();
}
}
}
setText(text.stripWhiteSpace());
didUpdateActiveOption(optionIndex);
}
void LayoutMenuList::setText(const String& s)
{
if (s.isEmpty()) {
// FIXME: This is a hack. We need the select to have the same baseline positioning as
// any surrounding text. Wihtout any content, we align the bottom of the select to the bottom
// of the text. With content (In this case the faked " ") we correctly align the middle of
// the select to the middle of the text. It should be possible to remove this, just set
// s.impl() into the text and have things align correctly ... crbug.com/485982
m_isEmpty = true;
m_buttonText->setText(StringImpl::create(" ", 1), true);
} else {
m_isEmpty = false;
m_buttonText->setText(s.impl(), true);
}
adjustInnerStyle();
}
String LayoutMenuList::text() const
{
return m_buttonText && !m_isEmpty ? m_buttonText->text() : String();
}
LayoutRect LayoutMenuList::controlClipRect(const LayoutPoint& additionalOffset) const
{
// Clip to the intersection of the content box and the content box for the inner box
// This will leave room for the arrows which sit in the inner box padding,
// and if the inner box ever spills out of the outer box, that will get clipped too.
LayoutRect outerBox = contentBoxRect();
outerBox.moveBy(additionalOffset);
LayoutRect innerBox(additionalOffset + m_innerBlock->location()
+ LayoutSize(m_innerBlock->paddingLeft(), m_innerBlock->paddingTop())
, m_innerBlock->contentSize());
return intersection(outerBox, innerBox);
}
void LayoutMenuList::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
maxLogicalWidth = std::max(m_optionsWidth, LayoutTheme::theme().minimumMenuListSize(styleRef())) + m_innerBlock->paddingLeft() + m_innerBlock->paddingRight();
if (!style()->width().hasPercent())
minLogicalWidth = maxLogicalWidth;
}
void LayoutMenuList::showPopup()
{
if (m_popupIsVisible)
return;
if (document().frameHost()->chromeClient().hasOpenedPopup())
return;
if (!m_popup)
m_popup = document().frameHost()->chromeClient().openPopupMenu(*document().frame(), this);
m_popupIsVisible = true;
FloatQuad quad(localToAbsoluteQuad(FloatQuad(borderBoundingBox())));
IntSize size = pixelSnappedIntRect(frameRect()).size();
HTMLSelectElement* select = selectElement();
m_popup->show(quad, size, select->optionToListIndex(select->selectedIndex()));
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->didShowMenuListPopup(this);
}
void LayoutMenuList::hidePopup()
{
if (m_popup)
m_popup->hide();
}
void LayoutMenuList::valueChanged(unsigned listIndex, bool fireOnChange)
{
// Check to ensure a page navigation has not occurred while
// the popup was up.
Document& doc = toElement(node())->document();
if (&doc != doc.frame()->document())
return;
setIndexToSelectOnCancel(-1);
HTMLSelectElement* select = selectElement();
select->optionSelectedByUser(select->listToOptionIndex(listIndex), fireOnChange);
}
void LayoutMenuList::listBoxSelectItem(int listIndex, bool allowMultiplySelections, bool shift, bool fireOnChangeNow)
{
selectElement()->listBoxSelectItem(listIndex, allowMultiplySelections, shift, fireOnChangeNow);
}
bool LayoutMenuList::multiple() const
{
return selectElement()->multiple();
}
IntRect LayoutMenuList::elementRectRelativeToViewport() const
{
// We don't use absoluteBoundingBoxRect() because it can return an IntRect
// larger the actual size by 1px.
return selectElement()->document().view()->contentsToViewport(roundedIntRect(absoluteBoundingBoxFloatRect()));
}
Element& LayoutMenuList::ownerElement() const
{
return *selectElement();
}
const ComputedStyle* LayoutMenuList::computedStyleForItem(Element& element) const
{
return element.computedStyle() ? element.computedStyle() : element.ensureComputedStyle();
}
void LayoutMenuList::didSetSelectedIndex(int listIndex)
{
didUpdateActiveOption(selectElement()->listToOptionIndex(listIndex));
}
void LayoutMenuList::didUpdateActiveOption(int optionIndex)
{
if (!document().existingAXObjectCache())
return;
if (m_lastActiveIndex == optionIndex)
return;
m_lastActiveIndex = optionIndex;
HTMLSelectElement* select = selectElement();
int listIndex = select->optionToListIndex(optionIndex);
if (listIndex < 0 || listIndex >= static_cast<int>(select->listItems().size()))
return;
// We skip sending accessiblity notifications for the very first option, otherwise
// we get extra focus and select events that are undesired.
if (!m_hasUpdatedActiveOption) {
m_hasUpdatedActiveOption = true;
return;
}
document().existingAXObjectCache()->handleUpdateActiveMenuOption(this, optionIndex);
}
String LayoutMenuList::itemText(unsigned listIndex) const
{
HTMLSelectElement* select = selectElement();
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = select->listItems();
if (listIndex >= listItems.size())
return String();
String itemString;
Element* element = listItems[listIndex];
if (isHTMLOptGroupElement(*element))
itemString = toHTMLOptGroupElement(*element).groupLabelText();
else if (isHTMLOptionElement(*element))
itemString = toHTMLOptionElement(*element).textIndentedToRespectGroupLabel();
applyTextTransform(style(), itemString, ' ');
return itemString;
}
String LayoutMenuList::itemAccessibilityText(unsigned listIndex) const
{
// Allow the accessible name be changed if necessary.
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
if (listIndex >= listItems.size())
return String();
return listItems[listIndex]->fastGetAttribute(aria_labelAttr);
}
String LayoutMenuList::itemToolTip(unsigned listIndex) const
{
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
if (listIndex >= listItems.size())
return String();
return listItems[listIndex]->title();
}
bool LayoutMenuList::itemIsEnabled(unsigned listIndex) const
{
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
if (listIndex >= listItems.size())
return false;
HTMLElement* element = listItems[listIndex];
if (!isHTMLOptionElement(*element))
return false;
bool groupEnabled = true;
if (Element* parentElement = element->parentElement()) {
if (isHTMLOptGroupElement(*parentElement))
groupEnabled = !parentElement->isDisabledFormControl();
}
if (!groupEnabled)
return false;
return !element->isDisabledFormControl();
}
PopupMenuStyle LayoutMenuList::itemStyle(unsigned listIndex) const
{
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
if (listIndex >= listItems.size()) {
// If we are making an out of bounds access, then we want to use the style
// of a different option element (index 0). However, if there isn't an option element
// before at index 0, we fall back to the menu's style.
if (!listIndex)
return menuStyle();
// Try to retrieve the style of an option element we know exists (index 0).
listIndex = 0;
}
HTMLElement* element = listItems[listIndex];
Color itemBackgroundColor;
bool itemHasCustomBackgroundColor;
getItemBackgroundColor(listIndex, itemBackgroundColor, itemHasCustomBackgroundColor);
const ComputedStyle* style = element->computedStyle() ? element->computedStyle() : element->ensureComputedStyle();
return style ? PopupMenuStyle(resolveColor(*style, CSSPropertyColor), itemBackgroundColor, style->font(), style->visibility() == VISIBLE,
isHTMLOptionElement(*element) ? toHTMLOptionElement(*element).isDisplayNone() : style->display() == NONE,
style->textIndent(), style->direction(), isOverride(style->unicodeBidi()),
itemHasCustomBackgroundColor ? PopupMenuStyle::CustomBackgroundColor : PopupMenuStyle::DefaultBackgroundColor) : menuStyle();
}
void LayoutMenuList::getItemBackgroundColor(unsigned listIndex, Color& itemBackgroundColor, bool& itemHasCustomBackgroundColor) const
{
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
if (listIndex >= listItems.size()) {
itemBackgroundColor = resolveColor(CSSPropertyBackgroundColor);
itemHasCustomBackgroundColor = false;
return;
}
HTMLElement* element = listItems[listIndex];
Color backgroundColor;
if (const ComputedStyle* style = element->computedStyle())
backgroundColor = resolveColor(*style, CSSPropertyBackgroundColor);
itemHasCustomBackgroundColor = backgroundColor.alpha();
// If the item has an opaque background color, return that.
if (!backgroundColor.hasAlpha()) {
itemBackgroundColor = backgroundColor;
return;
}
// Otherwise, the item's background is overlayed on top of the menu background.
backgroundColor = resolveColor(CSSPropertyBackgroundColor).blend(backgroundColor);
if (!backgroundColor.hasAlpha()) {
itemBackgroundColor = backgroundColor;
return;
}
// If the menu background is not opaque, then add an opaque white background behind.
itemBackgroundColor = Color(Color::white).blend(backgroundColor);
}
PopupMenuStyle LayoutMenuList::menuStyle() const
{
const LayoutObject* o = m_innerBlock ? m_innerBlock : this;
const ComputedStyle& style = o->styleRef();
return PopupMenuStyle(o->resolveColor(CSSPropertyColor), o->resolveColor(CSSPropertyBackgroundColor), style.font(), style.visibility() == VISIBLE,
style.display() == NONE, style.textIndent(), style.direction(), isOverride(style.unicodeBidi()));
}
LayoutUnit LayoutMenuList::clientPaddingLeft() const
{
return paddingLeft() + m_innerBlock->paddingLeft();
}
const int endOfLinePadding = 2;
LayoutUnit LayoutMenuList::clientPaddingRight() const
{
if (style()->appearance() == MenulistPart || style()->appearance() == MenulistButtonPart) {
// For these appearance values, the theme applies padding to leave room for the
// drop-down button. But leaving room for the button inside the popup menu itself
// looks strange, so we return a small default padding to avoid having a large empty
// space appear on the side of the popup menu.
return endOfLinePadding;
}
// If the appearance isn't MenulistPart, then the select is styled (non-native), so
// we want to return the user specified padding.
return paddingRight() + m_innerBlock->paddingRight();
}
int LayoutMenuList::listSize() const
{
return selectElement()->listItems().size();
}
int LayoutMenuList::selectedIndex() const
{
HTMLSelectElement* select = selectElement();
return select->optionToListIndex(select->selectedIndex());
}
void LayoutMenuList::popupDidHide()
{
m_popupIsVisible = false;
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->didHideMenuListPopup(this);
}
void LayoutMenuList::popupDidCancel()
{
if (m_indexToSelectOnCancel >= 0)
valueChanged(m_indexToSelectOnCancel);
}
bool LayoutMenuList::itemIsSeparator(unsigned listIndex) const
{
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
return listIndex < listItems.size() && isHTMLHRElement(*listItems[listIndex]);
}
bool LayoutMenuList::itemIsLabel(unsigned listIndex) const
{
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
return listIndex < listItems.size() && isHTMLOptGroupElement(*listItems[listIndex]);
}
bool LayoutMenuList::itemIsSelected(unsigned listIndex) const
{
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems();
if (listIndex >= listItems.size())
return false;
HTMLElement* element = listItems[listIndex];
return isHTMLOptionElement(*element) && toHTMLOptionElement(*element).selected();
}
void LayoutMenuList::provisionalSelectionChanged(unsigned listIndex)
{
setIndexToSelectOnCancel(listIndex);
}
} // namespace blink
| zero-rp/miniblink49 | third_party/WebKit/Source/core/layout/LayoutMenuList.cpp | C++ | apache-2.0 | 22,827 |
/*
* Copyright 2018, OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opencensus.contrib.appengine.standard.util;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.apphosting.api.CloudTraceContext;
import com.google.common.annotations.VisibleForTesting;
import io.opencensus.trace.SpanContext;
import io.opencensus.trace.SpanId;
import io.opencensus.trace.TraceId;
import io.opencensus.trace.TraceOptions;
import io.opencensus.trace.Tracestate;
import java.nio.ByteBuffer;
/**
* Utility class to convert between {@link io.opencensus.trace.SpanContext} and {@link
* CloudTraceContext}.
*
* @since 0.14
*/
public final class AppEngineCloudTraceContextUtils {
private static final byte[] INVALID_TRACE_ID =
TraceIdProto.newBuilder().setHi(0).setLo(0).build().toByteArray();
private static final long INVALID_SPAN_ID = 0L;
private static final long INVALID_TRACE_MASK = 0L;
private static final Tracestate TRACESTATE_DEFAULT = Tracestate.builder().build();
@VisibleForTesting
static final CloudTraceContext INVALID_CLOUD_TRACE_CONTEXT =
new CloudTraceContext(INVALID_TRACE_ID, INVALID_SPAN_ID, INVALID_TRACE_MASK);
/**
* Converts AppEngine {@code CloudTraceContext} to {@code SpanContext}.
*
* @param cloudTraceContext the AppEngine {@code CloudTraceContext}.
* @return the converted {@code SpanContext}.
* @since 0.14
*/
public static SpanContext fromCloudTraceContext(CloudTraceContext cloudTraceContext) {
checkNotNull(cloudTraceContext, "cloudTraceContext");
try {
// Extract the trace ID from the binary protobuf CloudTraceContext#traceId.
TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId());
ByteBuffer traceIdBuf = ByteBuffer.allocate(TraceId.SIZE);
traceIdBuf.putLong(traceIdProto.getHi());
traceIdBuf.putLong(traceIdProto.getLo());
ByteBuffer spanIdBuf = ByteBuffer.allocate(SpanId.SIZE);
spanIdBuf.putLong(cloudTraceContext.getSpanId());
return SpanContext.create(
TraceId.fromBytes(traceIdBuf.array()),
SpanId.fromBytes(spanIdBuf.array()),
TraceOptions.builder().setIsSampled(cloudTraceContext.isTraceEnabled()).build(),
TRACESTATE_DEFAULT);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
}
/**
* Converts {@code SpanContext} to AppEngine {@code CloudTraceContext}.
*
* @param spanContext the {@code SpanContext}.
* @return the converted AppEngine {@code CloudTraceContext}.
* @since 0.14
*/
public static CloudTraceContext toCloudTraceContext(SpanContext spanContext) {
checkNotNull(spanContext, "spanContext");
ByteBuffer traceIdBuf = ByteBuffer.wrap(spanContext.getTraceId().getBytes());
TraceIdProto traceIdProto =
TraceIdProto.newBuilder().setHi(traceIdBuf.getLong()).setLo(traceIdBuf.getLong()).build();
ByteBuffer spanIdBuf = ByteBuffer.wrap(spanContext.getSpanId().getBytes());
return new CloudTraceContext(
traceIdProto.toByteArray(),
spanIdBuf.getLong(),
spanContext.getTraceOptions().isSampled() ? 1L : 0L);
}
private AppEngineCloudTraceContextUtils() {}
}
| bogdandrutu/opencensus-java | contrib/appengine_standard_util/src/main/java/io/opencensus/contrib/appengine/standard/util/AppEngineCloudTraceContextUtils.java | Java | apache-2.0 | 3,787 |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2019 The ZAP Development Team
*
* 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.zaproxy.zap.extension.ascanrulesBeta;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Duplicated from Replacer addon. */
class HexString {
private static final Pattern HEX_VALUE = Pattern.compile("\\\\?\\\\x\\p{XDigit}{2}");
private static final String ESCAPED_ESCAPE_CHAR = "\\\\";
static String compile(String binaryRegex) {
Matcher matcher = HEX_VALUE.matcher(binaryRegex);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String value = matcher.group();
if (!value.startsWith(ESCAPED_ESCAPE_CHAR)) {
value = convertByte(value.substring(2));
}
matcher.appendReplacement(sb, value);
}
matcher.appendTail(sb);
return sb.toString();
}
private static String convertByte(String value) {
return Matcher.quoteReplacement(
new String(
new byte[] {(byte) Integer.parseInt(value, 16)},
StandardCharsets.US_ASCII));
}
}
| kingthorin/zap-extensions | addOns/ascanrulesBeta/src/main/java/org/zaproxy/zap/extension/ascanrulesBeta/HexString.java | Java | apache-2.0 | 1,851 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.query.aggregation.post;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.druid.java.util.common.guava.Comparators;
import org.apache.druid.math.expr.Expr;
import org.apache.druid.math.expr.ExprMacroTable;
import org.apache.druid.math.expr.Parser;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.PostAggregator;
import org.apache.druid.query.cache.CacheKeyBuilder;
import org.apache.druid.utils.CollectionUtils;
import javax.annotation.Nullable;
import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class ExpressionPostAggregator implements PostAggregator
{
private static final Comparator<Comparable> DEFAULT_COMPARATOR = Comparator.nullsFirst(
(Comparable o1, Comparable o2) -> {
if (o1 instanceof Long && o2 instanceof Long) {
return Long.compare((long) o1, (long) o2);
} else if (o1 instanceof Number && o2 instanceof Number) {
return Double.compare(((Number) o1).doubleValue(), ((Number) o2).doubleValue());
} else {
return o1.compareTo(o2);
}
}
);
private final String name;
private final String expression;
private final Comparator<Comparable> comparator;
private final String ordering;
private final ExprMacroTable macroTable;
private final Map<String, Function<Object, Object>> finalizers;
private final Supplier<Expr> parsed;
private final Supplier<Set<String>> dependentFields;
/**
* Constructor for serialization.
*/
@JsonCreator
public ExpressionPostAggregator(
@JsonProperty("name") String name,
@JsonProperty("expression") String expression,
@JsonProperty("ordering") @Nullable String ordering,
@JacksonInject ExprMacroTable macroTable
)
{
this(name, expression, ordering, macroTable, ImmutableMap.of());
}
/**
* Constructor for {@link #decorate(Map)}.
*/
private ExpressionPostAggregator(
final String name,
final String expression,
@Nullable final String ordering,
final ExprMacroTable macroTable,
final Map<String, Function<Object, Object>> finalizers
)
{
this(
name,
expression,
ordering,
macroTable,
finalizers,
Suppliers.memoize(() -> Parser.parse(expression, macroTable))
);
}
private ExpressionPostAggregator(
final String name,
final String expression,
@Nullable final String ordering,
final ExprMacroTable macroTable,
final Map<String, Function<Object, Object>> finalizers,
final Supplier<Expr> parsed
)
{
this(
name,
expression,
ordering,
macroTable,
finalizers,
parsed,
Suppliers.memoize(() -> parsed.get().analyzeInputs().getRequiredBindings()));
}
private ExpressionPostAggregator(
final String name,
final String expression,
@Nullable final String ordering,
final ExprMacroTable macroTable,
final Map<String, Function<Object, Object>> finalizers,
final Supplier<Expr> parsed,
final Supplier<Set<String>> dependentFields
)
{
Preconditions.checkArgument(expression != null, "expression cannot be null");
this.name = name;
this.expression = expression;
this.ordering = ordering;
this.comparator = ordering == null ? DEFAULT_COMPARATOR : Ordering.valueOf(ordering);
this.macroTable = macroTable;
this.finalizers = finalizers;
this.parsed = parsed;
this.dependentFields = dependentFields;
}
@Override
public Set<String> getDependentFields()
{
return dependentFields.get();
}
@Override
public Comparator getComparator()
{
return comparator;
}
@Override
public Object compute(Map<String, Object> values)
{
// Maps.transformEntries is lazy, will only finalize values we actually read.
final Map<String, Object> finalizedValues = Maps.transformEntries(
values,
(String k, Object v) -> {
final Function<Object, Object> finalizer = finalizers.get(k);
return finalizer != null ? finalizer.apply(v) : v;
}
);
return parsed.get().eval(Parser.withMap(finalizedValues)).value();
}
@Override
@JsonProperty
public String getName()
{
return name;
}
@Override
public ExpressionPostAggregator decorate(final Map<String, AggregatorFactory> aggregators)
{
return new ExpressionPostAggregator(
name,
expression,
ordering,
macroTable,
CollectionUtils.mapValues(aggregators, aggregatorFactory -> obj -> aggregatorFactory.finalizeComputation(obj)),
parsed,
dependentFields
);
}
@JsonProperty("expression")
public String getExpression()
{
return expression;
}
@JsonProperty("ordering")
public String getOrdering()
{
return ordering;
}
@Override
public String toString()
{
return "ExpressionPostAggregator{" +
"name='" + name + '\'' +
", expression='" + expression + '\'' +
", ordering=" + ordering +
'}';
}
@Override
public byte[] getCacheKey()
{
return new CacheKeyBuilder(PostAggregatorIds.EXPRESSION)
.appendString(expression)
.appendString(ordering)
.build();
}
public enum Ordering implements Comparator<Comparable>
{
/**
* Ensures the following order: numeric > NaN > Infinite.
*
* The name may be referenced via Ordering.valueOf(String) in the constructor {@link
* ExpressionPostAggregator#ExpressionPostAggregator(String, String, String, ExprMacroTable, Map)}.
*/
@SuppressWarnings("unused")
numericFirst {
@Override
public int compare(Comparable lhs, Comparable rhs)
{
if (lhs instanceof Long && rhs instanceof Long) {
return Long.compare(((Number) lhs).longValue(), ((Number) rhs).longValue());
} else if (lhs instanceof Number && rhs instanceof Number) {
double d1 = ((Number) lhs).doubleValue();
double d2 = ((Number) rhs).doubleValue();
if (Double.isFinite(d1) && !Double.isFinite(d2)) {
return 1;
}
if (!Double.isFinite(d1) && Double.isFinite(d2)) {
return -1;
}
return Double.compare(d1, d2);
} else {
return Comparators.<Comparable>naturalNullsFirst().compare(lhs, rhs);
}
}
}
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ExpressionPostAggregator that = (ExpressionPostAggregator) o;
if (!comparator.equals(that.comparator)) {
return false;
}
if (!Objects.equals(name, that.name)) {
return false;
}
if (!Objects.equals(expression, that.expression)) {
return false;
}
if (!Objects.equals(ordering, that.ordering)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = name != null ? name.hashCode() : 0;
result = 31 * result + expression.hashCode();
result = 31 * result + comparator.hashCode();
result = 31 * result + (ordering != null ? ordering.hashCode() : 0);
return result;
}
}
| deltaprojects/druid | processing/src/main/java/org/apache/druid/query/aggregation/post/ExpressionPostAggregator.java | Java | apache-2.0 | 8,546 |
/******************************************************************************
* Copyright (c) 2006, 2010 VMware Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
* VMware Inc.
*****************************************************************************/
package org.eclipse.gemini.blueprint.service.importer.support.internal.aop;
import org.eclipse.gemini.blueprint.service.importer.ServiceReferenceProxy;
import org.eclipse.gemini.blueprint.service.importer.support.internal.util.ServiceComparatorUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.springframework.util.Assert;
/**
* Simple {@link ServiceReference} proxy which simply does delegation, without any extra features. It's main purpose is
* to allow the consistent behaviour between dynamic and static proxies.
*
* @author Costin Leau
*
*/
public class StaticServiceReferenceProxy implements ServiceReferenceProxy {
private static final int HASH_CODE = StaticServiceReferenceProxy.class.hashCode() * 13;
private final ServiceReference target;
/**
* Constructs a new <code>StaticServiceReferenceProxy</code> instance.
*
* @param target service reference
*/
public StaticServiceReferenceProxy(ServiceReference target) {
Assert.notNull(target);
this.target = target;
}
public Bundle getBundle() {
return target.getBundle();
}
public Object getProperty(String key) {
return target.getProperty(key);
}
public String[] getPropertyKeys() {
return target.getPropertyKeys();
}
public Bundle[] getUsingBundles() {
return target.getUsingBundles();
}
public boolean isAssignableTo(Bundle bundle, String className) {
return target.isAssignableTo(bundle, className);
}
public ServiceReference getTargetServiceReference() {
return target;
}
public boolean equals(Object obj) {
if (obj instanceof StaticServiceReferenceProxy) {
StaticServiceReferenceProxy other = (StaticServiceReferenceProxy) obj;
return (target.equals(other.target));
}
return false;
}
public int hashCode() {
return HASH_CODE + target.hashCode();
}
public int compareTo(Object other) {
return ServiceComparatorUtil.compare(target, other);
}
} | eclipse/gemini.blueprint | core/src/main/java/org/eclipse/gemini/blueprint/service/importer/support/internal/aop/StaticServiceReferenceProxy.java | Java | apache-2.0 | 2,728 |
// ----------------------------------------------------------------------------------
//
// 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 Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Sql.AdvancedThreatProtection.Model;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Commands.Sql.ThreatDetection.Model;
using Microsoft.Azure.Commands.Sql.ThreatDetection.Services;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Microsoft.Azure.Management.Sql.Models;
using System.Linq;
namespace Microsoft.Azure.Commands.Sql.AdvancedThreatProtection.Services
{
/// <summary>
/// The SqlAdvancedThreatProtectionAdapter class is responsible for transforming the data that was received form the endpoints to the cmdlets model of AdvancedThreatProtection policy and vice versa
/// </summary>
public class SqlAdvancedThreatProtectionAdapter
{
/// <summary>
/// Gets or sets the Azure subscription
/// </summary>
private IAzureSubscription Subscription { get; set; }
/// <summary>
/// The Threat Detection endpoints communicator used by this adapter
/// </summary>
private SqlThreatDetectionAdapter SqlThreatDetectionAdapter { get; set; }
/// <summary>
/// The Azure endpoints communicator used by this adapter
/// </summary>
private AzureEndpointsCommunicator AzureCommunicator { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public IAzureContext Context { get; set; }
public SqlAdvancedThreatProtectionAdapter(IAzureContext context)
{
Context = context;
Subscription = context.Subscription;
SqlThreatDetectionAdapter = new SqlThreatDetectionAdapter(Context);
}
/// <summary>
/// Provides a server Advanced Threat Protection policy model for the given database
/// </summary>
public ServerAdvancedThreatProtectionPolicyModel GetServerAdvancedThreatProtectionPolicy(string resourceGroup, string serverName)
{
// Currently Advanced Threat Protection policy is a TD policy until the backend will support Advanced Threat Protection APIs
var threatDetectionPolicy = SqlThreatDetectionAdapter.GetServerThreatDetectionPolicy(resourceGroup, serverName);
var serverAdvancedThreatProtectionPolicyModel = new ServerAdvancedThreatProtectionPolicyModel()
{
ResourceGroupName = resourceGroup,
ServerName = serverName,
IsEnabled = (threatDetectionPolicy.ThreatDetectionState == ThreatDetectionStateType.Enabled)
};
return serverAdvancedThreatProtectionPolicyModel;
}
/// <summary>
/// Sets a server Advanced Threat Protection policy model for the given database
/// </summary>
public ServerAdvancedThreatProtectionPolicyModel SetServerAdvancedThreatProtection(ServerAdvancedThreatProtectionPolicyModel model)
{
// Currently Advanced Threat Protection policy is a TD policy until the backend will support Advanced Threat Protection APIs
var threatDetectionPolicy = SqlThreatDetectionAdapter.GetServerThreatDetectionPolicy(model.ResourceGroupName, model.ServerName);
threatDetectionPolicy.ThreatDetectionState = model.IsEnabled ? ThreatDetectionStateType.Enabled : ThreatDetectionStateType.Disabled;
SqlThreatDetectionAdapter.SetServerThreatDetectionPolicy(threatDetectionPolicy, AzureEnvironment.Endpoint.StorageEndpointSuffix);
return model;
}
}
}
| AzureAutomationTeam/azure-powershell | src/ResourceManager/Sql/Commands.Sql/AdvancedThreatProtection/Services/SqlAdvancedThreatProtectionAdapter.cs | C# | apache-2.0 | 4,342 |
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.springframework.boot.actuate.endpoint;
import java.util.Collection;
import org.springframework.boot.actuate.metrics.Metric;
/**
* Interface to expose specific {@link Metric}s via a {@link MetricsEndpoint}.
*
* @author Dave Syer
* @see VanillaPublicMetrics
* @see SystemPublicMetrics
*/
public interface PublicMetrics {
/**
* @return an indication of current state through metrics
*/
Collection<Metric<?>> metrics();
}
| 10045125/spring-boot | spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/PublicMetrics.java | Java | apache-2.0 | 1,069 |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.view.compilation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.threeten.bp.Instant;
import com.google.common.collect.Sets;
import com.opengamma.engine.ComputationTargetResolver;
import com.opengamma.engine.depgraph.DependencyGraph;
import com.opengamma.engine.depgraph.DependencyGraphBuilder;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.resolver.CompiledFunctionResolver;
import com.opengamma.engine.function.resolver.ComputationTargetResults;
import com.opengamma.engine.function.resolver.DefaultCompiledFunctionResolver;
import com.opengamma.engine.function.resolver.ResolutionRule;
import com.opengamma.engine.target.ComputationTargetReference;
import com.opengamma.engine.view.ViewCalculationConfiguration;
import com.opengamma.engine.view.ViewDefinition;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
/**
* Holds context relating to the partially-completed compilation of a view definition, for passing to different stages of the compilation.
*/
/* package */class ViewCompilationContext {
private final ViewDefinition _viewDefinition;
private final ViewCompilationServices _services;
private final Collection<DependencyGraphBuilder> _builders;
private final VersionCorrection _resolverVersionCorrection;
private final Collection<DependencyGraph> _graphs;
private final ConcurrentMap<ComputationTargetReference, UniqueId> _activeResolutions;
private final CompiledFunctionResolver _functions;
private final Collection<ResolutionRule> _rules;
private final ComputationTargetResolver.AtVersionCorrection _targetResolver;
private Set<UniqueId> _expiredResolutions;
/* package */ViewCompilationContext(final ViewDefinition viewDefinition, final ViewCompilationServices compilationServices,
final Instant valuationTime, final VersionCorrection resolverVersionCorrection, final ConcurrentMap<ComputationTargetReference, UniqueId> resolutions) {
_viewDefinition = viewDefinition;
_services = compilationServices;
_builders = new LinkedList<DependencyGraphBuilder>();
_expiredResolutions = Sets.newSetFromMap(new ConcurrentHashMap<UniqueId, Boolean>());
_functions = compilationServices.getFunctionResolver().compile(valuationTime);
_rules = _functions.getAllResolutionRules();
_targetResolver = TargetResolutionLogger.of(compilationServices.getFunctionCompilationContext().getRawComputationTargetResolver().atVersionCorrection(resolverVersionCorrection), resolutions,
_expiredResolutions);
for (final ViewCalculationConfiguration calcConfig : viewDefinition.getAllCalculationConfigurations()) {
_builders.add(createBuilder(calcConfig));
}
_resolverVersionCorrection = resolverVersionCorrection;
_graphs = new ArrayList<DependencyGraph>(_builders.size());
_activeResolutions = resolutions;
}
public DependencyGraphBuilder createBuilder(final ViewCalculationConfiguration calcConfig) {
final DependencyGraphBuilder builder = _services.getDependencyGraphBuilder().newInstance();
builder.setCalculationConfigurationName(calcConfig.getName());
builder.setMarketDataAvailabilityProvider(_services.getMarketDataAvailabilityProvider());
final FunctionCompilationContext compilationContext = _services.getFunctionCompilationContext().clone();
compilationContext.setViewCalculationConfiguration(calcConfig);
compilationContext.setComputationTargetResolver(_targetResolver);
final Collection<ResolutionRule> transformedRules = calcConfig.getResolutionRuleTransform().transform(_rules);
compilationContext.setComputationTargetResults(new ComputationTargetResults(transformedRules));
final DefaultCompiledFunctionResolver functionResolver = new DefaultCompiledFunctionResolver(compilationContext, transformedRules);
functionResolver.compileRules();
builder.setFunctionResolver(functionResolver);
compilationContext.init();
builder.setCompilationContext(compilationContext);
return builder;
}
public ViewDefinition getViewDefinition() {
return _viewDefinition;
}
public ViewCompilationServices getServices() {
return _services;
}
public CompiledFunctionResolver getCompiledFunctionResolver() {
return _functions;
}
public Collection<DependencyGraphBuilder> getBuilders() {
return _builders;
}
public Collection<DependencyGraph> getGraphs() {
return _graphs;
}
public VersionCorrection getResolverVersionCorrection() {
return _resolverVersionCorrection;
}
public ConcurrentMap<ComputationTargetReference, UniqueId> getActiveResolutions() {
return _activeResolutions;
}
public boolean hasExpiredResolutions() {
return !_expiredResolutions.isEmpty();
}
public Set<UniqueId> takeExpiredResolutions() {
final Set<UniqueId> result = _expiredResolutions;
_expiredResolutions = Sets.newSetFromMap(new ConcurrentHashMap<UniqueId, Boolean>());
return result;
}
}
| jeorme/OG-Platform | projects/OG-Engine/src/main/java/com/opengamma/engine/view/compilation/ViewCompilationContext.java | Java | apache-2.0 | 5,308 |
/**
* 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.hdfs.server.datanode;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import org.apache.hadoop.fs.ChecksumException;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.DataTransferProtocol;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.net.SocketOutputStream;
import org.apache.hadoop.util.ChecksumUtil;
import org.apache.hadoop.util.CrcConcat;
import org.apache.hadoop.util.DataChecksum;
import org.apache.hadoop.util.StringUtils;
/**
* Read from blocks with separate checksum files.
* Block file name:
* blk_(blockId)
*
* Checksum file name:
* blk_(blockId)_(generation_stamp).meta
*
* The on disk file format is:
* Data file keeps just data in the block:
*
* +---------------+
* | |
* | Data |
* | . |
* | . |
* | . |
* | . |
* | . |
* | . |
* | |
* +---------------+
*
* Checksum file:
* +----------------------+
* | Checksum Header |
* +----------------------+
* | Checksum for Chunk 1 |
* +----------------------+
* | Checksum for Chunk 2 |
* +----------------------+
* | . |
* | . |
* | . |
* +----------------------+
* | Checksum for last |
* | Chunk (Partial) |
* +----------------------+
*
*/
public class BlockWithChecksumFileReader extends DatanodeBlockReader {
private InputStreamWithChecksumFactory streamFactory;
private DataInputStream checksumIn; // checksum datastream
private BlockDataFile.Reader blockDataFileReader;
boolean useTransferTo = false;
MemoizedBlock memoizedBlock;
BlockWithChecksumFileReader(int namespaceId, Block block,
boolean isFinalized, boolean ignoreChecksum,
boolean verifyChecksum, boolean corruptChecksumOk,
InputStreamWithChecksumFactory streamFactory) throws IOException {
super(namespaceId, block, isFinalized, ignoreChecksum, verifyChecksum,
corruptChecksumOk);
this.streamFactory = streamFactory;
this.checksumIn = streamFactory.getChecksumStream();
this.block = block;
}
@Override
public void fadviseStream(int advise, long offset, long len)
throws IOException {
blockDataFileReader.posixFadviseIfPossible(offset, len, advise);
}
private void initializeNullChecksum() {
checksumIn = null;
// This only decides the buffer size. Use BUFFER_SIZE?
checksum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_NULL,
16 * 1024);
}
public DataChecksum getChecksumToSend(long blockLength) throws IOException {
if (!corruptChecksumOk || checksumIn != null) {
// read and handle the common header here. For now just a version
try {
BlockMetadataHeader header = BlockMetadataHeader.readHeader(checksumIn);
short version = header.getVersion();
if (version != FSDataset.FORMAT_VERSION_NON_INLINECHECKSUM) {
LOG.warn("Wrong version (" + version + ") for metadata file for "
+ block + " ignoring ...");
}
checksum = header.getChecksum();
} catch (IOException ioe) {
if (blockLength == 0) {
initializeNullChecksum();
} else {
throw ioe;
}
}
} else {
LOG.warn("Could not find metadata file for " + block);
initializeNullChecksum();
}
super.getChecksumInfo(blockLength);
return checksum;
}
public void initialize(long offset, long blockLength)
throws IOException {
// seek to the right offsets
if (offset > 0) {
long checksumSkip = (offset / bytesPerChecksum) * checksumSize;
// note blockInStream is seeked when created below
if (checksumSkip > 0) {
// Should we use seek() for checksum file as well?
IOUtils.skipFully(checksumIn, checksumSkip);
}
}
blockDataFileReader = streamFactory.getBlockDataFileReader();
memoizedBlock = new MemoizedBlock(blockLength, streamFactory, block);
}
public boolean prepareTransferTo() throws IOException {
useTransferTo = true;
return useTransferTo;
}
@Override
public void sendChunks(OutputStream out, byte[] buf, long offset,
int checksumOff, int numChunks, int len, BlockCrcUpdater crcUpdater,
int packetVersion) throws IOException {
if (packetVersion != DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST) {
throw new IOException("packet version " + packetVersion
+ " is not supported by non-inline checksum blocks.");
}
int checksumLen = numChunks * checksumSize;
if (checksumSize > 0 && checksumIn != null) {
try {
checksumIn.readFully(buf, checksumOff, checksumLen);
if (dnData != null) {
dnData.recordReadChunkCheckSumTime();
}
if (crcUpdater != null) {
long tempOffset = offset;
long remain = len;
for (int i = 0; i < checksumLen; i += checksumSize) {
long chunkSize = (remain > bytesPerChecksum) ? bytesPerChecksum
: remain;
crcUpdater.updateBlockCrc(tempOffset, (int) chunkSize,
DataChecksum.getIntFromBytes(buf, checksumOff + i));
remain -= chunkSize;
}
}
} catch (IOException e) {
LOG.warn(" Could not read or failed to veirfy checksum for data"
+ " at offset " + offset + " for block " + block + " got : "
+ StringUtils.stringifyException(e));
IOUtils.closeStream(checksumIn);
checksumIn = null;
if (corruptChecksumOk) {
if (checksumOff < checksumLen) {
// Just fill the array with zeros.
Arrays.fill(buf, checksumOff, checksumLen, (byte) 0);
if (dnData != null) {
dnData.recordReadChunkCheckSumTime();
}
}
} else {
throw e;
}
}
}
int dataOff = checksumOff + checksumLen;
if (!useTransferTo) {
// normal transfer
blockDataFileReader.readFully(buf, dataOff, len, offset, true);
if (dnData != null) {
dnData.recordReadChunkDataTime();
}
if (verifyChecksum) {
int dOff = dataOff;
int cOff = checksumOff;
int dLeft = len;
for (int i = 0; i < numChunks; i++) {
checksum.reset();
int dLen = Math.min(dLeft, bytesPerChecksum);
checksum.update(buf, dOff, dLen);
if (!checksum.compare(buf, cOff)) {
throw new ChecksumException("Checksum failed at "
+ (offset + len - dLeft), len);
}
dLeft -= dLen;
dOff += dLen;
cOff += checksumSize;
}
if (dnData != null) {
dnData.recordVerifyCheckSumTime();
}
}
// only recompute checksum if we can't trust the meta data due to
// concurrent writes
if (memoizedBlock.hasBlockChanged(len, offset)) {
ChecksumUtil.updateChunkChecksum(buf, checksumOff, dataOff, len,
checksum);
if (dnData != null) {
dnData.recordUpdateChunkCheckSumTime();
}
}
try {
out.write(buf, 0, dataOff + len);
if (dnData != null) {
dnData.recordSendChunkToClientTime();
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("IOException when reading block " + block + " offset " + offset, e);
}
throw BlockSender.ioeToSocketException(e);
}
} else {
try {
// use transferTo(). Checks on out and blockIn are already done.
SocketOutputStream sockOut = (SocketOutputStream) out;
if (memoizedBlock.hasBlockChanged(len, offset)) {
blockDataFileReader.readFully(buf, dataOff, len, offset, true);
if (dnData != null) {
dnData.recordReadChunkDataTime();
}
ChecksumUtil.updateChunkChecksum(buf, checksumOff, dataOff, len,
checksum);
if (dnData != null) {
dnData.recordUpdateChunkCheckSumTime();
}
sockOut.write(buf, 0, dataOff + len);
if (dnData != null) {
dnData.recordSendChunkToClientTime();
}
} else {
// first write the packet
sockOut.write(buf, 0, dataOff);
// no need to flush. since we know out is not a buffered stream.
blockDataFileReader.transferToSocketFully(sockOut,offset, len);
if (dnData != null) {
dnData.recordTransferChunkToClientTime();
}
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("IOException when reading block " + block + " offset "
+ offset, e);
}
/*
* exception while writing to the client (well, with transferTo(), it
* could also be while reading from the local file).
*/
throw BlockSender.ioeToSocketException(e);
}
}
}
@Override
public int getPreferredPacketVersion() {
return DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST;
}
public void close() throws IOException {
IOException ioe = null;
// close checksum file
if (checksumIn != null) {
try {
checksumIn.close();
} catch (IOException e) {
ioe = e;
}
checksumIn = null;
}
// throw IOException if there is any
if (ioe != null) {
throw ioe;
}
}
/**
* helper class used to track if a block's meta data is verifiable or not
*/
class MemoizedBlock {
// visible block length
private long blockLength;
private final Block block;
private final InputStreamWithChecksumFactory isf;
private MemoizedBlock(long blockLength,
InputStreamWithChecksumFactory isf, Block block) {
this.blockLength = blockLength;
this.isf = isf;
this.block = block;
}
// logic: if we are starting or ending on a partial chunk and the block
// has more data than we were told at construction, the block has 'changed'
// in a way that we care about (ie, we can't trust crc data)
boolean hasBlockChanged(long dataLen, long offset) throws IOException {
if (isFinalized) {
// We would treat it an error case for a finalized block at open time
// has an unmatched size when closing. There might be false positive
// for append() case. We made the trade-off to avoid false negative.
// always return true so it data integrity is guaranteed by checksum
// checking.
return false;
}
// check if we are using transferTo since we tell if the file has changed
// (blockInPosition >= 0 => we are using transferTo and File Channels
if (useTransferTo) {
long currentLength = blockDataFileReader.size();
return (offset % bytesPerChecksum != 0 || dataLen
% bytesPerChecksum != 0)
&& currentLength > blockLength;
} else {
FSDatasetInterface ds = null;
if (isf instanceof DatanodeBlockReader.BlockInputStreamFactory) {
ds = ((DatanodeBlockReader.BlockInputStreamFactory) isf).getDataset();
}
// offset is the offset into the block
return (offset % bytesPerChecksum != 0 || dataLen % bytesPerChecksum != 0)
&& ds != null
&& ds.getOnDiskLength(namespaceId, block) > blockLength;
}
}
}
public static interface InputStreamWithChecksumFactory extends
BlockSender.InputStreamFactory {
public InputStream createStream(long offset) throws IOException;
public DataInputStream getChecksumStream() throws IOException;
}
/** Find the metadata file for the specified block file.
* Return the generation stamp from the name of the metafile.
*/
static long getGenerationStampFromSeperateChecksumFile(String[] listdir, String blockName) {
for (int j = 0; j < listdir.length; j++) {
String path = listdir[j];
if (!path.startsWith(blockName)) {
continue;
}
String[] vals = StringUtils.split(path, '_');
if (vals.length != 3) { // blk, blkid, genstamp.meta
continue;
}
String[] str = StringUtils.split(vals[2], '.');
if (str.length != 2) {
continue;
}
return Long.parseLong(str[0]);
}
DataNode.LOG.warn("Block " + blockName +
" does not have a metafile!");
return Block.GRANDFATHER_GENERATION_STAMP;
}
/**
* Find generation stamp from block file and meta file.
* @param blockFile
* @param metaFile
* @return
* @throws IOException
*/
static long parseGenerationStampInMetaFile(File blockFile, File metaFile
) throws IOException {
String metaname = metaFile.getName();
String gs = metaname.substring(blockFile.getName().length() + 1,
metaname.length() - FSDataset.METADATA_EXTENSION.length());
try {
return Long.parseLong(gs);
} catch(NumberFormatException nfe) {
throw (IOException)new IOException("blockFile=" + blockFile
+ ", metaFile=" + metaFile).initCause(nfe);
}
}
/**
* This class provides the input stream and length of the metadata
* of a block
*
*/
static class MetaDataInputStream extends FilterInputStream {
MetaDataInputStream(InputStream stream, long len) {
super(stream);
length = len;
}
private long length;
public long getLength() {
return length;
}
}
static protected File getMetaFile(FSDatasetInterface dataset, int namespaceId,
Block b) throws IOException {
return BlockWithChecksumFileWriter.getMetaFile(dataset.getBlockFile(namespaceId, b), b);
}
/**
* Does the meta file exist for this block?
* @param namespaceId - parent namespace id
* @param b - the block
* @return true of the metafile for specified block exits
* @throws IOException
*/
static public boolean metaFileExists(FSDatasetInterface dataset, int namespaceId, Block b) throws IOException {
return getMetaFile(dataset, namespaceId, b).exists();
}
/**
* Returns metaData of block b as an input stream (and its length)
* @param namespaceId - parent namespace id
* @param b - the block
* @return the metadata input stream;
* @throws IOException
*/
static public MetaDataInputStream getMetaDataInputStream(
FSDatasetInterface dataset, int namespace, Block b) throws IOException {
File checksumFile = getMetaFile(dataset, namespace, b);
return new MetaDataInputStream(new FileInputStream(checksumFile),
checksumFile.length());
}
static byte[] getMetaData(FSDatasetInterface dataset, int namespaceId,
Block block) throws IOException {
MetaDataInputStream checksumIn = null;
try {
checksumIn = getMetaDataInputStream(dataset, namespaceId, block);
long fileSize = checksumIn.getLength();
if (fileSize >= 1L << 31 || fileSize <= 0) {
throw new IOException("Unexpected size for checksumFile of block"
+ block);
}
byte[] buf = new byte[(int) fileSize];
IOUtils.readFully(checksumIn, buf, 0, buf.length);
return buf;
} finally {
IOUtils.closeStream(checksumIn);
}
}
/**
* Calculate CRC Checksum of the whole block. Implemented by concatenating
* checksums of all the chunks.
*
* @param datanode
* @param ri
* @param namespaceId
* @param block
* @return
* @throws IOException
*/
static public int getBlockCrc(DataNode datanode, ReplicaToRead ri,
int namespaceId, Block block) throws IOException {
InputStream rawStreamIn = null;
DataInputStream streamIn = null;
try {
int bytesPerCRC;
int checksumSize;
long crcPerBlock;
rawStreamIn = BlockWithChecksumFileReader.getMetaDataInputStream(
datanode.data, namespaceId, block);
streamIn = new DataInputStream(new BufferedInputStream(rawStreamIn,
FSConstants.BUFFER_SIZE));
final BlockMetadataHeader header = BlockMetadataHeader
.readHeader(streamIn);
final DataChecksum checksum = header.getChecksum();
if (checksum.getChecksumType() != DataChecksum.CHECKSUM_CRC32) {
throw new IOException("File Checksum now is only supported for CRC32");
}
bytesPerCRC = checksum.getBytesPerChecksum();
checksumSize = checksum.getChecksumSize();
crcPerBlock = (((BlockWithChecksumFileReader.MetaDataInputStream) rawStreamIn)
.getLength() - BlockMetadataHeader.getHeaderSize()) / checksumSize;
int blockCrc = 0;
byte[] buffer = new byte[checksumSize];
for (int i = 0; i < crcPerBlock; i++) {
IOUtils.readFully(streamIn, buffer, 0, buffer.length);
int intChecksum = ((buffer[0] & 0xff) << 24)
| ((buffer[1] & 0xff) << 16) | ((buffer[2] & 0xff) << 8)
| ((buffer[3] & 0xff));
if (i == 0) {
blockCrc = intChecksum;
} else {
int chunkLength;
if (i != crcPerBlock - 1 || ri.getBytesVisible() % bytesPerCRC == 0) {
chunkLength = bytesPerCRC;
} else {
chunkLength = (int) ri.getBytesVisible() % bytesPerCRC;
}
blockCrc = CrcConcat.concatCrc(blockCrc, intChecksum, chunkLength);
}
}
return blockCrc;
} finally {
if (streamIn != null) {
IOUtils.closeStream(streamIn);
}
if (rawStreamIn != null) {
IOUtils.closeStream(rawStreamIn);
}
}
}
static long readBlockAccelerator(Socket s, File dataFile, Block block,
long startOffset, long length, DataNode datanode) throws IOException {
File checksumFile = BlockWithChecksumFileWriter.getMetaFile(dataFile, block);
FileInputStream datain = new FileInputStream(dataFile);
FileInputStream metain = new FileInputStream(checksumFile);
FileChannel dch = datain.getChannel();
FileChannel mch = metain.getChannel();
// read in type of crc and bytes-per-checksum from metadata file
int versionSize = 2; // the first two bytes in meta file is the version
byte[] cksumHeader = new byte[versionSize + DataChecksum.HEADER_LEN];
int numread = metain.read(cksumHeader);
if (numread != versionSize + DataChecksum.HEADER_LEN) {
String msg = "readBlockAccelerator: metafile header should be atleast " +
(versionSize + DataChecksum.HEADER_LEN) + " bytes " +
" but could read only " + numread + " bytes.";
LOG.warn(msg);
throw new IOException(msg);
}
DataChecksum ckHdr = DataChecksum.newDataChecksum(cksumHeader, versionSize);
int type = ckHdr.getChecksumType();
int bytesPerChecksum = ckHdr.getBytesPerChecksum();
long cheaderSize = DataChecksum.getChecksumHeaderSize();
// align the startOffset with the previous bytesPerChecksum boundary.
long delta = startOffset % bytesPerChecksum;
startOffset -= delta;
length += delta;
// align the length to encompass the entire last checksum chunk
delta = length % bytesPerChecksum;
if (delta != 0) {
delta = bytesPerChecksum - delta;
length += delta;
}
// find the offset in the metafile
long startChunkNumber = startOffset / bytesPerChecksum;
long numChunks = length / bytesPerChecksum;
long checksumSize = ckHdr.getChecksumSize();
long startMetaOffset = versionSize + cheaderSize + startChunkNumber * checksumSize;
long metaLength = numChunks * checksumSize;
// get a connection back to the client
SocketOutputStream out = new SocketOutputStream(s, datanode.socketWriteTimeout);
try {
// write out the checksum type and bytesperchecksum to client
// skip the first two bytes that describe the version
long val = mch.transferTo(versionSize, cheaderSize, out);
if (val != cheaderSize) {
String msg = "readBlockAccelerator for block " + block +
" at offset " + 0 +
" but could not transfer checksum header.";
LOG.warn(msg);
throw new IOException(msg);
}
if (LOG.isDebugEnabled()) {
LOG.debug("readBlockAccelerator metaOffset " + startMetaOffset +
" mlength " + metaLength);
}
// write out the checksums back to the client
val = mch.transferTo(startMetaOffset, metaLength, out);
if (val != metaLength) {
String msg = "readBlockAccelerator for block " + block +
" at offset " + startMetaOffset +
" but could not transfer checksums of size " +
metaLength + ". Transferred only " + val;
LOG.warn(msg);
throw new IOException(msg);
}
if (LOG.isDebugEnabled()) {
LOG.debug("readBlockAccelerator dataOffset " + startOffset +
" length " + length);
}
// send data block back to client
long read = dch.transferTo(startOffset, length, out);
if (read != length) {
String msg = "readBlockAccelerator for block " + block +
" at offset " + startOffset +
" but block size is only " + length +
" and could transfer only " + read;
LOG.warn(msg);
throw new IOException(msg);
}
return read;
} catch ( SocketException ignored ) {
// Its ok for remote side to close the connection anytime.
datanode.myMetrics.blocksRead.inc();
return -1;
} catch ( IOException ioe ) {
/* What exactly should we do here?
* Earlier version shutdown() datanode if there is disk error.
*/
LOG.warn(datanode.getDatanodeInfo() +
":readBlockAccelerator:Got exception while serving " +
block + " to " +
s.getInetAddress() + ":\n" +
StringUtils.stringifyException(ioe) );
throw ioe;
} finally {
IOUtils.closeStream(out);
IOUtils.closeStream(datain);
IOUtils.closeStream(metain);
}
}
public static boolean isMetaFilename(String name) {
return name.startsWith(Block.BLOCK_FILE_PREFIX)
&& name.endsWith(Block.METADATA_EXTENSION);
}
/**
* Returns array of two longs: the first one is the block id, and the second
* one is genStamp. The method workds under assumption that metafile name has
* the following format: "blk_<blkid>_<gensmp>.meta"
*/
public static long[] parseMetafileName(String path) {
String[] groundSeparated = StringUtils.split(path, '_');
if (groundSeparated.length != 3) { // blk, blkid, genstamp.meta
throw new IllegalArgumentException("Not a valid meta file name");
}
String[] dotSeparated = StringUtils.split(groundSeparated[2], '.');
if (dotSeparated.length != 2) {
throw new IllegalArgumentException("Not a valid meta file name");
}
return new long[] { Long.parseLong(groundSeparated[1]),
Long.parseLong(dotSeparated[0]) };
}
}
| shakamunyi/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockWithChecksumFileReader.java | Java | apache-2.0 | 24,443 |
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.springframework.beans.factory.xml;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
/**
* Support class for implementing custom {@link NamespaceHandler NamespaceHandlers}.
* Parsing and decorating of individual {@link Node Nodes} is done via {@link BeanDefinitionParser}
* and {@link BeanDefinitionDecorator} strategy interfaces, respectively.
*
* <p>Provides the {@link #registerBeanDefinitionParser} and {@link #registerBeanDefinitionDecorator}
* methods for registering a {@link BeanDefinitionParser} or {@link BeanDefinitionDecorator}
* to handle a specific element.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @see #registerBeanDefinitionParser(String, BeanDefinitionParser)
* @see #registerBeanDefinitionDecorator(String, BeanDefinitionDecorator)
*/
public abstract class NamespaceHandlerSupport implements NamespaceHandler {
/**
* Stores the {@link BeanDefinitionParser} implementations keyed by the
* local name of the {@link Element Elements} they handle.
*/
private final Map<String, BeanDefinitionParser> parsers =
new HashMap<String, BeanDefinitionParser>();
/**
* Stores the {@link BeanDefinitionDecorator} implementations keyed by the
* local name of the {@link Element Elements} they handle.
*/
private final Map<String, BeanDefinitionDecorator> decorators =
new HashMap<String, BeanDefinitionDecorator>();
/**
* Stores the {@link BeanDefinitionDecorator} implementations keyed by the local
* name of the {@link Attr Attrs} they handle.
*/
private final Map<String, BeanDefinitionDecorator> attributeDecorators =
new HashMap<String, BeanDefinitionDecorator>();
/**
* Parses the supplied {@link Element} by delegating to the {@link BeanDefinitionParser} that is
* registered for that {@link Element}.
*/
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
return findParserForElement(element, parserContext).parse(element, parserContext);
}
/**
* Locates the {@link BeanDefinitionParser} from the register implementations using
* the local name of the supplied {@link Element}.
*/
private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
String localName = parserContext.getDelegate().getLocalName(element);
BeanDefinitionParser parser = this.parsers.get(localName);
if (parser == null) {
parserContext.getReaderContext().fatal(
"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
}
return parser;
}
/**
* Decorates the supplied {@link Node} by delegating to the {@link BeanDefinitionDecorator} that
* is registered to handle that {@link Node}.
*/
@Override
public BeanDefinitionHolder decorate(
Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
return findDecoratorForNode(node, parserContext).decorate(node, definition, parserContext);
}
/**
* Locates the {@link BeanDefinitionParser} from the register implementations using
* the local name of the supplied {@link Node}. Supports both {@link Element Elements}
* and {@link Attr Attrs}.
*/
private BeanDefinitionDecorator findDecoratorForNode(Node node, ParserContext parserContext) {
BeanDefinitionDecorator decorator = null;
String localName = parserContext.getDelegate().getLocalName(node);
if (node instanceof Element) {
decorator = this.decorators.get(localName);
}
else if (node instanceof Attr) {
decorator = this.attributeDecorators.get(localName);
}
else {
parserContext.getReaderContext().fatal(
"Cannot decorate based on Nodes of type [" + node.getClass().getName() + "]", node);
}
if (decorator == null) {
parserContext.getReaderContext().fatal("Cannot locate BeanDefinitionDecorator for " +
(node instanceof Element ? "element" : "attribute") + " [" + localName + "]", node);
}
return decorator;
}
/**
* Subclasses can call this to register the supplied {@link BeanDefinitionParser} to
* handle the specified element. The element name is the local (non-namespace qualified)
* name.
*/
protected final void registerBeanDefinitionParser(String elementName, BeanDefinitionParser parser) {
this.parsers.put(elementName, parser);
}
/**
* Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to
* handle the specified element. The element name is the local (non-namespace qualified)
* name.
*/
protected final void registerBeanDefinitionDecorator(String elementName, BeanDefinitionDecorator dec) {
this.decorators.put(elementName, dec);
}
/**
* Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to
* handle the specified attribute. The attribute name is the local (non-namespace qualified)
* name.
*/
protected final void registerBeanDefinitionDecoratorForAttribute(String attrName, BeanDefinitionDecorator dec) {
this.attributeDecorators.put(attrName, dec);
}
}
| sunpy1106/SpringBeanLifeCycle | src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java | Java | apache-2.0 | 5,803 |
// Copyright JS Foundation and other contributors, http://js.foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const obj = {};
var a = { a : (o) = 1 } = obj;
assert (a === obj);
assert (o === 1);
| jerryscript-project/jerryscript | tests/jerry/regression-test-issue-3935.js | JavaScript | apache-2.0 | 716 |
/**
* 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.fs.s3native;
import static org.apache.hadoop.fs.s3native.NativeS3FileSystem.PATH_DELIMITER;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.s3.S3Credentials;
import org.apache.hadoop.fs.s3.S3Exception;
import org.jets3t.service.S3Service;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.ServiceException;
import org.jets3t.service.StorageObjectsChunk;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.MultipartPart;
import org.jets3t.service.model.MultipartUpload;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageObject;
import org.jets3t.service.security.AWSCredentials;
import org.jets3t.service.utils.MultipartUtils;
@InterfaceAudience.Private
@InterfaceStability.Unstable
class Jets3tNativeFileSystemStore implements NativeFileSystemStore {
private S3Service s3Service;
private S3Bucket bucket;
private long multipartBlockSize;
private boolean multipartEnabled;
private long multipartCopyBlockSize;
static final long MAX_PART_SIZE = (long)5 * 1024 * 1024 * 1024;
public static final Log LOG =
LogFactory.getLog(Jets3tNativeFileSystemStore.class);
@Override
public void initialize(URI uri, Configuration conf) throws IOException {
S3Credentials s3Credentials = new S3Credentials();
s3Credentials.initialize(uri, conf);
try {
AWSCredentials awsCredentials =
new AWSCredentials(s3Credentials.getAccessKey(),
s3Credentials.getSecretAccessKey());
this.s3Service = new RestS3Service(awsCredentials);
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
multipartEnabled =
conf.getBoolean("fs.s3n.multipart.uploads.enabled", false);
multipartBlockSize = Math.min(
conf.getLong("fs.s3n.multipart.uploads.block.size", 64 * 1024 * 1024),
MAX_PART_SIZE);
multipartCopyBlockSize = Math.min(
conf.getLong("fs.s3n.multipart.copy.block.size", MAX_PART_SIZE),
MAX_PART_SIZE);
bucket = new S3Bucket(uri.getHost());
}
@Override
public void storeFile(String key, File file, byte[] md5Hash)
throws IOException {
if (multipartEnabled && file.length() >= multipartBlockSize) {
storeLargeFile(key, file, md5Hash);
return;
}
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
S3Object object = new S3Object(key);
object.setDataInputStream(in);
object.setContentType("binary/octet-stream");
object.setContentLength(file.length());
if (md5Hash != null) {
object.setMd5Hash(md5Hash);
}
s3Service.putObject(bucket, object);
} catch (S3ServiceException e) {
handleS3ServiceException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
}
public void storeLargeFile(String key, File file, byte[] md5Hash)
throws IOException {
S3Object object = new S3Object(key);
object.setDataInputFile(file);
object.setContentType("binary/octet-stream");
object.setContentLength(file.length());
if (md5Hash != null) {
object.setMd5Hash(md5Hash);
}
List<StorageObject> objectsToUploadAsMultipart =
new ArrayList<StorageObject>();
objectsToUploadAsMultipart.add(object);
MultipartUtils mpUtils = new MultipartUtils(multipartBlockSize);
try {
mpUtils.uploadObjects(bucket.getName(), s3Service,
objectsToUploadAsMultipart, null);
} catch (ServiceException e) {
handleServiceException(e);
} catch (Exception e) {
throw new S3Exception(e);
}
}
@Override
public void storeEmptyFile(String key) throws IOException {
try {
S3Object object = new S3Object(key);
object.setDataInputStream(new ByteArrayInputStream(new byte[0]));
object.setContentType("binary/octet-stream");
object.setContentLength(0);
s3Service.putObject(bucket, object);
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
}
@Override
public FileMetadata retrieveMetadata(String key) throws IOException {
StorageObject object = null;
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Getting metadata for key: " + key + " from bucket:" + bucket.getName());
}
object = s3Service.getObjectDetails(bucket.getName(), key);
return new FileMetadata(key, object.getContentLength(),
object.getLastModifiedDate().getTime());
} catch (ServiceException e) {
// Following is brittle. Is there a better way?
if ("NoSuchKey".equals(e.getErrorCode())) {
return null; //return null if key not found
}
handleServiceException(e);
return null; //never returned - keep compiler happy
} finally {
if (object != null) {
object.closeDataInputStream();
}
}
}
/**
* @param key
* The key is the object name that is being retrieved from the S3 bucket
* @return
* This method returns null if the key is not found
* @throws IOException
*/
@Override
public InputStream retrieve(String key) throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Getting key: " + key + " from bucket:" + bucket.getName());
}
S3Object object = s3Service.getObject(bucket.getName(), key);
return object.getDataInputStream();
} catch (ServiceException e) {
handleServiceException(key, e);
return null; //return null if key not found
}
}
/**
*
* @param key
* The key is the object name that is being retrieved from the S3 bucket
* @return
* This method returns null if the key is not found
* @throws IOException
*/
@Override
public InputStream retrieve(String key, long byteRangeStart)
throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Getting key: " + key + " from bucket:" + bucket.getName() + " with byteRangeStart: " + byteRangeStart);
}
S3Object object = s3Service.getObject(bucket, key, null, null, null,
null, byteRangeStart, null);
return object.getDataInputStream();
} catch (ServiceException e) {
handleServiceException(key, e);
return null; //return null if key not found
}
}
@Override
public PartialListing list(String prefix, int maxListingLength)
throws IOException {
return list(prefix, maxListingLength, null, false);
}
@Override
public PartialListing list(String prefix, int maxListingLength, String priorLastKey,
boolean recurse) throws IOException {
return list(prefix, recurse ? null : PATH_DELIMITER, maxListingLength, priorLastKey);
}
/**
*
* @return
* This method returns null if the list could not be populated
* due to S3 giving ServiceException
* @throws IOException
*/
private PartialListing list(String prefix, String delimiter,
int maxListingLength, String priorLastKey) throws IOException {
try {
if (prefix.length() > 0 && !prefix.endsWith(PATH_DELIMITER)) {
prefix += PATH_DELIMITER;
}
StorageObjectsChunk chunk = s3Service.listObjectsChunked(bucket.getName(),
prefix, delimiter, maxListingLength, priorLastKey);
FileMetadata[] fileMetadata =
new FileMetadata[chunk.getObjects().length];
for (int i = 0; i < fileMetadata.length; i++) {
StorageObject object = chunk.getObjects()[i];
fileMetadata[i] = new FileMetadata(object.getKey(),
object.getContentLength(), object.getLastModifiedDate().getTime());
}
return new PartialListing(chunk.getPriorLastKey(), fileMetadata,
chunk.getCommonPrefixes());
} catch (S3ServiceException e) {
handleS3ServiceException(e);
return null; //never returned - keep compiler happy
} catch (ServiceException e) {
handleServiceException(e);
return null; //return null if list could not be populated
}
}
@Override
public void delete(String key) throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Deleting key:" + key + "from bucket" + bucket.getName());
}
s3Service.deleteObject(bucket, key);
} catch (ServiceException e) {
handleServiceException(key, e);
}
}
public void rename(String srcKey, String dstKey) throws IOException {
try {
s3Service.renameObject(bucket.getName(), srcKey, new S3Object(dstKey));
} catch (ServiceException e) {
handleServiceException(e);
}
}
@Override
public void copy(String srcKey, String dstKey) throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Copying srcKey: " + srcKey + "to dstKey: " + dstKey + "in bucket: " + bucket.getName());
}
if (multipartEnabled) {
S3Object object = s3Service.getObjectDetails(bucket, srcKey, null,
null, null, null);
if (multipartCopyBlockSize > 0 &&
object.getContentLength() > multipartCopyBlockSize) {
copyLargeFile(object, dstKey);
return;
}
}
s3Service.copyObject(bucket.getName(), srcKey, bucket.getName(),
new S3Object(dstKey), false);
} catch (ServiceException e) {
handleServiceException(srcKey, e);
}
}
public void copyLargeFile(S3Object srcObject, String dstKey) throws IOException {
try {
long partCount = srcObject.getContentLength() / multipartCopyBlockSize +
(srcObject.getContentLength() % multipartCopyBlockSize > 0 ? 1 : 0);
MultipartUpload multipartUpload = s3Service.multipartStartUpload
(bucket.getName(), dstKey, srcObject.getMetadataMap());
List<MultipartPart> listedParts = new ArrayList<MultipartPart>();
for (int i = 0; i < partCount; i++) {
long byteRangeStart = i * multipartCopyBlockSize;
long byteLength;
if (i < partCount - 1) {
byteLength = multipartCopyBlockSize;
} else {
byteLength = srcObject.getContentLength() % multipartCopyBlockSize;
if (byteLength == 0) {
byteLength = multipartCopyBlockSize;
}
}
MultipartPart copiedPart = s3Service.multipartUploadPartCopy
(multipartUpload, i + 1, bucket.getName(), srcObject.getKey(),
null, null, null, null, byteRangeStart,
byteRangeStart + byteLength - 1, null);
listedParts.add(copiedPart);
}
Collections.reverse(listedParts);
s3Service.multipartCompleteUpload(multipartUpload, listedParts);
} catch (ServiceException e) {
handleServiceException(e);
}
}
@Override
public void purge(String prefix) throws IOException {
try {
S3Object[] objects = s3Service.listObjects(bucket.getName(), prefix, null);
for (S3Object object : objects) {
s3Service.deleteObject(bucket, object.getKey());
}
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
}
@Override
public void dump() throws IOException {
StringBuilder sb = new StringBuilder("S3 Native Filesystem, ");
sb.append(bucket.getName()).append("\n");
try {
S3Object[] objects = s3Service.listObjects(bucket.getName());
for (S3Object object : objects) {
sb.append(object.getKey()).append("\n");
}
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
System.out.println(sb);
}
private void handleServiceException(String key, ServiceException e) throws IOException {
if ("NoSuchKey".equals(e.getErrorCode())) {
throw new FileNotFoundException("Key '" + key + "' does not exist in S3");
} else {
handleServiceException(e);
}
}
private void handleS3ServiceException(S3ServiceException e) throws IOException {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
else {
if(LOG.isDebugEnabled()) {
LOG.debug("S3 Error code: " + e.getS3ErrorCode() + "; S3 Error message: " + e.getS3ErrorMessage());
}
throw new S3Exception(e);
}
}
private void handleServiceException(ServiceException e) throws IOException {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
else {
if(LOG.isDebugEnabled()) {
LOG.debug("Got ServiceException with Error code: " + e.getErrorCode() + ";and Error message: " + e.getErrorMessage());
}
}
}
}
| songweijia/fffs | sources/hadoop-2.4.1-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/s3native/Jets3tNativeFileSystemStore.java | Java | apache-2.0 | 14,116 |
# Copyright 2014-2015 Canonical Limited.
#
# 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.
# Bootstrap charm-helpers, installing its dependencies if necessary using
# only standard libraries.
import subprocess
import sys
try:
import six # flake8: noqa
except ImportError:
if sys.version_info.major == 2:
subprocess.check_call(['apt-get', 'install', '-y', 'python-six'])
else:
subprocess.check_call(['apt-get', 'install', '-y', 'python3-six'])
import six # flake8: noqa
try:
import yaml # flake8: noqa
except ImportError:
if sys.version_info.major == 2:
subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml'])
else:
subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml'])
import yaml # flake8: noqa
| CanonicalBootStack/charm-hacluster | tests/charmhelpers/__init__.py | Python | apache-2.0 | 1,285 |
/*
* 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.cassandra.auth;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Iterables;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.service.StorageService;
import static org.apache.cassandra.auth.AuthTestUtils.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CassandraRoleManagerTest
{
@BeforeClass
public static void setupClass()
{
SchemaLoader.prepareServer();
// create the system_auth keyspace so the IRoleManager can function as normal
SchemaLoader.createKeyspace(SchemaConstants.AUTH_KEYSPACE_NAME,
KeyspaceParams.simple(1),
Iterables.toArray(AuthKeyspace.metadata().tables, TableMetadata.class));
// We start StorageService because confirmFastRoleSetup confirms that CassandraRoleManager will
// take a faster path once the cluster is already setup, which includes checking MessagingService
// and issuing queries with QueryProcessor.process, which uses TokenMetadata
DatabaseDescriptor.daemonInitialization();
StorageService.instance.initServer(0);
AuthCacheService.initializeAndRegisterCaches();
}
@Before
public void setup() throws Exception
{
ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES).truncateBlocking();
ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS).truncateBlocking();
}
@Test
public void getGrantedRolesImplMinimizesReads()
{
// IRoleManager::getRoleDetails was not in the initial API, so a default impl
// was added which uses the existing methods on IRoleManager as primitive to
// construct the Role objects. While this will work for any IRoleManager impl
// it is inefficient, so CassandraRoleManager has its own implementation which
// collects all of the necessary info with a single query for each granted role.
// This just tests that that is the case, i.e. we perform 1 read per role in the
// transitive set of granted roles
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
// simple role with no grants
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// single level of grants
grantRolesTo(roleManager, ROLE_A, ROLE_B, ROLE_C);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// multi level role hierarchy
grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// Check that when granted roles appear multiple times in parallel levels of the hierarchy, we don't
// do redundant reads. E.g. here role_b_1, role_b_2 and role_b3 are granted to both role_b and role_c
// but we only want to actually read them once
grantRolesTo(roleManager, ROLE_C, ROLE_B_1, ROLE_B_2, ROLE_B_3);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
}
private void fetchRolesAndCheckReadCount(IRoleManager roleManager, RoleResource primaryRole)
{
long before = getRolesReadCount();
Set<Role> granted = roleManager.getRoleDetails(primaryRole);
long after = getRolesReadCount();
assertEquals(granted.size(), after - before);
}
@Test
public void confirmFastRoleSetup()
{
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
CassandraRoleManager crm = new CassandraRoleManager();
assertTrue("Expected the role manager to have existing roles before CassandraRoleManager setup", CassandraRoleManager.hasExistingRoles());
}
@Test
public void warmCacheLoadsAllEntries()
{
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
// Multi level role hierarchy
grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
// Use CassandraRoleManager to get entries for pre-warming a cache, then verify those entries
CassandraRoleManager crm = new CassandraRoleManager();
crm.setup();
Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get();
Set<Role> roleBRoles = cacheEntries.get(ROLE_B);
assertRoleSet(roleBRoles, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
Set<Role> roleCRoles = cacheEntries.get(ROLE_C);
assertRoleSet(roleCRoles, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
for (RoleResource r : ALL_ROLES)
{
// We already verified ROLE_B and ROLE_C
if (r.equals(ROLE_B) || r.equals(ROLE_C))
continue;
// Check the cache entries for the roles without any further grants
assertRoleSet(cacheEntries.get(r), r);
}
}
@Test
public void warmCacheWithEmptyTable()
{
CassandraRoleManager crm = new CassandraRoleManager();
crm.setup();
Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get();
assertTrue(cacheEntries.isEmpty());
}
private void assertRoleSet(Set<Role> actual, RoleResource...expected)
{
assertEquals(expected.length, actual.size());
for (RoleResource expectedRole : expected)
assertTrue(actual.stream().anyMatch(role -> role.resource.equals(expectedRole)));
}
}
| belliottsmith/cassandra | test/unit/org/apache/cassandra/auth/CassandraRoleManagerTest.java | Java | apache-2.0 | 7,254 |
<?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.
*/
class Google_Service_CloudKMS_KeyOperationAttestation extends Google_Model
{
protected $certChainsType = 'Google_Service_CloudKMS_CertificateChains';
protected $certChainsDataType = '';
public $content;
public $format;
/**
* @param Google_Service_CloudKMS_CertificateChains
*/
public function setCertChains(Google_Service_CloudKMS_CertificateChains $certChains)
{
$this->certChains = $certChains;
}
/**
* @return Google_Service_CloudKMS_CertificateChains
*/
public function getCertChains()
{
return $this->certChains;
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
}
| tsugiproject/tsugi | vendor/google/apiclient-services/src/Google/Service/CloudKMS/KeyOperationAttestation.php | PHP | apache-2.0 | 1,447 |
/**
* Copyright 2015-2017 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
*
* 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.wildfly.swarm.datasources.runtime.drivers;
import org.wildfly.swarm.config.datasources.DataSource;
import org.wildfly.swarm.datasources.runtime.DriverInfo;
/**
* Auto-detection for Apache Hive
*
* @author Kylin Soong
*/
public class Hive2DriverInfo extends DriverInfo {
public static final String DEFAULT_CONNETION_URL = "jdbc:hive2://localhost:10000/default";
public static final String DEFAULT_USER_NAME = "sa";
public static final String DEFAULT_PASSWORD = "sa";
protected Hive2DriverInfo() {
super("hive2", "org.apache.hive.jdbc", "org.apache.hive.jdbc.HiveDriver");
}
@Override
protected void configureDefaultDS(DataSource datasource) {
datasource.connectionUrl(DEFAULT_CONNETION_URL);
datasource.userName(DEFAULT_USER_NAME);
datasource.password(DEFAULT_PASSWORD);
}
}
| swarmsandbox/wildfly-swarm | fractions/javaee/datasources/src/main/java/org/wildfly/swarm/datasources/runtime/drivers/Hive2DriverInfo.java | Java | apache-2.0 | 1,490 |
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
/**
*
* Indicates whether Contact Seller is enabled for Classified Ads.
* Added for EbayMotors Pro users.
*
*/
public class EBayMotorsProBestOfferEnabledDefinitionType implements Serializable {
private static final long serialVersionUID = -1L;
@AnyElement
@Order(value=0)
public List<Object> any;
} | uaraven/nano | sample/webservice/eBayDemoApp/src/com/ebay/trading/api/EBayMotorsProBestOfferEnabledDefinitionType.java | Java | apache-2.0 | 509 |
package useridentitymapping
import (
"fmt"
kapi "k8s.io/kubernetes/pkg/api"
kerrs "k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/rest"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/fielderrors"
"k8s.io/kubernetes/pkg/util/sets"
"github.com/openshift/origin/pkg/user/api"
"github.com/openshift/origin/pkg/user/registry/identity"
"github.com/openshift/origin/pkg/user/registry/user"
)
// REST implements the RESTStorage interface in terms of an image registry and
// image repository registry. It only supports the Create method and is used
// to simplify adding a new Image and tag to an ImageRepository.
type REST struct {
userRegistry user.Registry
identityRegistry identity.Registry
}
// NewREST returns a new REST.
func NewREST(userRegistry user.Registry, identityRegistry identity.Registry) *REST {
return &REST{userRegistry: userRegistry, identityRegistry: identityRegistry}
}
// New returns a new UserIdentityMapping for use with Create.
func (r *REST) New() runtime.Object {
return &api.UserIdentityMapping{}
}
// Get returns the mapping for the named identity
func (s *REST) Get(ctx kapi.Context, name string) (runtime.Object, error) {
_, _, _, _, mapping, err := s.getRelatedObjects(ctx, name)
return mapping, err
}
// Create associates a user and identity if they both exist, and the identity is not already mapped to a user
func (s *REST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {
mapping, ok := obj.(*api.UserIdentityMapping)
if !ok {
return nil, kerrs.NewBadRequest("invalid type")
}
Strategy.PrepareForCreate(mapping)
createdMapping, _, err := s.createOrUpdate(ctx, obj, true)
return createdMapping, err
}
// Update associates an identity with a user.
// Both the identity and user must already exist.
// If the identity is associated with another user already, it is disassociated.
func (s *REST) Update(ctx kapi.Context, obj runtime.Object) (runtime.Object, bool, error) {
mapping, ok := obj.(*api.UserIdentityMapping)
if !ok {
return nil, false, kerrs.NewBadRequest("invalid type")
}
Strategy.PrepareForUpdate(mapping, nil)
return s.createOrUpdate(ctx, mapping, false)
}
func (s *REST) createOrUpdate(ctx kapi.Context, obj runtime.Object, forceCreate bool) (runtime.Object, bool, error) {
mapping := obj.(*api.UserIdentityMapping)
identity, identityErr, oldUser, oldUserErr, oldMapping, oldMappingErr := s.getRelatedObjects(ctx, mapping.Name)
// Ensure we didn't get any errors other than NotFound errors
if !(oldMappingErr == nil || kerrs.IsNotFound(oldMappingErr)) {
return nil, false, oldMappingErr
}
if !(identityErr == nil || kerrs.IsNotFound(identityErr)) {
return nil, false, identityErr
}
if !(oldUserErr == nil || kerrs.IsNotFound(oldUserErr)) {
return nil, false, oldUserErr
}
// If we expect to be creating, fail if the mapping already existed
if forceCreate && oldMappingErr == nil {
return nil, false, kerrs.NewAlreadyExists("UserIdentityMapping", oldMapping.Name)
}
// Allow update to create if missing
creating := forceCreate || kerrs.IsNotFound(oldMappingErr)
if creating {
// Pre-create checks with no access to oldMapping
if err := rest.BeforeCreate(Strategy, ctx, mapping); err != nil {
return nil, false, err
}
// Ensure resource version is not specified
if len(mapping.ResourceVersion) > 0 {
return nil, false, kerrs.NewNotFound("UserIdentityMapping", mapping.Name)
}
} else {
// Pre-update checks with access to oldMapping
if err := rest.BeforeUpdate(Strategy, ctx, mapping, oldMapping); err != nil {
return nil, false, err
}
// Ensure resource versions match
if len(mapping.ResourceVersion) > 0 && mapping.ResourceVersion != oldMapping.ResourceVersion {
return nil, false, kerrs.NewConflict("UserIdentityMapping", mapping.Name, fmt.Errorf("the resource was updated to %s", oldMapping.ResourceVersion))
}
// If we're "updating" to the user we're already pointing to, we're already done
if mapping.User.Name == oldMapping.User.Name {
return oldMapping, false, nil
}
}
// Validate identity
if kerrs.IsNotFound(identityErr) {
errs := fielderrors.ValidationErrorList([]error{
fielderrors.NewFieldInvalid("identity.name", mapping.Identity.Name, "referenced identity does not exist"),
})
return nil, false, kerrs.NewInvalid("UserIdentityMapping", mapping.Name, errs)
}
// Get new user
newUser, err := s.userRegistry.GetUser(ctx, mapping.User.Name)
if kerrs.IsNotFound(err) {
errs := fielderrors.ValidationErrorList([]error{
fielderrors.NewFieldInvalid("user.name", mapping.User.Name, "referenced user does not exist"),
})
return nil, false, kerrs.NewInvalid("UserIdentityMapping", mapping.Name, errs)
}
if err != nil {
return nil, false, err
}
// Update the new user to point at the identity. If this fails, Update is re-entrant
if addIdentityToUser(identity, newUser) {
if _, err := s.userRegistry.UpdateUser(ctx, newUser); err != nil {
return nil, false, err
}
}
// Update the identity to point at the new user. If this fails. Update is re-entrant
if setIdentityUser(identity, newUser) {
if updatedIdentity, err := s.identityRegistry.UpdateIdentity(ctx, identity); err != nil {
return nil, false, err
} else {
identity = updatedIdentity
}
}
// At this point, the mapping for the identity has been updated to the new user
// Everything past this point is cleanup
// Update the old user to no longer point at the identity.
// If this fails, log the error, but continue, because Update is no longer re-entrant
if oldUser != nil && removeIdentityFromUser(identity, oldUser) {
if _, err := s.userRegistry.UpdateUser(ctx, oldUser); err != nil {
util.HandleError(fmt.Errorf("error removing identity reference %s from user %s: %v", identity.Name, oldUser.Name, err))
}
}
updatedMapping, err := mappingFor(newUser, identity)
return updatedMapping, creating, err
}
// Delete deletes the user association for the named identity
func (s *REST) Delete(ctx kapi.Context, name string) (runtime.Object, error) {
identity, _, user, _, _, mappingErr := s.getRelatedObjects(ctx, name)
if mappingErr != nil {
return nil, mappingErr
}
// Disassociate the identity with the user first
// If this fails, Delete is re-entrant
if removeIdentityFromUser(identity, user) {
if _, err := s.userRegistry.UpdateUser(ctx, user); err != nil {
return nil, err
}
}
// Remove the user association from the identity last.
// If this fails, log the error, but continue, because Delete is no longer re-entrant
// At this point, the mapping for the identity no longer exists
if unsetIdentityUser(identity) {
if _, err := s.identityRegistry.UpdateIdentity(ctx, identity); err != nil {
util.HandleError(fmt.Errorf("error removing user reference %s from identity %s: %v", user.Name, identity.Name, err))
}
}
return &kapi.Status{Status: kapi.StatusSuccess}, nil
}
// getRelatedObjects returns the identity, user, and mapping for the named identity
// a nil mappingErr means all objects were retrieved without errors, and correctly reference each other
func (s *REST) getRelatedObjects(ctx kapi.Context, name string) (
identity *api.Identity, identityErr error,
user *api.User, userErr error,
mapping *api.UserIdentityMapping, mappingErr error,
) {
// Initialize errors to NotFound
identityErr = kerrs.NewNotFound("Identity", name)
userErr = kerrs.NewNotFound("User", "")
mappingErr = kerrs.NewNotFound("UserIdentityMapping", name)
// Get identity
identity, identityErr = s.identityRegistry.GetIdentity(ctx, name)
if identityErr != nil {
return
}
if !hasUserMapping(identity) {
return
}
// Get user
user, userErr = s.userRegistry.GetUser(ctx, identity.User.Name)
if userErr != nil {
return
}
// Ensure relational integrity
if !identityReferencesUser(identity, user) {
return
}
if !userReferencesIdentity(user, identity) {
return
}
mapping, mappingErr = mappingFor(user, identity)
return
}
// hasUserMapping returns true if the given identity references a user
func hasUserMapping(identity *api.Identity) bool {
return len(identity.User.Name) > 0
}
// identityReferencesUser returns true if the identity's user name and uid match the given user
func identityReferencesUser(identity *api.Identity, user *api.User) bool {
return identity.User.Name == user.Name && identity.User.UID == user.UID
}
// userReferencesIdentity returns true if the user's identity list contains the given identity
func userReferencesIdentity(user *api.User, identity *api.Identity) bool {
return sets.NewString(user.Identities...).Has(identity.Name)
}
// addIdentityToUser adds the given identity to the user's list of identities
// returns true if the user's identity list was modified
func addIdentityToUser(identity *api.Identity, user *api.User) bool {
identities := sets.NewString(user.Identities...)
if identities.Has(identity.Name) {
return false
}
identities.Insert(identity.Name)
user.Identities = identities.List()
return true
}
// removeIdentityFromUser removes the given identity from the user's list of identities
// returns true if the user's identity list was modified
func removeIdentityFromUser(identity *api.Identity, user *api.User) bool {
identities := sets.NewString(user.Identities...)
if !identities.Has(identity.Name) {
return false
}
identities.Delete(identity.Name)
user.Identities = identities.List()
return true
}
// setIdentityUser sets the identity to reference the given user
// returns true if the identity's user reference was modified
func setIdentityUser(identity *api.Identity, user *api.User) bool {
if identityReferencesUser(identity, user) {
return false
}
identity.User = kapi.ObjectReference{
Name: user.Name,
UID: user.UID,
}
return true
}
// unsetIdentityUser clears the identity's user reference
// returns true if the identity's user reference was modified
func unsetIdentityUser(identity *api.Identity) bool {
if !hasUserMapping(identity) {
return false
}
identity.User = kapi.ObjectReference{}
return true
}
// mappingFor returns a UserIdentityMapping for the given user and identity
// The name and resource version of the identity mapping match the identity
func mappingFor(user *api.User, identity *api.Identity) (*api.UserIdentityMapping, error) {
return &api.UserIdentityMapping{
ObjectMeta: kapi.ObjectMeta{
Name: identity.Name,
ResourceVersion: identity.ResourceVersion,
UID: identity.UID,
},
Identity: kapi.ObjectReference{
Name: identity.Name,
UID: identity.UID,
},
User: kapi.ObjectReference{
Name: user.Name,
UID: user.UID,
},
}, nil
}
| vongalpha/origin | pkg/user/registry/useridentitymapping/rest.go | GO | apache-2.0 | 10,722 |
// ----------------------------------------------------------------------------------
//
// 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 System.Management.Automation;
using Microsoft.Azure.Commands.TrafficManager.Models;
using Microsoft.Azure.Commands.TrafficManager.Utilities;
using ProjectResources = Microsoft.Azure.Commands.TrafficManager.Properties.Resources;
namespace Microsoft.Azure.Commands.TrafficManager
{
[Cmdlet(VerbsCommon.Remove, "AzureRmTrafficManagerEndpointConfig"), OutputType(typeof(TrafficManagerProfile))]
public class RemoveAzureTrafficManagerEndpointConfig : TrafficManagerBaseCmdlet
{
[Parameter(Mandatory = true, HelpMessage = "The name of the endpoint.")]
[ValidateNotNullOrEmpty]
public string EndpointName { get; set; }
[Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The profile.")]
[ValidateNotNullOrEmpty]
public TrafficManagerProfile TrafficManagerProfile { get; set; }
public override void ExecuteCmdlet()
{
if (this.TrafficManagerProfile.Endpoints == null)
{
throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName));
}
int endpointsRemoved = this.TrafficManagerProfile.Endpoints.RemoveAll(endpoint => string.Equals(this.EndpointName, endpoint.Name));
if (endpointsRemoved == 0)
{
throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName));
}
this.WriteVerbose(ProjectResources.Success);
this.WriteObject(this.TrafficManagerProfile);
}
}
}
| dulems/azure-powershell | src/ResourceManager/TrafficManager/Commands.TrafficManager2/Endpoint/RemoveAzureTrafficManagerEndpointConfig.cs | C# | apache-2.0 | 2,353 |
cask 'hunt-x' do
version :latest
sha256 :no_check
url 'http://huntx.mobilefirst.in/Apps/Hunt%20X.zip'
name 'Hunt X'
homepage 'http://huntx.mobilefirst.in/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Hunt X.app'
end
| jppelteret/homebrew-cask | Casks/hunt-x.rb | Ruby | bsd-2-clause | 307 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding-for-await/obj-ptrn-prop-ary.case
// - src/dstr-binding-for-await/default/for-await-of-async-func-var.template
/*---
description: Object binding pattern with "nested" array binding pattern not using initializer (for-await-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( var ForBinding of AssignmentExpression ) Statement
[...]
2. Return ? ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult,
varBinding, labelSet, async).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. Let destructuring be IsDestructuring of lhs.
[...]
6. Repeat
[...]
j. If destructuring is false, then
[...]
k. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
1. Assert: lhs is a ForBinding.
2. Let status be the result of performing BindingInitialization
for lhs passing nextValue and undefined as the arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
[...]
3. If Initializer is present and v is undefined, then
[...]
4. Return the result of performing BindingInitialization for BindingPattern
passing v and environment as arguments.
---*/
var iterCount = 0;
async function fn() {
for await (var { w: [x, y, z] = [4, 5, 6] } of [{ w: [7, undefined, ] }]) {
assert.sameValue(x, 7);
assert.sameValue(y, undefined);
assert.sameValue(z, undefined);
assert.throws(ReferenceError, function() {
w;
});
iterCount += 1;
}
}
fn()
.then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE)
.then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-await-of/async-func-dstr-var-obj-ptrn-prop-ary.js | JavaScript | bsd-2-clause | 1,967 |
/*
* Copyright 2010-2017 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bx#license-bsd-2-clause
*/
#include "test.h"
#include <bx/handlealloc.h>
#include <bx/hash.h>
TEST_CASE("HandleListT", "")
{
bx::HandleListT<32> list;
list.pushBack(16);
REQUIRE(list.getFront() == 16);
REQUIRE(list.getBack() == 16);
list.pushFront(7);
REQUIRE(list.getFront() == 7);
REQUIRE(list.getBack() == 16);
uint16_t expected0[] = { 15, 31, 7, 16, 17, 11, 13 };
list.pushBack(17);
list.pushBack(11);
list.pushBack(13);
list.pushFront(31);
list.pushFront(15);
uint16_t count = 0;
for (uint16_t it = list.getFront(); it != UINT16_MAX; it = list.getNext(it), ++count)
{
REQUIRE(it == expected0[count]);
}
REQUIRE(count == BX_COUNTOF(expected0) );
list.remove(17);
list.remove(31);
list.remove(16);
list.pushBack(16);
uint16_t expected1[] = { 15, 7, 11, 13, 16 };
count = 0;
for (uint16_t it = list.getFront(); it != UINT16_MAX; it = list.getNext(it), ++count)
{
REQUIRE(it == expected1[count]);
}
REQUIRE(count == BX_COUNTOF(expected1) );
list.popBack();
list.popFront();
list.popBack();
list.popBack();
REQUIRE(list.getFront() == 7);
REQUIRE(list.getBack() == 7);
list.popBack();
REQUIRE(list.getFront() == UINT16_MAX);
REQUIRE(list.getBack() == UINT16_MAX);
}
TEST_CASE("HandleAllocLruT", "")
{
bx::HandleAllocLruT<16> lru;
uint16_t handle[4] =
{
lru.alloc(),
lru.alloc(),
lru.alloc(),
lru.alloc(),
};
lru.touch(handle[1]);
uint16_t expected0[] = { handle[1], handle[3], handle[2], handle[0] };
uint16_t count = 0;
for (uint16_t it = lru.getFront(); it != UINT16_MAX; it = lru.getNext(it), ++count)
{
REQUIRE(it == expected0[count]);
}
}
TEST_CASE("HandleHashTable", "")
{
typedef bx::HandleHashMapT<512> HashMap;
HashMap hm;
REQUIRE(512 == hm.getMaxCapacity() );
bx::StringView sv0("test0");
bool ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(ok);
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(!ok);
REQUIRE(1 == hm.getNumElements() );
bx::StringView sv1("test1");
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv1), 0);
REQUIRE(ok);
REQUIRE(2 == hm.getNumElements() );
hm.removeByHandle(0);
REQUIRE(0 == hm.getNumElements() );
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(ok);
hm.removeByKey(bx::hash<bx::HashMurmur2A>(sv0) );
REQUIRE(0 == hm.getNumElements() );
for (uint32_t ii = 0, num = hm.getMaxCapacity(); ii < num; ++ii)
{
ok = hm.insert(ii, uint16_t(ii) );
REQUIRE(ok);
}
}
| mmicko/bx | tests/handle_test.cpp | C++ | bsd-2-clause | 2,557 |
class Libwebsockets < Formula
desc "C websockets server library"
homepage "https://libwebsockets.org"
url "https://github.com/warmcat/libwebsockets/archive/v3.1.0.tar.gz"
sha256 "db948be74c78fc13f1f1a55e76707d7baae3a1c8f62b625f639e8f2736298324"
head "https://github.com/warmcat/libwebsockets.git"
bottle do
sha256 "c3dee13c27c98c87853ec9d1cbd3db27473c3fee1b0870260dc6c47294dd95e4" => :mojave
sha256 "fce83552c866222ad1386145cdd9745b82efc0c0a97b89b9069b98928241e893" => :high_sierra
sha256 "a57218f16bde1f484648fd7893d99d3dafc5c0ade4902c7ce442019b9782dc66" => :sierra
end
depends_on "cmake" => :build
depends_on "libevent"
depends_on "libuv"
depends_on "openssl"
def install
system "cmake", ".", *std_cmake_args,
"-DLWS_IPV6=ON",
"-DLWS_WITH_HTTP2=ON",
"-DLWS_WITH_LIBEVENT=ON",
"-DLWS_WITH_LIBUV=ON",
"-DLWS_WITH_PLUGINS=ON",
"-DLWS_WITHOUT_TESTAPPS=ON",
"-DLWS_UNIX_SOCK=ON"
system "make"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <openssl/ssl.h>
#include <libwebsockets.h>
int main()
{
struct lws_context_creation_info info;
memset(&info, 0, sizeof(info));
struct lws_context *context;
context = lws_create_context(&info);
lws_context_destroy(context);
return 0;
}
EOS
system ENV.cc, "test.c", "-I#{Formula["openssl"].opt_prefix}/include", "-L#{lib}", "-lwebsockets", "-o", "test"
system "./test"
end
end
| adamliter/homebrew-core | Formula/libwebsockets.rb | Ruby | bsd-2-clause | 1,637 |
#ifndef SM_PYTHON_ID_HPP
#define SM_PYTHON_ID_HPP
#include <numpy_eigen/boost_python_headers.hpp>
#include <boost/python/to_python_converter.hpp>
#include <Python.h>
#include <boost/cstdint.hpp>
namespace sm { namespace python {
// to use: sm::python::Id_python_converter<FrameId>::register_converter();
// adapted from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/
template<typename ID_T>
struct Id_python_converter
{
typedef ID_T id_t;
// The "Convert from C to Python" API
static PyObject * convert(id_t const & id){
PyObject * i = PyInt_FromLong(id.getId());
// It seems that the call to "incref(.)" caused a memory leak!
// I will check this in hoping it doesn't cause any instability.
return i;//boost::python::incref(i);
}
// The "Convert from Python to C" API
// Two functions: convertible() and construct()
static void * convertible(PyObject* obj_ptr)
{
if (!(PyInt_Check(obj_ptr) || PyLong_Check(obj_ptr)))
return 0;
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
// Get the value.
boost::uint64_t value;
if ( PyInt_Check(obj_ptr) ) {
value = PyInt_AsUnsignedLongLongMask(obj_ptr);
} else {
value = PyLong_AsUnsignedLongLong(obj_ptr);
}
void* storage = ((boost::python::converter::rvalue_from_python_storage<id_t>*)
data)->storage.bytes;
new (storage) id_t(value);
// Stash the memory chunk pointer for later use by boost.python
data->convertible = storage;
}
// The registration function.
static void register_converter()
{
// This code checks if the type has already been registered.
// http://stackoverflow.com/questions/9888289/checking-whether-a-converter-has-already-been-registered
boost::python::type_info info = boost::python::type_id<id_t>();
const boost::python::converter::registration* reg = boost::python::converter::registry::query(info);
if (reg == NULL || reg->m_to_python == NULL) {
// This is the code to register the type.
boost::python::to_python_converter<id_t,Id_python_converter>();
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<id_t>());
}
}
};
}}
#endif /* SM_PYTHON_ID_HPP */
| ethz-asl/Schweizer-Messer | sm_python/include/sm/python/Id.hpp | C++ | bsd-3-clause | 2,754 |
// Copyright (c) 2006-2008 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 "base/thread_local.h"
#include <pthread.h>
#include "base/logging.h"
namespace base {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
int error = pthread_key_create(&slot, NULL);
CHECK(error == 0);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
int error = pthread_key_delete(slot);
DCHECK(error == 0);
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
return pthread_getspecific(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
int error = pthread_setspecific(slot, value);
CHECK(error == 0);
}
} // namespace base
| balena/sandboxed | chrome/base/thread_local_posix.cc | C++ | bsd-3-clause | 826 |
// 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 "third_party/blink/renderer/core/paint/paint_invalidator.h"
#include "base/trace_event/trace_event.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_table.h"
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h"
#include "third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h"
#include "third_party/blink/renderer/core/page/link_highlight.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/pre_paint_tree_walk.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
namespace blink {
void PaintInvalidator::UpdatePaintingLayer(const LayoutObject& object,
PaintInvalidatorContext& context) {
if (object.HasLayer() &&
To<LayoutBoxModelObject>(object).HasSelfPaintingLayer()) {
context.painting_layer = To<LayoutBoxModelObject>(object).Layer();
} else if (object.IsColumnSpanAll() ||
object.IsFloatingWithNonContainingBlockParent()) {
// See |LayoutObject::PaintingLayer| for the special-cases of floating under
// inline and multicolumn.
// Post LayoutNG the |LayoutObject::IsFloatingWithNonContainingBlockParent|
// check can be removed as floats will be painted by the correct layer.
context.painting_layer = object.PaintingLayer();
}
auto* layout_block_flow = DynamicTo<LayoutBlockFlow>(object);
if (layout_block_flow && !object.IsLayoutNGBlockFlow() &&
layout_block_flow->ContainsFloats())
context.painting_layer->SetNeedsPaintPhaseFloat();
if (object.IsFloating() &&
(object.IsInLayoutNGInlineFormattingContext() ||
IsLayoutNGContainingBlock(object.ContainingBlock())))
context.painting_layer->SetNeedsPaintPhaseFloat();
if (!context.painting_layer->NeedsPaintPhaseDescendantOutlines() &&
((object != context.painting_layer->GetLayoutObject() &&
object.StyleRef().HasOutline()) ||
// If this is a block-in-inline, it may need to paint outline.
// See |StyleForContinuationOutline|.
(layout_block_flow && layout_block_flow->StyleForContinuationOutline())))
context.painting_layer->SetNeedsPaintPhaseDescendantOutlines();
}
void PaintInvalidator::UpdateFromTreeBuilderContext(
const PaintPropertyTreeBuilderFragmentContext& tree_builder_context,
PaintInvalidatorContext& context) {
DCHECK_EQ(tree_builder_context.current.paint_offset,
context.fragment_data->PaintOffset());
// For performance, we ignore subpixel movement of composited layers for paint
// invalidation. This will result in imperfect pixel-snapped painting.
// See crbug.com/833083 for details.
if (!RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() &&
tree_builder_context.current
.directly_composited_container_paint_offset_subpixel_delta ==
tree_builder_context.current.paint_offset -
tree_builder_context.old_paint_offset) {
context.old_paint_offset = tree_builder_context.current.paint_offset;
} else {
context.old_paint_offset = tree_builder_context.old_paint_offset;
}
context.transform_ = tree_builder_context.current.transform;
}
void PaintInvalidator::UpdateLayoutShiftTracking(
const LayoutObject& object,
const PaintPropertyTreeBuilderFragmentContext& tree_builder_context,
PaintInvalidatorContext& context) {
if (!object.ShouldCheckGeometryForPaintInvalidation())
return;
if (tree_builder_context.this_or_ancestor_opacity_is_zero ||
context.inside_opaque_layout_shift_root) {
object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true);
return;
}
auto& layout_shift_tracker = object.GetFrameView()->GetLayoutShiftTracker();
if (!layout_shift_tracker.NeedsToTrack(object)) {
object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true);
return;
}
PropertyTreeStateOrAlias property_tree_state(
*tree_builder_context.current.transform,
*tree_builder_context.current.clip, *tree_builder_context.current_effect);
// Adjust old_paint_offset so that LayoutShiftTracker will see the change of
// offset caused by change of paint offset translations and scroll offset
// below the layout shift root. For more details, see
// renderer/core/layout/layout-shift-tracker-old-paint-offset.md.
PhysicalOffset adjusted_old_paint_offset =
context.old_paint_offset -
tree_builder_context.current
.additional_offset_to_layout_shift_root_delta -
PhysicalOffset::FromVector2dFRound(
tree_builder_context.translation_2d_to_layout_shift_root_delta +
tree_builder_context.current
.scroll_offset_to_layout_shift_root_delta);
PhysicalOffset new_paint_offset = tree_builder_context.current.paint_offset;
if (object.IsText()) {
const auto& text = To<LayoutText>(object);
LogicalOffset new_starting_point;
LayoutUnit logical_height;
text.LogicalStartingPointAndHeight(new_starting_point, logical_height);
LogicalOffset old_starting_point = text.PreviousLogicalStartingPoint();
if (new_starting_point == old_starting_point)
return;
text.SetPreviousLogicalStartingPoint(new_starting_point);
if (old_starting_point == LayoutText::UninitializedLogicalStartingPoint())
return;
// If the layout shift root has changed, LayoutShiftTracker can't use the
// current paint property tree to map the old rect.
if (tree_builder_context.current.layout_shift_root_changed)
return;
layout_shift_tracker.NotifyTextPrePaint(
text, property_tree_state, old_starting_point, new_starting_point,
adjusted_old_paint_offset,
tree_builder_context.translation_2d_to_layout_shift_root_delta,
tree_builder_context.current.scroll_offset_to_layout_shift_root_delta,
tree_builder_context.current.pending_scroll_anchor_adjustment,
new_paint_offset, logical_height);
return;
}
DCHECK(object.IsBox());
const auto& box = To<LayoutBox>(object);
PhysicalRect new_rect = box.PhysicalVisualOverflowRectAllowingUnset();
new_rect.Move(new_paint_offset);
PhysicalRect old_rect = box.PreviousPhysicalVisualOverflowRect();
old_rect.Move(adjusted_old_paint_offset);
// TODO(crbug.com/1178618): We may want to do better than this. For now, just
// don't report anything inside multicol containers.
const auto* block_flow = DynamicTo<LayoutBlockFlow>(&box);
if (block_flow && block_flow->IsFragmentationContextRoot() &&
block_flow->IsLayoutNGObject())
context.inside_opaque_layout_shift_root = true;
bool should_create_containing_block_scope =
// TODO(crbug.com/1178618): Support multiple-fragments when switching to
// LayoutNGFragmentTraversal.
context.fragment_data == &box.FirstFragment() && block_flow &&
block_flow->ChildrenInline() && block_flow->FirstChild();
if (should_create_containing_block_scope) {
// For layout shift tracking of contained LayoutTexts.
context.containing_block_scope_.emplace(
PhysicalSizeToBeNoop(box.PreviousSize()),
PhysicalSizeToBeNoop(box.Size()), old_rect, new_rect);
}
bool should_report_layout_shift = [&]() -> bool {
if (box.ShouldSkipNextLayoutShiftTracking()) {
box.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(false);
return false;
}
// If the layout shift root has changed, LayoutShiftTracker can't use the
// current paint property tree to map the old rect.
if (tree_builder_context.current.layout_shift_root_changed)
return false;
if (new_rect.IsEmpty() || old_rect.IsEmpty())
return false;
// Track self-painting layers separately because their ancestors'
// PhysicalVisualOverflowRect may not cover them.
if (object.HasLayer() &&
To<LayoutBoxModelObject>(object).HasSelfPaintingLayer())
return true;
// Always track if the parent doesn't need to track (e.g. it has visibility:
// hidden), while this object needs (e.g. it has visibility: visible).
// This also includes non-anonymous child with an anonymous parent.
if (object.Parent()->ShouldSkipNextLayoutShiftTracking())
return true;
// Report if the parent is in a different transform space.
const auto* parent_context = context.ParentContext();
if (!parent_context || !parent_context->transform_ ||
parent_context->transform_ != tree_builder_context.current.transform)
return true;
// Report if this object has local movement (i.e. delta of paint offset is
// different from that of the parent).
return parent_context->fragment_data->PaintOffset() -
parent_context->old_paint_offset !=
new_paint_offset - context.old_paint_offset;
}();
if (should_report_layout_shift) {
layout_shift_tracker.NotifyBoxPrePaint(
box, property_tree_state, old_rect, new_rect, adjusted_old_paint_offset,
tree_builder_context.translation_2d_to_layout_shift_root_delta,
tree_builder_context.current.scroll_offset_to_layout_shift_root_delta,
tree_builder_context.current.pending_scroll_anchor_adjustment,
new_paint_offset);
}
}
bool PaintInvalidator::InvalidatePaint(
const LayoutObject& object,
const NGPrePaintInfo* pre_paint_info,
const PaintPropertyTreeBuilderContext* tree_builder_context,
PaintInvalidatorContext& context) {
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"),
"PaintInvalidator::InvalidatePaint()", "object",
object.DebugName().Ascii());
if (object.IsSVGHiddenContainer() || object.IsLayoutTableCol())
context.subtree_flags |= PaintInvalidatorContext::kSubtreeNoInvalidation;
if (context.subtree_flags & PaintInvalidatorContext::kSubtreeNoInvalidation)
return false;
object.GetMutableForPainting().EnsureIsReadyForPaintInvalidation();
UpdatePaintingLayer(object, context);
// Assert that the container state in the invalidation context is consistent
// with what the LayoutObject tree says. We cannot do this if we're fragment-
// traversing an "orphaned" object (an object that has a fragment inside a
// fragmentainer, even though not all its ancestor objects have it; this may
// happen to OOFs, and also to floats, if they are inside a non-atomic
// inline). In such cases we'll just have to live with the inconsitency, which
// means that we'll lose any paint effects from such "missing" ancestors.
DCHECK_EQ(context.painting_layer, object.PaintingLayer()) << object;
if (AXObjectCache* cache = object.GetDocument().ExistingAXObjectCache())
cache->InvalidateBoundingBox(&object);
if (!object.ShouldCheckForPaintInvalidation() && !context.NeedsSubtreeWalk())
return false;
if (object.SubtreeShouldDoFullPaintInvalidation()) {
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeFullInvalidation |
PaintInvalidatorContext::kSubtreeFullInvalidationForStackedContents;
}
if (object.SubtreeShouldCheckForPaintInvalidation()) {
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeInvalidationChecking;
}
if (UNLIKELY(object.ContainsInlineWithOutlineAndContinuation()) &&
// Need this only if the subtree needs to check geometry change.
PrePaintTreeWalk::ObjectRequiresTreeBuilderContext(object)) {
// Force subtree invalidation checking to ensure invalidation of focus rings
// when continuation's geometry changes.
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeInvalidationChecking;
}
if (pre_paint_info) {
FragmentData& fragment_data = *pre_paint_info->fragment_data;
context.fragment_data = &fragment_data;
if (tree_builder_context) {
DCHECK_EQ(tree_builder_context->fragments.size(), 1u);
const auto& fragment_tree_builder_context =
tree_builder_context->fragments[0];
UpdateFromTreeBuilderContext(fragment_tree_builder_context, context);
UpdateLayoutShiftTracking(object, fragment_tree_builder_context, context);
} else {
context.old_paint_offset = fragment_data.PaintOffset();
}
object.InvalidatePaint(context);
} else {
unsigned tree_builder_index = 0;
for (auto* fragment_data = &object.GetMutableForPainting().FirstFragment();
fragment_data;
fragment_data = fragment_data->NextFragment(), tree_builder_index++) {
context.fragment_data = fragment_data;
DCHECK(!tree_builder_context ||
tree_builder_index < tree_builder_context->fragments.size());
if (tree_builder_context) {
const auto& fragment_tree_builder_context =
tree_builder_context->fragments[tree_builder_index];
UpdateFromTreeBuilderContext(fragment_tree_builder_context, context);
UpdateLayoutShiftTracking(object, fragment_tree_builder_context,
context);
} else {
context.old_paint_offset = fragment_data->PaintOffset();
}
object.InvalidatePaint(context);
}
}
auto reason = static_cast<const DisplayItemClient&>(object)
.GetPaintInvalidationReason();
if (object.ShouldDelayFullPaintInvalidation() &&
(!IsFullPaintInvalidationReason(reason) ||
// Delay invalidation if the client has never been painted.
reason == PaintInvalidationReason::kJustCreated))
pending_delayed_paint_invalidations_.push_back(&object);
if (auto* local_frame = DynamicTo<LocalFrame>(object.GetFrame()->Top())) {
if (auto* mf_checker =
local_frame->View()->GetMobileFriendlinessChecker()) {
if (tree_builder_context &&
(!pre_paint_info || pre_paint_info->is_last_for_node))
mf_checker->NotifyInvalidatePaint(object);
}
}
return reason != PaintInvalidationReason::kNone;
}
void PaintInvalidator::ProcessPendingDelayedPaintInvalidations() {
for (const auto& target : pending_delayed_paint_invalidations_)
target->GetMutableForPainting().SetShouldDelayFullPaintInvalidation();
}
} // namespace blink
| chromium/chromium | third_party/blink/renderer/core/paint/paint_invalidator.cc | C++ | bsd-3-clause | 15,422 |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/graphics/GeneratedImage.h"
#include "platform/geometry/FloatRect.h"
#include "platform/graphics/paint/SkPictureBuilder.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace blink {
void GeneratedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
{
Image::computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
intrinsicRatio = FloatSize();
}
void GeneratedImage::drawPattern(GraphicsContext& destContext, const FloatRect& srcRect, const FloatSize& scale,
const FloatPoint& phase, SkXfermode::Mode compositeOp, const FloatRect& destRect,
const FloatSize& repeatSpacing)
{
FloatRect tileRect = srcRect;
tileRect.expand(FloatSize(repeatSpacing));
SkPictureBuilder builder(tileRect, nullptr, &destContext);
builder.context().beginRecording(tileRect);
drawTile(builder.context(), srcRect);
RefPtr<const SkPicture> tilePicture = builder.endRecording();
AffineTransform patternTransform;
patternTransform.translate(phase.x(), phase.y());
patternTransform.scale(scale.width(), scale.height());
patternTransform.translate(tileRect.x(), tileRect.y());
RefPtr<Pattern> picturePattern = Pattern::createPicturePattern(tilePicture);
picturePattern->setPatternSpaceTransform(patternTransform);
SkPaint fillPaint = destContext.fillPaint();
picturePattern->applyToPaint(fillPaint);
fillPaint.setColor(SK_ColorBLACK);
fillPaint.setXfermodeMode(compositeOp);
destContext.drawRect(destRect, fillPaint);
}
PassRefPtr<SkImage> GeneratedImage::imageForCurrentFrame()
{
return nullptr;
}
} // namespace blink
| js0701/chromium-crosswalk | third_party/WebKit/Source/platform/graphics/GeneratedImage.cpp | C++ | bsd-3-clause | 3,311 |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Benchmarks.Data
{
[Table("fortune")]
public class Fortune : IComparable<Fortune>, IComparable
{
[Column("id")]
public int Id { get; set; }
[Column("message")]
[StringLength(2048)]
[Required]
public string Message { get; set; }
public int CompareTo(object obj)
{
return CompareTo((Fortune)obj);
}
public int CompareTo(Fortune other)
{
// Performance critical, using culture insensitive comparison
return String.CompareOrdinal(Message, other.Message);
}
}
}
| sumeetchhetri/FrameworkBenchmarks | frameworks/CSharp/aspnetcore/Benchmarks/Data/Fortune.cs | C# | bsd-3-clause | 902 |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Benchmarks.Configuration;
using Benchmarks.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Benchmarks.Middleware
{
public class MultipleUpdatesRawMiddleware
{
private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiUpdateRaw));
private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
private readonly RequestDelegate _next;
public MultipleUpdatesRawMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
{
var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
var db = httpContext.RequestServices.GetService<RawDb>();
var rows = await db.LoadMultipleUpdatesRows(count);
var result = JsonSerializer.Serialize(rows, _serializerOptions);
httpContext.Response.StatusCode = StatusCodes.Status200OK;
httpContext.Response.ContentType = "application/json";
httpContext.Response.ContentLength = result.Length;
await httpContext.Response.WriteAsync(result);
return;
}
await _next(httpContext);
}
}
public static class MultipleUpdatesRawMiddlewareExtensions
{
public static IApplicationBuilder UseMultipleUpdatesRaw(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MultipleUpdatesRawMiddleware>();
}
}
}
| sumeetchhetri/FrameworkBenchmarks | frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesRawMiddleware.cs | C# | bsd-3-clause | 2,038 |
/*
* Copyright (c) 2010-2014 ARM Limited
* Copyright (c) 2012-2013 AMD
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Kevin Lim
* Korey Sewell
*/
#ifndef __CPU_O3_FETCH_IMPL_HH__
#define __CPU_O3_FETCH_IMPL_HH__
#include <algorithm>
#include <cstring>
#include <list>
#include <map>
#include <queue>
#include "arch/isa_traits.hh"
#include "arch/tlb.hh"
#include "arch/utility.hh"
#include "arch/vtophys.hh"
#include "base/random.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "cpu/base.hh"
//#include "cpu/checker/cpu.hh"
#include "cpu/o3/fetch.hh"
#include "cpu/exetrace.hh"
#include "debug/Activity.hh"
#include "debug/Drain.hh"
#include "debug/Fetch.hh"
#include "debug/O3PipeView.hh"
#include "mem/packet.hh"
#include "params/DerivO3CPU.hh"
#include "sim/byteswap.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "sim/full_system.hh"
#include "sim/system.hh"
#include "cpu/o3/isa_specific.hh"
using namespace std;
template<class Impl>
DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
: cpu(_cpu),
decodeToFetchDelay(params->decodeToFetchDelay),
renameToFetchDelay(params->renameToFetchDelay),
iewToFetchDelay(params->iewToFetchDelay),
commitToFetchDelay(params->commitToFetchDelay),
fetchWidth(params->fetchWidth),
decodeWidth(params->decodeWidth),
retryPkt(NULL),
retryTid(InvalidThreadID),
cacheBlkSize(cpu->cacheLineSize()),
fetchBufferSize(params->fetchBufferSize),
fetchBufferMask(fetchBufferSize - 1),
fetchQueueSize(params->fetchQueueSize),
numThreads(params->numThreads),
numFetchingThreads(params->smtNumFetchingThreads),
finishTranslationEvent(this)
{
if (numThreads > Impl::MaxThreads)
fatal("numThreads (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
numThreads, static_cast<int>(Impl::MaxThreads));
if (fetchWidth > Impl::MaxWidth)
fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
fetchWidth, static_cast<int>(Impl::MaxWidth));
if (fetchBufferSize > cacheBlkSize)
fatal("fetch buffer size (%u bytes) is greater than the cache "
"block size (%u bytes)\n", fetchBufferSize, cacheBlkSize);
if (cacheBlkSize % fetchBufferSize)
fatal("cache block (%u bytes) is not a multiple of the "
"fetch buffer (%u bytes)\n", cacheBlkSize, fetchBufferSize);
std::string policy = params->smtFetchPolicy;
// Convert string to lowercase
std::transform(policy.begin(), policy.end(), policy.begin(),
(int(*)(int)) tolower);
// Figure out fetch policy
if (policy == "singlethread") {
fetchPolicy = SingleThread;
if (numThreads > 1)
panic("Invalid Fetch Policy for a SMT workload.");
} else if (policy == "roundrobin") {
fetchPolicy = RoundRobin;
DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
} else if (policy == "branch") {
fetchPolicy = Branch;
DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
} else if (policy == "iqcount") {
fetchPolicy = IQ;
DPRINTF(Fetch, "Fetch policy set to IQ count\n");
} else if (policy == "lsqcount") {
fetchPolicy = LSQ;
DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
} else {
fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
" RoundRobin,LSQcount,IQcount}\n");
}
// Get the size of an instruction.
instSize = sizeof(TheISA::MachInst);
for (int i = 0; i < Impl::MaxThreads; i++) {
decoder[i] = NULL;
fetchBuffer[i] = NULL;
fetchBufferPC[i] = 0;
fetchBufferValid[i] = false;
}
branchPred = params->branchPred;
for (ThreadID tid = 0; tid < numThreads; tid++) {
decoder[tid] = new TheISA::Decoder(params->isa[tid]);
// Create space to buffer the cache line data,
// which may not hold the entire cache line.
fetchBuffer[tid] = new uint8_t[fetchBufferSize];
}
}
template <class Impl>
std::string
DefaultFetch<Impl>::name() const
{
return cpu->name() + ".fetch";
}
template <class Impl>
void
DefaultFetch<Impl>::regProbePoints()
{
ppFetch = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Fetch");
ppFetchRequestSent = new ProbePointArg<RequestPtr>(cpu->getProbeManager(),
"FetchRequest");
}
template <class Impl>
void
DefaultFetch<Impl>::regStats()
{
icacheStallCycles
.name(name() + ".icacheStallCycles")
.desc("Number of cycles fetch is stalled on an Icache miss")
.prereq(icacheStallCycles);
fetchedInsts
.name(name() + ".Insts")
.desc("Number of instructions fetch has processed")
.prereq(fetchedInsts);
fetchedBranches
.name(name() + ".Branches")
.desc("Number of branches that fetch encountered")
.prereq(fetchedBranches);
predictedBranches
.name(name() + ".predictedBranches")
.desc("Number of branches that fetch has predicted taken")
.prereq(predictedBranches);
fetchCycles
.name(name() + ".Cycles")
.desc("Number of cycles fetch has run and was not squashing or"
" blocked")
.prereq(fetchCycles);
fetchSquashCycles
.name(name() + ".SquashCycles")
.desc("Number of cycles fetch has spent squashing")
.prereq(fetchSquashCycles);
fetchTlbCycles
.name(name() + ".TlbCycles")
.desc("Number of cycles fetch has spent waiting for tlb")
.prereq(fetchTlbCycles);
fetchIdleCycles
.name(name() + ".IdleCycles")
.desc("Number of cycles fetch was idle")
.prereq(fetchIdleCycles);
fetchBlockedCycles
.name(name() + ".BlockedCycles")
.desc("Number of cycles fetch has spent blocked")
.prereq(fetchBlockedCycles);
fetchedCacheLines
.name(name() + ".CacheLines")
.desc("Number of cache lines fetched")
.prereq(fetchedCacheLines);
fetchMiscStallCycles
.name(name() + ".MiscStallCycles")
.desc("Number of cycles fetch has spent waiting on interrupts, or "
"bad addresses, or out of MSHRs")
.prereq(fetchMiscStallCycles);
fetchPendingDrainCycles
.name(name() + ".PendingDrainCycles")
.desc("Number of cycles fetch has spent waiting on pipes to drain")
.prereq(fetchPendingDrainCycles);
fetchNoActiveThreadStallCycles
.name(name() + ".NoActiveThreadStallCycles")
.desc("Number of stall cycles due to no active thread to fetch from")
.prereq(fetchNoActiveThreadStallCycles);
fetchPendingTrapStallCycles
.name(name() + ".PendingTrapStallCycles")
.desc("Number of stall cycles due to pending traps")
.prereq(fetchPendingTrapStallCycles);
fetchPendingQuiesceStallCycles
.name(name() + ".PendingQuiesceStallCycles")
.desc("Number of stall cycles due to pending quiesce instructions")
.prereq(fetchPendingQuiesceStallCycles);
fetchIcacheWaitRetryStallCycles
.name(name() + ".IcacheWaitRetryStallCycles")
.desc("Number of stall cycles due to full MSHR")
.prereq(fetchIcacheWaitRetryStallCycles);
fetchIcacheSquashes
.name(name() + ".IcacheSquashes")
.desc("Number of outstanding Icache misses that were squashed")
.prereq(fetchIcacheSquashes);
fetchTlbSquashes
.name(name() + ".ItlbSquashes")
.desc("Number of outstanding ITLB misses that were squashed")
.prereq(fetchTlbSquashes);
fetchNisnDist
.init(/* base value */ 0,
/* last value */ fetchWidth,
/* bucket size */ 1)
.name(name() + ".rateDist")
.desc("Number of instructions fetched each cycle (Total)")
.flags(Stats::pdf);
idleRate
.name(name() + ".idleRate")
.desc("Percent of cycles fetch was idle")
.prereq(idleRate);
idleRate = fetchIdleCycles * 100 / cpu->numCycles;
branchRate
.name(name() + ".branchRate")
.desc("Number of branch fetches per cycle")
.flags(Stats::total);
branchRate = fetchedBranches / cpu->numCycles;
fetchRate
.name(name() + ".rate")
.desc("Number of inst fetches per cycle")
.flags(Stats::total);
fetchRate = fetchedInsts / cpu->numCycles;
}
template<class Impl>
void
DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
{
timeBuffer = time_buffer;
// Create wires to get information from proper places in time buffer.
fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
fromRename = timeBuffer->getWire(-renameToFetchDelay);
fromIEW = timeBuffer->getWire(-iewToFetchDelay);
fromCommit = timeBuffer->getWire(-commitToFetchDelay);
}
template<class Impl>
void
DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
{
activeThreads = at_ptr;
}
template<class Impl>
void
DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *ftb_ptr)
{
// Create wire to write information to proper place in fetch time buf.
toDecode = ftb_ptr->getWire(0);
}
template<class Impl>
void
DefaultFetch<Impl>::startupStage()
{
assert(priorityList.empty());
resetStage();
// Fetch needs to start fetching instructions at the very beginning,
// so it must start up in active state.
switchToActive();
}
template<class Impl>
void
DefaultFetch<Impl>::resetStage()
{
numInst = 0;
interruptPending = false;
cacheBlocked = false;
priorityList.clear();
// Setup PC and nextPC with initial state.
for (ThreadID tid = 0; tid < numThreads; ++tid) {
fetchStatus[tid] = Running;
pc[tid] = cpu->pcState(tid);
fetchOffset[tid] = 0;
macroop[tid] = NULL;
delayedCommit[tid] = false;
memReq[tid] = NULL;
stalls[tid].decode = false;
stalls[tid].drain = false;
fetchBufferPC[tid] = 0;
fetchBufferValid[tid] = false;
fetchQueue[tid].clear();
priorityList.push_back(tid);
}
wroteToTimeBuffer = false;
_status = Inactive;
}
template<class Impl>
void
DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
{
ThreadID tid = cpu->contextToThread(pkt->req->contextId());
DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
assert(!cpu->switchedOut());
// Only change the status if it's still waiting on the icache access
// to return.
if (fetchStatus[tid] != IcacheWaitResponse ||
pkt->req != memReq[tid]) {
++fetchIcacheSquashes;
delete pkt->req;
delete pkt;
return;
}
memcpy(fetchBuffer[tid], pkt->getConstPtr<uint8_t>(), fetchBufferSize);
fetchBufferValid[tid] = true;
// Wake up the CPU (if it went to sleep and was waiting on
// this completion event).
cpu->wakeCPU();
DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
tid);
switchToActive();
// Only switch to IcacheAccessComplete if we're not stalled as well.
if (checkStall(tid)) {
fetchStatus[tid] = Blocked;
} else {
fetchStatus[tid] = IcacheAccessComplete;
}
pkt->req->setAccessLatency();
cpu->ppInstAccessComplete->notify(pkt);
// Reset the mem req to NULL.
delete pkt->req;
delete pkt;
memReq[tid] = NULL;
}
template <class Impl>
void
DefaultFetch<Impl>::drainResume()
{
for (ThreadID i = 0; i < numThreads; ++i)
stalls[i].drain = false;
}
template <class Impl>
void
DefaultFetch<Impl>::drainSanityCheck() const
{
assert(isDrained());
assert(retryPkt == NULL);
assert(retryTid == InvalidThreadID);
assert(!cacheBlocked);
assert(!interruptPending);
for (ThreadID i = 0; i < numThreads; ++i) {
assert(!memReq[i]);
assert(fetchStatus[i] == Idle || stalls[i].drain);
}
branchPred->drainSanityCheck();
}
template <class Impl>
bool
DefaultFetch<Impl>::isDrained() const
{
/* Make sure that threads are either idle of that the commit stage
* has signaled that draining has completed by setting the drain
* stall flag. This effectively forces the pipeline to be disabled
* until the whole system is drained (simulation may continue to
* drain other components).
*/
for (ThreadID i = 0; i < numThreads; ++i) {
// Verify fetch queues are drained
if (!fetchQueue[i].empty())
return false;
// Return false if not idle or drain stalled
if (fetchStatus[i] != Idle) {
if (fetchStatus[i] == Blocked && stalls[i].drain)
continue;
else
return false;
}
}
/* The pipeline might start up again in the middle of the drain
* cycle if the finish translation event is scheduled, so make
* sure that's not the case.
*/
return !finishTranslationEvent.scheduled();
}
template <class Impl>
void
DefaultFetch<Impl>::takeOverFrom()
{
assert(cpu->getInstPort().isConnected());
resetStage();
}
template <class Impl>
void
DefaultFetch<Impl>::drainStall(ThreadID tid)
{
assert(cpu->isDraining());
assert(!stalls[tid].drain);
DPRINTF(Drain, "%i: Thread drained.\n", tid);
stalls[tid].drain = true;
}
template <class Impl>
void
DefaultFetch<Impl>::wakeFromQuiesce()
{
DPRINTF(Fetch, "Waking up from quiesce\n");
// Hopefully this is safe
// @todo: Allow other threads to wake from quiesce.
fetchStatus[0] = Running;
}
template <class Impl>
inline void
DefaultFetch<Impl>::switchToActive()
{
if (_status == Inactive) {
DPRINTF(Activity, "Activating stage.\n");
cpu->activateStage(O3CPU::FetchIdx);
_status = Active;
}
}
template <class Impl>
inline void
DefaultFetch<Impl>::switchToInactive()
{
if (_status == Active) {
DPRINTF(Activity, "Deactivating stage.\n");
cpu->deactivateStage(O3CPU::FetchIdx);
_status = Inactive;
}
}
template <class Impl>
void
DefaultFetch<Impl>::deactivateThread(ThreadID tid)
{
// Update priority list
auto thread_it = std::find(priorityList.begin(), priorityList.end(), tid);
if (thread_it != priorityList.end()) {
priorityList.erase(thread_it);
}
}
template <class Impl>
bool
DefaultFetch<Impl>::lookupAndUpdateNextPC(
DynInstPtr &inst, TheISA::PCState &nextPC)
{
// Do branch prediction check here.
// A bit of a misnomer...next_PC is actually the current PC until
// this function updates it.
bool predict_taken;
if (!inst->isControl()) {
TheISA::advancePC(nextPC, inst->staticInst);
inst->setPredTarg(nextPC);
inst->setPredTaken(false);
return false;
}
ThreadID tid = inst->threadNumber;
predict_taken = branchPred->predict(inst->staticInst, inst->seqNum,
nextPC, tid);
if (predict_taken) {
DPRINTF(Fetch, "[tid:%i]: [sn:%i]: Branch predicted to be taken to %s.\n",
tid, inst->seqNum, nextPC);
} else {
DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
tid, inst->seqNum);
}
DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
tid, inst->seqNum, nextPC);
inst->setPredTarg(nextPC);
inst->setPredTaken(predict_taken);
++fetchedBranches;
if (predict_taken) {
++predictedBranches;
}
return predict_taken;
}
template <class Impl>
bool
DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
{
Fault fault = NoFault;
assert(!cpu->switchedOut());
// @todo: not sure if these should block translation.
//AlphaDep
if (cacheBlocked) {
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
tid);
return false;
} else if (checkInterrupt(pc) && !delayedCommit[tid]) {
// Hold off fetch from getting new instructions when:
// Cache is blocked, or
// while an interrupt is pending and we're not in PAL mode, or
// fetch is switched out.
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
tid);
return false;
}
// Align the fetch address to the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(vaddr);
DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
tid, fetchBufferBlockPC, vaddr);
// Setup the memReq to do a read of the first instruction's address.
// Set the appropriate read size and flags as well.
// Build request here.
RequestPtr mem_req =
new Request(tid, fetchBufferBlockPC, fetchBufferSize,
Request::INST_FETCH, cpu->instMasterId(), pc,
cpu->thread[tid]->contextId());
mem_req->taskId(cpu->taskId());
memReq[tid] = mem_req;
// Initiate translation of the icache block
fetchStatus[tid] = ItlbWait;
FetchTranslation *trans = new FetchTranslation(this);
cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
trans, BaseTLB::Execute);
return true;
}
template <class Impl>
void
DefaultFetch<Impl>::finishTranslation(const Fault &fault, RequestPtr mem_req)
{
ThreadID tid = cpu->contextToThread(mem_req->contextId());
Addr fetchBufferBlockPC = mem_req->getVaddr();
assert(!cpu->switchedOut());
// Wake up CPU if it was idle
cpu->wakeCPU();
if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
mem_req->getVaddr() != memReq[tid]->getVaddr()) {
DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
tid);
++fetchTlbSquashes;
delete mem_req;
return;
}
// If translation was successful, attempt to read the icache block.
if (fault == NoFault) {
// Check that we're not going off into random memory
// If we have, just wait around for commit to squash something and put
// us on the right track
if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
warn("Address %#x is outside of physical memory, stopping fetch\n",
mem_req->getPaddr());
fetchStatus[tid] = NoGoodAddr;
delete mem_req;
memReq[tid] = NULL;
return;
}
// Build packet here.
PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
data_pkt->dataDynamic(new uint8_t[fetchBufferSize]);
fetchBufferPC[tid] = fetchBufferBlockPC;
fetchBufferValid[tid] = false;
DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
fetchedCacheLines++;
// Access the cache.
if (!cpu->getInstPort().sendTimingReq(data_pkt)) {
assert(retryPkt == NULL);
assert(retryTid == InvalidThreadID);
DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
fetchStatus[tid] = IcacheWaitRetry;
retryPkt = data_pkt;
retryTid = tid;
cacheBlocked = true;
} else {
DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
"response.\n", tid);
lastIcacheStall[tid] = curTick();
fetchStatus[tid] = IcacheWaitResponse;
// Notify Fetch Request probe when a packet containing a fetch
// request is successfully sent
ppFetchRequestSent->notify(mem_req);
}
} else {
// Don't send an instruction to decode if we can't handle it.
if (!(numInst < fetchWidth) || !(fetchQueue[tid].size() < fetchQueueSize)) {
assert(!finishTranslationEvent.scheduled());
finishTranslationEvent.setFault(fault);
finishTranslationEvent.setReq(mem_req);
cpu->schedule(finishTranslationEvent,
cpu->clockEdge(Cycles(1)));
return;
}
DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
tid, mem_req->getVaddr(), memReq[tid]->getVaddr());
// Translation faulted, icache request won't be sent.
delete mem_req;
memReq[tid] = NULL;
// Send the fault to commit. This thread will not do anything
// until commit handles the fault. The only other way it can
// wake up is if a squash comes along and changes the PC.
TheISA::PCState fetchPC = pc[tid];
DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
// We will use a nop in ordier to carry the fault.
DynInstPtr instruction = buildInst(tid,
decoder[tid]->decode(TheISA::NoopMachInst, fetchPC.instAddr()),
NULL, fetchPC, fetchPC, false);
instruction->setPredTarg(fetchPC);
instruction->fault = fault;
wroteToTimeBuffer = true;
DPRINTF(Activity, "Activity this cycle.\n");
cpu->activityThisCycle();
fetchStatus[tid] = TrapPending;
DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
tid, fault->name(), pc[tid]);
}
_status = updateFetchStatus();
}
template <class Impl>
inline void
DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC,
const DynInstPtr squashInst, ThreadID tid)
{
DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
tid, newPC);
pc[tid] = newPC;
fetchOffset[tid] = 0;
if (squashInst && squashInst->pcState().instAddr() == newPC.instAddr())
macroop[tid] = squashInst->macroop;
else
macroop[tid] = NULL;
decoder[tid]->reset();
// Clear the icache miss if it's outstanding.
if (fetchStatus[tid] == IcacheWaitResponse) {
DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
tid);
memReq[tid] = NULL;
} else if (fetchStatus[tid] == ItlbWait) {
DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
tid);
memReq[tid] = NULL;
}
// Get rid of the retrying packet if it was from this thread.
if (retryTid == tid) {
assert(cacheBlocked);
if (retryPkt) {
delete retryPkt->req;
delete retryPkt;
}
retryPkt = NULL;
retryTid = InvalidThreadID;
}
fetchStatus[tid] = Squashing;
// Empty fetch queue
fetchQueue[tid].clear();
// microops are being squashed, it is not known wheather the
// youngest non-squashed microop was marked delayed commit
// or not. Setting the flag to true ensures that the
// interrupts are not handled when they cannot be, though
// some opportunities to handle interrupts may be missed.
delayedCommit[tid] = true;
++fetchSquashCycles;
}
template<class Impl>
void
DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
const DynInstPtr squashInst,
const InstSeqNum seq_num, ThreadID tid)
{
DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
doSquash(newPC, squashInst, tid);
// Tell the CPU to remove any instructions that are in flight between
// fetch and decode.
cpu->removeInstsUntil(seq_num, tid);
}
template<class Impl>
bool
DefaultFetch<Impl>::checkStall(ThreadID tid) const
{
bool ret_val = false;
if (stalls[tid].drain) {
assert(cpu->isDraining());
DPRINTF(Fetch,"[tid:%i]: Drain stall detected.\n",tid);
ret_val = true;
}
return ret_val;
}
template<class Impl>
typename DefaultFetch<Impl>::FetchStatus
DefaultFetch<Impl>::updateFetchStatus()
{
//Check Running
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
if (fetchStatus[tid] == Running ||
fetchStatus[tid] == Squashing ||
fetchStatus[tid] == IcacheAccessComplete) {
if (_status == Inactive) {
DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
if (fetchStatus[tid] == IcacheAccessComplete) {
DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
"completion\n",tid);
}
cpu->activateStage(O3CPU::FetchIdx);
}
return Active;
}
}
// Stage is switching from active to inactive, notify CPU of it.
if (_status == Active) {
DPRINTF(Activity, "Deactivating stage.\n");
cpu->deactivateStage(O3CPU::FetchIdx);
}
return Inactive;
}
template <class Impl>
void
DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
const InstSeqNum seq_num, DynInstPtr squashInst,
ThreadID tid)
{
DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
doSquash(newPC, squashInst, tid);
// Tell the CPU to remove any instructions that are not in the ROB.
cpu->removeInstsNotInROB(tid);
}
template <class Impl>
void
DefaultFetch<Impl>::tick()
{
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
bool status_change = false;
wroteToTimeBuffer = false;
for (ThreadID i = 0; i < numThreads; ++i) {
issuePipelinedIfetch[i] = false;
}
while (threads != end) {
ThreadID tid = *threads++;
// Check the signals for each thread to determine the proper status
// for each thread.
bool updated_status = checkSignalsAndUpdate(tid);
status_change = status_change || updated_status;
}
DPRINTF(Fetch, "Running stage.\n");
if (FullSystem) {
if (fromCommit->commitInfo[0].interruptPending) {
interruptPending = true;
}
if (fromCommit->commitInfo[0].clearInterrupt) {
interruptPending = false;
}
}
for (threadFetched = 0; threadFetched < numFetchingThreads;
threadFetched++) {
// Fetch each of the actively fetching threads.
fetch(status_change);
}
// Record number of instructions fetched this cycle for distribution.
fetchNisnDist.sample(numInst);
if (status_change) {
// Change the fetch stage status if there was a status change.
_status = updateFetchStatus();
}
// Issue the next I-cache request if possible.
for (ThreadID i = 0; i < numThreads; ++i) {
if (issuePipelinedIfetch[i]) {
pipelineIcacheAccesses(i);
}
}
// Send instructions enqueued into the fetch queue to decode.
// Limit rate by fetchWidth. Stall if decode is stalled.
unsigned insts_to_decode = 0;
unsigned available_insts = 0;
for (auto tid : *activeThreads) {
if (!stalls[tid].decode) {
available_insts += fetchQueue[tid].size();
}
}
// Pick a random thread to start trying to grab instructions from
auto tid_itr = activeThreads->begin();
std::advance(tid_itr, random_mt.random<uint8_t>(0, activeThreads->size() - 1));
while (available_insts != 0 && insts_to_decode < decodeWidth) {
ThreadID tid = *tid_itr;
if (!stalls[tid].decode && !fetchQueue[tid].empty()) {
auto inst = fetchQueue[tid].front();
toDecode->insts[toDecode->size++] = inst;
DPRINTF(Fetch, "[tid:%i][sn:%i]: Sending instruction to decode from "
"fetch queue. Fetch queue size: %i.\n",
tid, inst->seqNum, fetchQueue[tid].size());
wroteToTimeBuffer = true;
fetchQueue[tid].pop_front();
insts_to_decode++;
available_insts--;
}
tid_itr++;
// Wrap around if at end of active threads list
if (tid_itr == activeThreads->end())
tid_itr = activeThreads->begin();
}
// If there was activity this cycle, inform the CPU of it.
if (wroteToTimeBuffer) {
DPRINTF(Activity, "Activity this cycle.\n");
cpu->activityThisCycle();
}
// Reset the number of the instruction we've fetched.
numInst = 0;
}
template <class Impl>
bool
DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
{
// Update the per thread stall statuses.
if (fromDecode->decodeBlock[tid]) {
stalls[tid].decode = true;
}
if (fromDecode->decodeUnblock[tid]) {
assert(stalls[tid].decode);
assert(!fromDecode->decodeBlock[tid]);
stalls[tid].decode = false;
}
// Check squash signals from commit.
if (fromCommit->commitInfo[tid].squash) {
DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
"from commit.\n",tid);
// In any case, squash.
squash(fromCommit->commitInfo[tid].pc,
fromCommit->commitInfo[tid].doneSeqNum,
fromCommit->commitInfo[tid].squashInst, tid);
// If it was a branch mispredict on a control instruction, update the
// branch predictor with that instruction, otherwise just kill the
// invalid state we generated in after sequence number
if (fromCommit->commitInfo[tid].mispredictInst &&
fromCommit->commitInfo[tid].mispredictInst->isControl()) {
branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
fromCommit->commitInfo[tid].pc,
fromCommit->commitInfo[tid].branchTaken,
tid);
} else {
branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
tid);
}
return true;
} else if (fromCommit->commitInfo[tid].doneSeqNum) {
// Update the branch predictor if it wasn't a squashed instruction
// that was broadcasted.
branchPred->update(fromCommit->commitInfo[tid].doneSeqNum, tid);
}
// Check squash signals from decode.
if (fromDecode->decodeInfo[tid].squash) {
DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
"from decode.\n",tid);
// Update the branch predictor.
if (fromDecode->decodeInfo[tid].branchMispredict) {
branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
fromDecode->decodeInfo[tid].nextPC,
fromDecode->decodeInfo[tid].branchTaken,
tid);
} else {
branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
tid);
}
if (fetchStatus[tid] != Squashing) {
DPRINTF(Fetch, "Squashing from decode with PC = %s\n",
fromDecode->decodeInfo[tid].nextPC);
// Squash unless we're already squashing
squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
fromDecode->decodeInfo[tid].squashInst,
fromDecode->decodeInfo[tid].doneSeqNum,
tid);
return true;
}
}
if (checkStall(tid) &&
fetchStatus[tid] != IcacheWaitResponse &&
fetchStatus[tid] != IcacheWaitRetry &&
fetchStatus[tid] != ItlbWait &&
fetchStatus[tid] != QuiescePending) {
DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
fetchStatus[tid] = Blocked;
return true;
}
if (fetchStatus[tid] == Blocked ||
fetchStatus[tid] == Squashing) {
// Switch status to running if fetch isn't being told to block or
// squash this cycle.
DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
tid);
fetchStatus[tid] = Running;
return true;
}
// If we've reached this point, we have not gotten any signals that
// cause fetch to change its status. Fetch remains the same as before.
return false;
}
template<class Impl>
typename Impl::DynInstPtr
DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
StaticInstPtr curMacroop, TheISA::PCState thisPC,
TheISA::PCState nextPC, bool trace)
{
// Get a sequence number.
InstSeqNum seq = cpu->getAndIncrementInstSeq();
// Create a new DynInst from the instruction fetched.
DynInstPtr instruction =
new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu);
instruction->setTid(tid);
instruction->setASID(tid);
instruction->setThreadState(cpu->thread[tid]);
DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
"[sn:%lli].\n", tid, thisPC.instAddr(),
thisPC.microPC(), seq);
DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
instruction->staticInst->
disassemble(thisPC.instAddr()));
#if TRACING_ON
if (trace) {
instruction->traceData =
cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
instruction->staticInst, thisPC, curMacroop);
}
#else
instruction->traceData = NULL;
#endif
// Add instruction to the CPU's list of instructions.
instruction->setInstListIt(cpu->addInst(instruction));
// Write the instruction to the first slot in the queue
// that heads to decode.
assert(numInst < fetchWidth);
fetchQueue[tid].push_back(instruction);
assert(fetchQueue[tid].size() <= fetchQueueSize);
DPRINTF(Fetch, "[tid:%i]: Fetch queue entry created (%i/%i).\n",
tid, fetchQueue[tid].size(), fetchQueueSize);
//toDecode->insts[toDecode->size++] = instruction;
// Keep track of if we can take an interrupt at this boundary
delayedCommit[tid] = instruction->isDelayedCommit();
return instruction;
}
template<class Impl>
void
DefaultFetch<Impl>::fetch(bool &status_change)
{
//////////////////////////////////////////
// Start actual fetch
//////////////////////////////////////////
ThreadID tid = getFetchingThread(fetchPolicy);
assert(!cpu->switchedOut());
if (tid == InvalidThreadID) {
// Breaks looping condition in tick()
threadFetched = numFetchingThreads;
if (numThreads == 1) { // @todo Per-thread stats
profileStall(0);
}
return;
}
DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
// The current PC.
TheISA::PCState thisPC = pc[tid];
Addr pcOffset = fetchOffset[tid];
Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
bool inRom = isRomMicroPC(thisPC.microPC());
// If returning from the delay of a cache miss, then update the status
// to running, otherwise do the cache access. Possibly move this up
// to tick() function.
if (fetchStatus[tid] == IcacheAccessComplete) {
DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
fetchStatus[tid] = Running;
status_change = true;
} else if (fetchStatus[tid] == Running) {
// Align the fetch PC so its at the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
// If buffer is no longer valid or fetchAddr has moved to point
// to the next cache block, AND we have no remaining ucode
// from a macro-op, then start fetch from icache.
if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])
&& !inRom && !macroop[tid]) {
DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
"instruction, starting at PC %s.\n", tid, thisPC);
fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
if (fetchStatus[tid] == IcacheWaitResponse)
++icacheStallCycles;
else if (fetchStatus[tid] == ItlbWait)
++fetchTlbCycles;
else
++fetchMiscStallCycles;
return;
} else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])) {
// Stall CPU if an interrupt is posted and we're not issuing
// an delayed commit micro-op currently (delayed commit instructions
// are not interruptable by interrupts, only faults)
++fetchMiscStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid);
return;
}
} else {
if (fetchStatus[tid] == Idle) {
++fetchIdleCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
}
// Status is Idle, so fetch should do nothing.
return;
}
++fetchCycles;
TheISA::PCState nextPC = thisPC;
StaticInstPtr staticInst = NULL;
StaticInstPtr curMacroop = macroop[tid];
// If the read of the first instruction was successful, then grab the
// instructions from the rest of the cache line and put them into the
// queue heading to decode.
DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
"decode.\n", tid);
// Need to keep track of whether or not a predicted branch
// ended this fetch block.
bool predictedBranch = false;
// Need to halt fetch if quiesce instruction detected
bool quiesce = false;
TheISA::MachInst *cacheInsts =
reinterpret_cast<TheISA::MachInst *>(fetchBuffer[tid]);
const unsigned numInsts = fetchBufferSize / instSize;
unsigned blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
// Loop through instruction memory from the cache.
// Keep issuing while fetchWidth is available and branch is not
// predicted taken
while (numInst < fetchWidth && fetchQueue[tid].size() < fetchQueueSize
&& !predictedBranch && !quiesce) {
// We need to process more memory if we aren't going to get a
// StaticInst from the rom, the current macroop, or what's already
// in the decoder.
bool needMem = !inRom && !curMacroop &&
!decoder[tid]->instReady();
fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
if (needMem) {
// If buffer is no longer valid or fetchAddr has moved to point
// to the next cache block then start fetch from icache.
if (!fetchBufferValid[tid] ||
fetchBufferBlockPC != fetchBufferPC[tid])
break;
if (blkOffset >= numInsts) {
// We need to process more memory, but we've run out of the
// current block.
break;
}
if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
// Walk past any annulled delay slot instructions.
Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
while (fetchAddr != pcAddr && blkOffset < numInsts) {
blkOffset++;
fetchAddr += instSize;
}
if (blkOffset >= numInsts)
break;
}
MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
decoder[tid]->moreBytes(thisPC, fetchAddr, inst);
if (decoder[tid]->needMoreBytes()) {
blkOffset++;
fetchAddr += instSize;
pcOffset += instSize;
}
}
// Extract as many instructions and/or microops as we can from
// the memory we've processed so far.
do {
if (!(curMacroop || inRom)) {
if (decoder[tid]->instReady()) {
staticInst = decoder[tid]->decode(thisPC);
// Increment stat of fetched instructions.
++fetchedInsts;
if (staticInst->isMacroop()) {
curMacroop = staticInst;
} else {
pcOffset = 0;
}
} else {
// We need more bytes for this instruction so blkOffset and
// pcOffset will be updated
break;
}
}
// Whether we're moving to a new macroop because we're at the
// end of the current one, or the branch predictor incorrectly
// thinks we are...
bool newMacro = false;
if (curMacroop || inRom) {
if (inRom) {
staticInst = cpu->microcodeRom.fetchMicroop(
thisPC.microPC(), curMacroop);
} else {
staticInst = curMacroop->fetchMicroop(thisPC.microPC());
}
newMacro |= staticInst->isLastMicroop();
}
DynInstPtr instruction =
buildInst(tid, staticInst, curMacroop,
thisPC, nextPC, true);
ppFetch->notify(instruction);
numInst++;
#if TRACING_ON
if (DTRACE(O3PipeView)) {
instruction->fetchTick = curTick();
}
#endif
nextPC = thisPC;
// If we're branching after this instruction, quit fetching
// from the same block.
predictedBranch |= thisPC.branching();
predictedBranch |=
lookupAndUpdateNextPC(instruction, nextPC);
if (predictedBranch) {
DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
}
newMacro |= thisPC.instAddr() != nextPC.instAddr();
// Move to the next instruction, unless we have a branch.
thisPC = nextPC;
inRom = isRomMicroPC(thisPC.microPC());
if (newMacro) {
fetchAddr = thisPC.instAddr() & BaseCPU::PCMask;
blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
pcOffset = 0;
curMacroop = NULL;
}
if (instruction->isQuiesce()) {
DPRINTF(Fetch,
"Quiesce instruction encountered, halting fetch!\n");
fetchStatus[tid] = QuiescePending;
status_change = true;
quiesce = true;
break;
}
} while ((curMacroop || decoder[tid]->instReady()) &&
numInst < fetchWidth &&
fetchQueue[tid].size() < fetchQueueSize);
// Re-evaluate whether the next instruction to fetch is in micro-op ROM
// or not.
inRom = isRomMicroPC(thisPC.microPC());
}
if (predictedBranch) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
"instruction encountered.\n", tid);
} else if (numInst >= fetchWidth) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
"for this cycle.\n", tid);
} else if (blkOffset >= fetchBufferSize) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of the"
"fetch buffer.\n", tid);
}
macroop[tid] = curMacroop;
fetchOffset[tid] = pcOffset;
if (numInst > 0) {
wroteToTimeBuffer = true;
}
pc[tid] = thisPC;
// pipeline a fetch if we're crossing a fetch buffer boundary and not in
// a state that would preclude fetching
fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
issuePipelinedIfetch[tid] = fetchBufferBlockPC != fetchBufferPC[tid] &&
fetchStatus[tid] != IcacheWaitResponse &&
fetchStatus[tid] != ItlbWait &&
fetchStatus[tid] != IcacheWaitRetry &&
fetchStatus[tid] != QuiescePending &&
!curMacroop;
}
template<class Impl>
void
DefaultFetch<Impl>::recvReqRetry()
{
if (retryPkt != NULL) {
assert(cacheBlocked);
assert(retryTid != InvalidThreadID);
assert(fetchStatus[retryTid] == IcacheWaitRetry);
if (cpu->getInstPort().sendTimingReq(retryPkt)) {
fetchStatus[retryTid] = IcacheWaitResponse;
// Notify Fetch Request probe when a retryPkt is successfully sent.
// Note that notify must be called before retryPkt is set to NULL.
ppFetchRequestSent->notify(retryPkt->req);
retryPkt = NULL;
retryTid = InvalidThreadID;
cacheBlocked = false;
}
} else {
assert(retryTid == InvalidThreadID);
// Access has been squashed since it was sent out. Just clear
// the cache being blocked.
cacheBlocked = false;
}
}
///////////////////////////////////////
// //
// SMT FETCH POLICY MAINTAINED HERE //
// //
///////////////////////////////////////
template<class Impl>
ThreadID
DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
{
if (numThreads > 1) {
switch (fetch_priority) {
case SingleThread:
return 0;
case RoundRobin:
return roundRobin();
case IQ:
return iqCount();
case LSQ:
return lsqCount();
case Branch:
return branchCount();
default:
return InvalidThreadID;
}
} else {
list<ThreadID>::iterator thread = activeThreads->begin();
if (thread == activeThreads->end()) {
return InvalidThreadID;
}
ThreadID tid = *thread;
if (fetchStatus[tid] == Running ||
fetchStatus[tid] == IcacheAccessComplete ||
fetchStatus[tid] == Idle) {
return tid;
} else {
return InvalidThreadID;
}
}
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::roundRobin()
{
list<ThreadID>::iterator pri_iter = priorityList.begin();
list<ThreadID>::iterator end = priorityList.end();
ThreadID high_pri;
while (pri_iter != end) {
high_pri = *pri_iter;
assert(high_pri <= numThreads);
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle) {
priorityList.erase(pri_iter);
priorityList.push_back(high_pri);
return high_pri;
}
pri_iter++;
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::iqCount()
{
//sorted from lowest->highest
std::priority_queue<unsigned,vector<unsigned>,
std::greater<unsigned> > PQ;
std::map<unsigned, ThreadID> threadMap;
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
//we can potentially get tid collisions if two threads
//have the same iqCount, but this should be rare.
PQ.push(iqCount);
threadMap[iqCount] = tid;
}
while (!PQ.empty()) {
ThreadID high_pri = threadMap[PQ.top()];
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle)
return high_pri;
else
PQ.pop();
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::lsqCount()
{
//sorted from lowest->highest
std::priority_queue<unsigned,vector<unsigned>,
std::greater<unsigned> > PQ;
std::map<unsigned, ThreadID> threadMap;
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
//we can potentially get tid collisions if two threads
//have the same iqCount, but this should be rare.
PQ.push(ldstqCount);
threadMap[ldstqCount] = tid;
}
while (!PQ.empty()) {
ThreadID high_pri = threadMap[PQ.top()];
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle)
return high_pri;
else
PQ.pop();
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::branchCount()
{
#if 0
list<ThreadID>::iterator thread = activeThreads->begin();
assert(thread != activeThreads->end());
ThreadID tid = *thread;
#endif
panic("Branch Count Fetch policy unimplemented\n");
return InvalidThreadID;
}
template<class Impl>
void
DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid)
{
if (!issuePipelinedIfetch[tid]) {
return;
}
// The next PC to access.
TheISA::PCState thisPC = pc[tid];
if (isRomMicroPC(thisPC.microPC())) {
return;
}
Addr pcOffset = fetchOffset[tid];
Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
// Align the fetch PC so its at the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
// Unless buffer already got the block, fetch it from icache.
if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])) {
DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, "
"starting at PC %s.\n", tid, thisPC);
fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
}
}
template<class Impl>
void
DefaultFetch<Impl>::profileStall(ThreadID tid) {
DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
// @todo Per-thread stats
if (stalls[tid].drain) {
++fetchPendingDrainCycles;
DPRINTF(Fetch, "Fetch is waiting for a drain!\n");
} else if (activeThreads->empty()) {
++fetchNoActiveThreadStallCycles;
DPRINTF(Fetch, "Fetch has no active thread!\n");
} else if (fetchStatus[tid] == Blocked) {
++fetchBlockedCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
} else if (fetchStatus[tid] == Squashing) {
++fetchSquashCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
} else if (fetchStatus[tid] == IcacheWaitResponse) {
++icacheStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
tid);
} else if (fetchStatus[tid] == ItlbWait) {
++fetchTlbCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
"finish!\n", tid);
} else if (fetchStatus[tid] == TrapPending) {
++fetchPendingTrapStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n",
tid);
} else if (fetchStatus[tid] == QuiescePending) {
++fetchPendingQuiesceStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce "
"instruction!\n", tid);
} else if (fetchStatus[tid] == IcacheWaitRetry) {
++fetchIcacheWaitRetryStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n",
tid);
} else if (fetchStatus[tid] == NoGoodAddr) {
DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n",
tid);
} else {
DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n",
tid, fetchStatus[tid]);
}
}
#endif//__CPU_O3_FETCH_IMPL_HH__
| BellScurry/gem5-fault-injection | src/cpu/o3/fetch_impl.hh | C++ | bsd-3-clause | 54,320 |
/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* Copyright (c) 2010 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Nathan Binkert
*/
#include <cassert>
#include "base/callback.hh"
#include "base/inifile.hh"
#include "base/match.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "base/types.hh"
#include "debug/Checkpoint.hh"
#include "sim/probe/probe.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// SimObject member definitions
//
////////////////////////////////////////////////////////////////////////
//
// static list of all SimObjects, used for initialization etc.
//
SimObject::SimObjectList SimObject::simObjectList;
//
// SimObject constructor: used to maintain static simObjectList
//
SimObject::SimObject(const Params *p)
: EventManager(getEventQueue(p->eventq_index)), _params(p)
{
#ifdef DEBUG
doDebugBreak = false;
#endif
simObjectList.push_back(this);
probeManager = new ProbeManager(this);
}
void
SimObject::init()
{
}
void
SimObject::loadState(Checkpoint *cp)
{
if (cp->sectionExists(name())) {
DPRINTF(Checkpoint, "unserializing\n");
unserialize(cp, name());
} else {
DPRINTF(Checkpoint, "no checkpoint section found\n");
}
}
void
SimObject::initState()
{
}
void
SimObject::startup()
{
}
//
// no default statistics, so nothing to do in base implementation
//
void
SimObject::regStats()
{
}
void
SimObject::resetStats()
{
}
/**
* No probe points by default, so do nothing in base.
*/
void
SimObject::regProbePoints()
{
}
/**
* No probe listeners by default, so do nothing in base.
*/
void
SimObject::regProbeListeners()
{
}
ProbeManager *
SimObject::getProbeManager()
{
return probeManager;
}
//
// static function: serialize all SimObjects.
//
void
SimObject::serializeAll(std::ostream &os)
{
SimObjectList::reverse_iterator ri = simObjectList.rbegin();
SimObjectList::reverse_iterator rend = simObjectList.rend();
for (; ri != rend; ++ri) {
SimObject *obj = *ri;
obj->nameOut(os);
obj->serialize(os);
}
}
#ifdef DEBUG
//
// static function: flag which objects should have the debugger break
//
void
SimObject::debugObjectBreak(const string &objs)
{
SimObjectList::const_iterator i = simObjectList.begin();
SimObjectList::const_iterator end = simObjectList.end();
ObjectMatch match(objs);
for (; i != end; ++i) {
SimObject *obj = *i;
obj->doDebugBreak = match.match(obj->name());
}
}
void
debugObjectBreak(const char *objs)
{
SimObject::debugObjectBreak(string(objs));
}
#endif
unsigned int
SimObject::drain(DrainManager *drain_manager)
{
setDrainState(Drained);
return 0;
}
SimObject *
SimObject::find(const char *name)
{
SimObjectList::const_iterator i = simObjectList.begin();
SimObjectList::const_iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
if (obj->name() == name)
return obj;
}
return NULL;
}
| bxshi/gem5 | src/sim/sim_object.cc | C++ | bsd-3-clause | 4,656 |
<?php
/**
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
* @version 3.0.8
*/
namespace kartik\grid;
use kartik\base\AssetBundle;
/**
* Asset bundle for GridView Widget (for exporting content)
*
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @since 1.0
*/
class GridExportAsset extends AssetBundle
{
/**
* @inheritdoc
*/
public function init()
{
$this->setSourcePath(__DIR__ . '/assets');
$this->setupAssets('js', ['js/kv-grid-export']);
parent::init();
}
}
| hucongyang/yii | vendor/kartik-v/yii2-grid/GridExportAsset.php | PHP | bsd-3-clause | 631 |
#include <walle/sys/wallesys.h>
using namespace std;
/// Web Application Library namaspace
namespace walle {
namespace sys {
bool Filesystem::fileExist( const string &file ) {
if ( ::access(file.c_str(),F_OK) == 0 )
return true;
else
return false;
}
bool Filesystem::isLink( const string &file ) {
struct stat statbuf;
if( ::lstat(file.c_str(),&statbuf) == 0 ) {
if ( S_ISLNK(statbuf.st_mode) != 0 )
return true;
}
return false;
}
bool Filesystem::isDir( const string &file ) {
struct stat statbuf;
if( ::stat(file.c_str(),&statbuf) == 0 ) {
if ( S_ISDIR(statbuf.st_mode) != 0 )
return true;
}
return false;
}
bool Filesystem::mkLink( const string &srcfile, const string &destfile ) {
if ( ::symlink(srcfile.c_str(),destfile.c_str()) == 0 )
return true;
else
return false;
}
bool Filesystem::link(const string &srcfile, const string &destfile)
{
if ( ::link(srcfile.c_str(),destfile.c_str()) == 0 )
return true;
else
return false;
}
size_t Filesystem::fileSize( const string &file ) {
struct stat statbuf;
if( stat(file.c_str(),&statbuf)==0 )
return statbuf.st_size;
else
return -1;
}
time_t Filesystem::fileTime( const string &file ) {
struct stat statbuf;
if( stat(file.c_str(),&statbuf)==0 )
return statbuf.st_mtime;
else
return -1;
}
string Filesystem::filePath( const string &file ) {
size_t p;
if ( (p=file.rfind("/")) != file.npos )
return file.substr( 0, p );
return string( "" );
}
string Filesystem::fileName( const string &file ) {
size_t p;
if ( (p=file.rfind("/")) != file.npos )
return file.substr( p+1 );
return file;
}
bool Filesystem::renameFile( const string &oldname, const string &newname ) {
if ( ::rename(oldname.c_str(),newname.c_str()) != -1 )
return true;
else
return false;
}
bool Filesystem::copyFile( const string &srcfile, const string &destfile ) {
FILE *src=NULL, *dest=NULL;
if ( (src=fopen(srcfile.c_str(),"rb")) == NULL ) {
return false;
}
if ( (dest=fopen(destfile.c_str(),"wb+")) == NULL ) {
fclose( src );
return false;
}
const int bufsize = 8192;
char buf[bufsize];
size_t n;
while ( (n=fread(buf,1,bufsize,src)) >= 1 ) {
if ( fwrite(buf,1,n,dest) != n ) {
fclose( src );
fclose( dest );
return false;
}
}
fclose( src );
fclose( dest );
//chmod to 0666
mode_t mask = umask( 0 );
chmod( destfile.c_str(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH );
umask( mask );
return true;
}
bool Filesystem::deleteFile( const string &file ) {
if ( ::remove(file.c_str()) == 0 )
return true;
else
return false;
}
bool Filesystem::moveFile( const string &srcfile, const string &destfile ) {
if ( renameFile(srcfile,destfile) )
return true;
// rename fail, copy and delete file
if ( copyFile(srcfile,destfile) ) {
if ( deleteFile(srcfile) )
return true;
}
return false;
}
vector<string> Filesystem::dirFiles( const string &dir ) {
vector<string> files;
string file;
DIR *pdir = NULL;
dirent *pdirent = NULL;
if ( (pdir = ::opendir(dir.c_str())) != NULL ) {
while ( (pdirent=readdir(pdir)) != NULL ) {
file = pdirent->d_name;
if ( file!="." && file!=".." ) {
if ( isDir(dir+"/"+file) )
file = "/"+file;
files.push_back( file );
}
}
::closedir( pdir );
}
return files;
}
bool Filesystem::makeDir( const string &dir, const mode_t mode ) {
// check
size_t len = dir.length();
if ( len <= 0 ) return false;
string tomake;
char curchr;
for( size_t i=0; i<len; ++i ) {
// append
curchr = dir[i];
tomake += curchr;
if ( curchr=='/' || i==(len-1) ) {
// need to mkdir
if ( !fileExist(tomake) && !isDir(tomake) ) {
// able to mkdir
mode_t mask = umask( 0 );
if ( mkdir(tomake.c_str(),mode) == -1 ) {
umask( mask );
return false;
}
umask( mask );
}
}
}
return true;
}
bool Filesystem::copyDir( const string &srcdir, const string &destdir ) {
vector<string> files = dirFiles( srcdir );
string from;
string to;
if ( !fileExist(destdir) )
makeDir( destdir );
for ( size_t i=0; i<files.size(); ++i ) {
from = srcdir + "/" + files[i];
to = destdir + "/" + files[i];
if ( files[i][0] == '/' ) {
if ( !copyDir(from,to) )
return false;
}
else if ( !copyFile(from,to) )
return false;
}
return true;
}
bool Filesystem::deleteDir( const string &dir ) {
vector<string> files = dirFiles( dir );
string todel;
// ɾ³ýÎļþ
for ( size_t i=0; i<files.size(); ++i ) {
todel = dir + "/" + files[i];
// ×ÓĿ¼,µÝ¹éµ÷ÓÃ
if ( files[i][0] == '/' ) {
if ( !deleteDir(todel) )
return false;
}
// Îļþ
else if ( !deleteFile(todel) )
return false;
}
// ɾ³ýĿ¼
if ( rmdir(dir.c_str()) == 0 )
return true;
return false;
}
bool Filesystem::moveDir( const string &srcdir, const string &destdir ) {
if ( renameFile(srcdir,destdir) )
return true;
// rename fail, copy and delete dir
if ( copyDir(srcdir,destdir) ) {
if (deleteDir(srcdir) )
return true;
}
return false;
}
}
} // namespace
| lilothar/walle-c11 | walle/sys/Filesystem.cpp | C++ | bsd-3-clause | 5,052 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/sync_integration_test_util.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "sync/test/fake_server/bookmark_entity_builder.h"
#include "sync/test/fake_server/entity_builder_factory.h"
#include "sync/test/fake_server/fake_server_verifier.h"
#include "ui/base/layout.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using bookmarks_helper::AddFolder;
using bookmarks_helper::AddURL;
using bookmarks_helper::CountBookmarksWithTitlesMatching;
using bookmarks_helper::Create1xFaviconFromPNGFile;
using bookmarks_helper::GetBookmarkBarNode;
using bookmarks_helper::GetBookmarkModel;
using bookmarks_helper::GetOtherNode;
using bookmarks_helper::ModelMatchesVerifier;
using bookmarks_helper::Move;
using bookmarks_helper::Remove;
using bookmarks_helper::RemoveAll;
using bookmarks_helper::SetFavicon;
using bookmarks_helper::SetTitle;
using sync_integration_test_util::AwaitCommitActivityCompletion;
class SingleClientBookmarksSyncTest : public SyncTest {
public:
SingleClientBookmarksSyncTest() : SyncTest(SINGLE_CLIENT) {}
~SingleClientBookmarksSyncTest() override {}
// Verify that the local bookmark model (for the Profile corresponding to
// |index|) matches the data on the FakeServer. It is assumed that FakeServer
// is being used and each bookmark has a unique title. Folders are not
// verified.
void VerifyBookmarkModelMatchesFakeServer(int index);
private:
DISALLOW_COPY_AND_ASSIGN(SingleClientBookmarksSyncTest);
};
void SingleClientBookmarksSyncTest::VerifyBookmarkModelMatchesFakeServer(
int index) {
fake_server::FakeServerVerifier fake_server_verifier(GetFakeServer());
std::vector<BookmarkModel::URLAndTitle> local_bookmarks;
GetBookmarkModel(index)->GetBookmarks(&local_bookmarks);
// Verify that the number of local bookmarks matches the number in the
// server.
ASSERT_TRUE(fake_server_verifier.VerifyEntityCountByType(
local_bookmarks.size(),
syncer::BOOKMARKS));
// Verify that all local bookmark titles exist once on the server.
std::vector<BookmarkModel::URLAndTitle>::const_iterator it;
for (it = local_bookmarks.begin(); it != local_bookmarks.end(); ++it) {
ASSERT_TRUE(fake_server_verifier.VerifyEntityCountByTypeAndName(
1,
syncer::BOOKMARKS,
base::UTF16ToUTF8(it->title)));
}
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, Sanity) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
// Starting state:
// other_node
// -> top
// -> tier1_a
// -> http://mail.google.com "tier1_a_url0"
// -> http://www.pandora.com "tier1_a_url1"
// -> http://www.facebook.com "tier1_a_url2"
// -> tier1_b
// -> http://www.nhl.com "tier1_b_url0"
const BookmarkNode* top = AddFolder(0, GetOtherNode(0), 0, "top");
const BookmarkNode* tier1_a = AddFolder(0, top, 0, "tier1_a");
const BookmarkNode* tier1_b = AddFolder(0, top, 1, "tier1_b");
const BookmarkNode* tier1_a_url0 = AddURL(
0, tier1_a, 0, "tier1_a_url0", GURL("http://mail.google.com"));
const BookmarkNode* tier1_a_url1 = AddURL(
0, tier1_a, 1, "tier1_a_url1", GURL("http://www.pandora.com"));
const BookmarkNode* tier1_a_url2 = AddURL(
0, tier1_a, 2, "tier1_a_url2", GURL("http://www.facebook.com"));
const BookmarkNode* tier1_b_url0 = AddURL(
0, tier1_b, 0, "tier1_b_url0", GURL("http://www.nhl.com"));
// Setup sync, wait for its completion, and make sure changes were synced.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Ultimately we want to end up with the following model; but this test is
// more about the journey than the destination.
//
// bookmark_bar
// -> CNN (www.cnn.com)
// -> tier1_a
// -> tier1_a_url2 (www.facebook.com)
// -> tier1_a_url1 (www.pandora.com)
// -> Porsche (www.porsche.com)
// -> Bank of America (www.bankofamerica.com)
// -> Seattle Bubble
// other_node
// -> top
// -> tier1_b
// -> Wired News (www.wired.com)
// -> tier2_b
// -> tier1_b_url0
// -> tier3_b
// -> Toronto Maple Leafs (mapleleafs.nhl.com)
// -> Wynn (www.wynnlasvegas.com)
// -> tier1_a_url0
const BookmarkNode* bar = GetBookmarkBarNode(0);
const BookmarkNode* cnn = AddURL(0, bar, 0, "CNN",
GURL("http://www.cnn.com"));
ASSERT_TRUE(cnn != NULL);
Move(0, tier1_a, bar, 1);
// Wait for the bookmark position change to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
const BookmarkNode* porsche = AddURL(0, bar, 2, "Porsche",
GURL("http://www.porsche.com"));
// Rearrange stuff in tier1_a.
ASSERT_EQ(tier1_a, tier1_a_url2->parent());
ASSERT_EQ(tier1_a, tier1_a_url1->parent());
Move(0, tier1_a_url2, tier1_a, 0);
Move(0, tier1_a_url1, tier1_a, 2);
// Wait for the rearranged hierarchy to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
ASSERT_EQ(1, tier1_a_url0->parent()->GetIndexOf(tier1_a_url0));
Move(0, tier1_a_url0, bar, bar->child_count());
const BookmarkNode* boa = AddURL(0, bar, bar->child_count(),
"Bank of America", GURL("https://www.bankofamerica.com"));
ASSERT_TRUE(boa != NULL);
Move(0, tier1_a_url0, top, top->child_count());
const BookmarkNode* bubble = AddURL(
0, bar, bar->child_count(), "Seattle Bubble",
GURL("http://seattlebubble.com"));
ASSERT_TRUE(bubble != NULL);
const BookmarkNode* wired = AddURL(0, bar, 2, "Wired News",
GURL("http://www.wired.com"));
const BookmarkNode* tier2_b = AddFolder(
0, tier1_b, 0, "tier2_b");
Move(0, tier1_b_url0, tier2_b, 0);
Move(0, porsche, bar, 0);
SetTitle(0, wired, "News Wired");
SetTitle(0, porsche, "ICanHazPorsche?");
// Wait for the title change to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
ASSERT_EQ(tier1_a_url0->id(), top->GetChild(top->child_count() - 1)->id());
Remove(0, top, top->child_count() - 1);
Move(0, wired, tier1_b, 0);
Move(0, porsche, bar, 3);
const BookmarkNode* tier3_b = AddFolder(0, tier2_b, 1, "tier3_b");
const BookmarkNode* leafs = AddURL(
0, tier1_a, 0, "Toronto Maple Leafs", GURL("http://mapleleafs.nhl.com"));
const BookmarkNode* wynn = AddURL(0, bar, 1, "Wynn",
GURL("http://www.wynnlasvegas.com"));
Move(0, wynn, tier3_b, 0);
Move(0, leafs, tier3_b, 0);
// Wait for newly added bookmarks to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Only verify FakeServer data if FakeServer is being used.
// TODO(pvalenzuela): Use this style of verification in more tests once it is
// proven stable.
if (GetFakeServer())
VerifyBookmarkModelMatchesFakeServer(0);
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, InjectedBookmark) {
std::string title = "Montreal Canadiens";
fake_server::EntityBuilderFactory entity_builder_factory;
scoped_ptr<fake_server::FakeServerEntity> entity =
entity_builder_factory.NewBookmarkEntityBuilder(
title, GURL("http://canadiens.nhl.com")).Build();
fake_server_->InjectEntity(entity.Pass());
DisableVerifier();
ASSERT_TRUE(SetupClients());
ASSERT_TRUE(SetupSync());
ASSERT_EQ(1, CountBookmarksWithTitlesMatching(0, title));
}
// Test that a client doesn't mutate the favicon data in the process
// of storing the favicon data from sync to the database or in the process
// of requesting data from the database for sync.
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest,
SetFaviconHiDPIDifferentCodec) {
// Set the supported scale factors to 1x and 2x such that
// BookmarkModel::GetFavicon() requests both 1x and 2x.
// 1x -> for sync, 2x -> for the UI.
std::vector<ui::ScaleFactor> supported_scale_factors;
supported_scale_factors.push_back(ui::SCALE_FACTOR_100P);
supported_scale_factors.push_back(ui::SCALE_FACTOR_200P);
ui::SetSupportedScaleFactors(supported_scale_factors);
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(ModelMatchesVerifier(0));
const GURL page_url("http://www.google.com");
const GURL icon_url("http://www.google.com/favicon.ico");
const BookmarkNode* bookmark = AddURL(0, "title", page_url);
// Simulate receiving a favicon from sync encoded by a different PNG encoder
// than the one native to the OS. This tests the PNG data is not decoded to
// SkBitmap (or any other image format) then encoded back to PNG on the path
// between sync and the database.
gfx::Image original_favicon = Create1xFaviconFromPNGFile(
"favicon_cocoa_png_codec.png");
ASSERT_FALSE(original_favicon.IsEmpty());
SetFavicon(0, bookmark, icon_url, original_favicon,
bookmarks_helper::FROM_SYNC);
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
scoped_refptr<base::RefCountedMemory> original_favicon_bytes =
original_favicon.As1xPNGBytes();
gfx::Image final_favicon = GetBookmarkModel(0)->GetFavicon(bookmark);
scoped_refptr<base::RefCountedMemory> final_favicon_bytes =
final_favicon.As1xPNGBytes();
// Check that the data was not mutated from the original.
EXPECT_TRUE(original_favicon_bytes.get());
EXPECT_TRUE(original_favicon_bytes->Equals(final_favicon_bytes));
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest,
BookmarkAllNodesRemovedEvent) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
// Starting state:
// other_node
// -> folder0
// -> tier1_a
// -> http://mail.google.com
// -> http://www.google.com
// -> http://news.google.com
// -> http://yahoo.com
// -> http://www.cnn.com
// bookmark_bar
// -> empty_folder
// -> folder1
// -> http://yahoo.com
// -> http://gmail.com
const BookmarkNode* folder0 = AddFolder(0, GetOtherNode(0), 0, "folder0");
const BookmarkNode* tier1_a = AddFolder(0, folder0, 0, "tier1_a");
ASSERT_TRUE(AddURL(0, folder0, 1, "News", GURL("http://news.google.com")));
ASSERT_TRUE(AddURL(0, folder0, 2, "Yahoo", GURL("http://www.yahoo.com")));
ASSERT_TRUE(AddURL(0, tier1_a, 0, "Gmai", GURL("http://mail.google.com")));
ASSERT_TRUE(AddURL(0, tier1_a, 1, "Google", GURL("http://www.google.com")));
ASSERT_TRUE(
AddURL(0, GetOtherNode(0), 1, "CNN", GURL("http://www.cnn.com")));
ASSERT_TRUE(AddFolder(0, GetBookmarkBarNode(0), 0, "empty_folder"));
const BookmarkNode* folder1 =
AddFolder(0, GetBookmarkBarNode(0), 1, "folder1");
ASSERT_TRUE(AddURL(0, folder1, 0, "Yahoo", GURL("http://www.yahoo.com")));
ASSERT_TRUE(
AddURL(0, GetBookmarkBarNode(0), 2, "Gmai", GURL("http://gmail.com")));
// Set up sync, wait for its completion and verify that changes propagated.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Remove all bookmarks and wait for sync completion.
RemoveAll(0);
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
// Verify other node has no children now.
EXPECT_EQ(0, GetOtherNode(0)->child_count());
EXPECT_EQ(0, GetBookmarkBarNode(0)->child_count());
// Verify model matches verifier.
ASSERT_TRUE(ModelMatchesVerifier(0));
}
| sgraham/nope | chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc | C++ | bsd-3-clause | 12,107 |
# 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.
"""Utilities to process compresssed files."""
import contextlib
import logging
import os
import pathlib
import re
import shutil
import struct
import tempfile
import zipfile
class _ApkFileManager:
def __init__(self, temp_dir):
self._temp_dir = pathlib.Path(temp_dir)
self._subdir_by_apks_path = {}
self._infolist_by_path = {}
def _MapPath(self, path):
# Use numbered subdirectories for uniqueness.
# Suffix with basename(path) for readability.
default = '-'.join(
[str(len(self._subdir_by_apks_path)),
os.path.basename(path)])
return self._temp_dir / self._subdir_by_apks_path.setdefault(path, default)
def InfoList(self, path):
"""Returns zipfile.ZipFile(path).infolist()."""
ret = self._infolist_by_path.get(path)
if ret is None:
with zipfile.ZipFile(path) as z:
ret = z.infolist()
self._infolist_by_path[path] = ret
return ret
def SplitPath(self, minimal_apks_path, split_name):
"""Returns the path to the apk split extracted by ExtractSplits.
Args:
minimal_apks_path: The .apks file that was passed to ExtractSplits().
split_name: Then name of the split.
Returns:
Path to the extracted .apk file.
"""
subdir = self._subdir_by_apks_path[minimal_apks_path]
return self._temp_dir / subdir / 'splits' / f'{split_name}-master.apk'
def ExtractSplits(self, minimal_apks_path):
"""Extracts the master splits in the given .apks file.
Returns:
List of split names, with "base" always appearing first.
"""
dest = self._MapPath(minimal_apks_path)
split_names = []
logging.debug('Extracting %s', minimal_apks_path)
with zipfile.ZipFile(minimal_apks_path) as z:
for filename in z.namelist():
# E.g.:
# splits/base-master.apk
# splits/base-en.apk
# splits/vr-master.apk
# splits/vr-en.apk
m = re.match(r'splits/(.*)-master\.apk', filename)
if m:
split_names.append(m.group(1))
z.extract(filename, dest)
logging.debug('Extracting %s (done)', minimal_apks_path)
# Make "base" comes first since that's the main chunk of work.
# Also so that --abi-filter detection looks at it first.
return sorted(split_names, key=lambda x: (x != 'base', x))
@contextlib.contextmanager
def ApkFileManager():
"""Context manager that extracts apk splits to a temp dir."""
# Cannot use tempfile.TemporaryDirectory() here because our use of
# multiprocessing results in __del__ methods being called in forked processes.
temp_dir = tempfile.mkdtemp(suffix='-supersize')
zip_files = _ApkFileManager(temp_dir)
yield zip_files
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def UnzipToTemp(zip_path, inner_path):
"""Extract a |inner_path| from a |zip_path| file to an auto-deleted temp file.
Args:
zip_path: Path to the zip file.
inner_path: Path to the file within |zip_path| to extract.
Yields:
The path of the temp created (and auto-deleted when context exits).
"""
try:
logging.debug('Extracting %s', inner_path)
_, suffix = os.path.splitext(inner_path)
# Can't use NamedTemporaryFile() because it deletes via __del__, which will
# trigger in both this and the fork()'ed processes.
fd, temp_file = tempfile.mkstemp(suffix=suffix)
with zipfile.ZipFile(zip_path) as z:
os.write(fd, z.read(inner_path))
os.close(fd)
logging.debug('Extracting %s (done)', inner_path)
yield temp_file
finally:
os.unlink(temp_file)
def ReadZipInfoExtraFieldLength(zip_file, zip_info):
"""Reads the value of |extraLength| from |zip_info|'s local file header.
|zip_info| has an |extra| field, but it's read from the central directory.
Android's zipalign tool sets the extra field only in local file headers.
"""
# Refer to https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers
zip_file.fp.seek(zip_info.header_offset + 28)
return struct.unpack('<H', zip_file.fp.read(2))[0]
def MeasureApkSignatureBlock(zip_file):
"""Measures the size of the v2 / v3 signing block.
Refer to: https://source.android.com/security/apksigning/v2
"""
# Seek to "end of central directory" struct.
eocd_offset_from_end = -22 - len(zip_file.comment)
zip_file.fp.seek(eocd_offset_from_end, os.SEEK_END)
assert zip_file.fp.read(4) == b'PK\005\006', (
'failed to find end-of-central-directory')
# Read out the "start of central directory" offset.
zip_file.fp.seek(eocd_offset_from_end + 16, os.SEEK_END)
start_of_central_directory = struct.unpack('<I', zip_file.fp.read(4))[0]
# Compute the offset after the last zip entry.
last_info = max(zip_file.infolist(), key=lambda i: i.header_offset)
last_header_size = (30 + len(last_info.filename) +
ReadZipInfoExtraFieldLength(zip_file, last_info))
end_of_last_file = (last_info.header_offset + last_header_size +
last_info.compress_size)
return start_of_central_directory - end_of_last_file
| chromium/chromium | tools/binary_size/libsupersize/zip_util.py | Python | bsd-3-clause | 5,188 |
package cucumber.runtime.xstream;
import cucumber.deps.com.thoughtworks.xstream.converters.SingleValueConverter;
import java.util.ArrayList;
import java.util.List;
class ListConverter implements SingleValueConverter {
private final String delimiter;
private final SingleValueConverter delegate;
public ListConverter(String delimiter, SingleValueConverter delegate) {
this.delimiter = delimiter;
this.delegate = delegate;
}
@Override
public String toString(Object obj) {
boolean first = true;
if (obj instanceof List) {
StringBuilder sb = new StringBuilder();
for (Object elem : (List) obj) {
if (!first) {
sb.append(delimiter);
}
sb.append(delegate.toString(elem));
first = false;
}
return sb.toString();
} else {
return delegate.toString(obj);
}
}
@Override
public Object fromString(String s) {
final String[] strings = s.split(delimiter);
List<Object> list = new ArrayList<Object>(strings.length);
for (String elem : strings) {
list.add(delegate.fromString(elem));
}
return list;
}
@Override
public boolean canConvert(Class type) {
return List.class.isAssignableFrom(type);
}
}
| VivaceVivo/cucumber-mod-DI | core/src/main/java/cucumber/runtime/xstream/ListConverter.java | Java | mit | 1,391 |
package com.external.activeandroid.serializer;
/*
* Copyright (C) 2010 Michael Pardo
*
* 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 java.util.Date;
public final class UtilDateSerializer extends TypeSerializer {
public Class<?> getDeserializedType() {
return Date.class;
}
public Class<?> getSerializedType() {
return long.class;
}
public Long serialize(Object data) {
if (data == null) {
return null;
}
return ((Date) data).getTime();
}
public Date deserialize(Object data) {
if (data == null) {
return null;
}
return new Date((Long) data);
}
} | darlk/BeeFramework_Android | src/com/external/activeandroid/serializer/UtilDateSerializer.java | Java | mit | 1,106 |
<?php
namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs\TestKernel;
use Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand;
class OroTranslationPackCommandTest extends \PHPUnit_Framework_TestCase
{
public function testConfigure()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$app->add($this->getCommandMock());
$command = $app->find('oro:translation:pack');
$this->assertNotEmpty($command->getDescription());
$this->assertNotEmpty($command->getDefinition());
$this->assertNotEmpty($command->getHelp());
}
/**
* Test command execute
*
* @dataProvider executeInputProvider
*
* @param array $input
* @param array $expectedCalls
* @param bool|string $exception
*/
public function testExecute($input, $expectedCalls = array(), $exception = false)
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock(array_keys($expectedCalls));
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
if ($exception) {
$this->setExpectedException($exception);
}
$transServiceMock = $this->getMockBuilder(
'Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider'
)
->disableOriginalConstructor()
->getMock();
foreach ($expectedCalls as $method => $count) {
if ($method == 'getTranslationService') {
$commandMock->expects($this->exactly($count))
->method($method)
->will($this->returnValue($transServiceMock));
}
$commandMock->expects($this->exactly($count))->method($method);
}
$tester = new CommandTester($command);
$input += array('command' => $command->getName());
$tester->execute($input);
}
/**
* @return array
*/
public function executeInputProvider()
{
return array(
'error if action not specified' => array(
array('project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 0
)
),
'error if project not specified' => array(
array('--dump' => true),
array(
'dump' => 0,
'upload' => 0
),
'\RuntimeException'
),
'dump action should perform' => array(
array('--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 0
),
),
'upload action should perform' => array(
array('--upload' => true, 'project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 1,
'getTranslationService' => 1,
'getLangPackDir' => 1,
),
),
'dump and upload action should perform' => array(
array('--upload' => true, '--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 1,
'getTranslationService' => 1,
),
)
);
}
public function testUpload()
{
$this->runUploadDownloadTest('upload');
}
public function testUpdate()
{
$this->runUploadDownloadTest('upload', array('-m' => 'update'));
}
public function testDownload()
{
$this->runUploadDownloadTest('download');
}
public function runUploadDownloadTest($commandName, $args = [])
{
$kernel = new TestKernel();
$kernel->boot();
$projectId = 'someproject';
$adapterMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\CrowdinAdapter');
$adapterMock->expects($this->any())
->method('setProjectId')
->with($projectId);
$uploaderMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider');
$uploaderMock->expects($this->any())
->method('setAdapter')
->with($adapterMock)
->will($this->returnSelf());
$uploaderMock->expects($this->once())
->method('setLogger')
->with($this->isInstanceOf('Psr\Log\LoggerInterface'))
->will($this->returnSelf());
if (isset($args['-m']) && $args['-m'] == 'update') {
$uploaderMock->expects($this->once())
->method('update');
} else {
$uploaderMock->expects($this->once())
->method($commandName);
}
$kernel->getContainer()->set('oro_translation.uploader.crowdin_adapter', $adapterMock);
$kernel->getContainer()->set('oro_translation.service_provider', $uploaderMock);
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), '--' . $commandName => true, 'project' => $projectId);
if (!empty($args)) {
$input = array_merge($input, $args);
}
$tester->execute($input);
}
public function testExecuteWithoutMode()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), 'project' => 'test123');
$return = $tester->execute($input);
$this->assertEquals(1, $return);
}
/**
* @return array
*/
public function formatProvider()
{
return array(
'format do not specified, yml default' => array('yml', false),
'format specified xml expected ' => array('xml', 'xml')
);
}
/**
* Prepares command mock
* asText mocked by default in case when we don't need to mock anything
*
* @param array $methods
*
* @return \PHPUnit_Framework_MockObject_MockObject|OroTranslationPackCommand
*/
protected function getCommandMock($methods = array('asText'))
{
$commandMock = $this->getMockBuilder('Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand')
->setMethods($methods);
return $commandMock->getMock();
}
/**
* @param $class
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function getNewMock($class)
{
return $this->getMock($class, [], [], '', false);
}
}
| northdakota/platform | src/Oro/Bundle/TranslationBundle/Tests/Unit/Command/OroTranslationPackCommandTest.php | PHP | mit | 7,533 |
class AddSomeIndices < ActiveRecord::Migration
def change
add_index :updates, :created_at
add_index :observations, :created_at
add_index :observations, :observed_on
add_index :identifications, :created_at
end
end
| lucas-ez/inaturalist | db/migrate/20150319205049_add_some_indices.rb | Ruby | mit | 233 |
<?php
namespace Kunstmaan\CacheBundle\Form\Varnish;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class BanType.
*/
class BanType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('path', TextType::class, [
'label' => 'kunstmaan_cache.varnish.ban.path',
]);
$builder->add('allDomains', CheckboxType::class, [
'label' => 'kunstmaan_cache.varnish.ban.all_domains',
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'kunstmaan_cache_varnish_ban';
}
}
| mwoynarski/KunstmaanBundlesCMS | src/Kunstmaan/CacheBundle/Form/Varnish/BanType.php | PHP | mit | 844 |
package org.robolectric.shadows;
import android.widget.ArrayAdapter;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;
@SuppressWarnings("UnusedDeclaration")
@Implements(ArrayAdapter.class)
public class ShadowArrayAdapter<T> extends ShadowBaseAdapter {
@RealObject private ArrayAdapter<T> realArrayAdapter;
public int getTextViewResourceId() {
return ReflectionHelpers.getField(realArrayAdapter, "mFieldId");
}
public int getResourceId() {
return ReflectionHelpers.getField(realArrayAdapter, "mResource");
}
} | spotify/robolectric | shadows/framework/src/main/java/org/robolectric/shadows/ShadowArrayAdapter.java | Java | mit | 620 |
require File.dirname(__FILE__) + '/../spec_helper'
describe CodeFormatter do
def format(text)
CodeFormatter.new(text).to_html
end
it "determines language based on file path" do
formatter = CodeFormatter.new("")
formatter.language("unknown").should eq("unknown")
formatter.language("hello.rb").should eq("ruby")
formatter.language("hello.js").should eq("java_script")
formatter.language("hello.css").should eq("css")
formatter.language("hello.html.erb").should eq("rhtml")
formatter.language("hello.yml").should eq("yaml")
formatter.language("Gemfile").should eq("ruby")
formatter.language("app.rake").should eq("ruby")
formatter.language("foo.gemspec").should eq("ruby")
formatter.language("rails console").should eq("ruby")
formatter.language("hello.js.rjs").should eq("rjs")
formatter.language("hello.scss").should eq("css")
formatter.language("rails").should eq("ruby")
formatter.language("foo.bar ").should eq("bar")
formatter.language("foo ").should eq("foo")
formatter.language("").should eq("text")
formatter.language(nil).should eq("text")
formatter.language("0```").should eq("text")
end
it "converts to markdown" do
format("hello **world**").strip.should eq("<p>hello <strong>world</strong></p>")
end
it "hard wraps return statements" do
format("hello\nworld").strip.should eq("<p>hello<br>\nworld</p>")
end
it "autolinks a url" do
format("http://www.example.com/").strip.should eq('<p><a href="http://www.example.com/">http://www.example.com/</a></p>')
end
it "formats code block" do
# This could use some more extensive tests
format("```\nfoo\n```").strip.should include("<div class=\"code_block\">")
end
it "handle back-slashes in code block" do
# This could use some more extensive tests
format("```\nf\\'oo\n```").strip.should include("f\\'oo")
end
it "does not allow html" do
format("<img>").strip.should eq("")
end
end
| nischay13144/railscasts | spec/lib/code_formatter_spec.rb | Ruby | mit | 1,988 |
require "libxml"
require "active_support/core_ext/object/blank"
require "stringio"
module ActiveSupport
module XmlMini_LibXMLSAX #:nodoc:
extend self
# Class that will build the hash while the XML document
# is being parsed using SAX events.
class HashBuilder
include LibXML::XML::SaxParser::Callbacks
CONTENT_KEY = "__content__".freeze
HASH_SIZE_KEY = "__hash_size__".freeze
attr_reader :hash
def current_hash
@hash_stack.last
end
def on_start_document
@hash = { CONTENT_KEY => "" }
@hash_stack = [@hash]
end
def on_end_document
@hash = @hash_stack.pop
@hash.delete(CONTENT_KEY)
end
def on_start_element(name, attrs = {})
new_hash = { CONTENT_KEY => "" }.merge!(attrs)
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
case current_hash[name]
when Array then current_hash[name] << new_hash
when Hash then current_hash[name] = [current_hash[name], new_hash]
when nil then current_hash[name] = new_hash
end
@hash_stack.push(new_hash)
end
def on_end_element(name)
if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ""
current_hash.delete(CONTENT_KEY)
end
@hash_stack.pop
end
def on_characters(string)
current_hash[CONTENT_KEY] << string
end
alias_method :on_cdata_block, :on_characters
end
attr_accessor :document_class
self.document_class = HashBuilder
def parse(data)
if !data.respond_to?(:read)
data = StringIO.new(data || "")
end
char = data.getc
if char.nil?
{}
else
data.ungetc(char)
LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER)
parser = LibXML::XML::SaxParser.io(data)
document = self.document_class.new
parser.callbacks = document
parser.parse
document.hash
end
end
end
end
| arjes/rails | activesupport/lib/active_support/xml_mini/libxmlsax.rb | Ruby | mit | 2,092 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Operator x ^ y returns ToNumber(x) ^ ToNumber(y)
es5id: 11.10.2_A3_T2.3
description: >
Type(x) is different from Type(y) and both types vary between
Number (primitive or object) and Null
---*/
//CHECK#1
if ((1 ^ null) !== 1) {
$ERROR('#1: (1 ^ null) === 1. Actual: ' + ((1 ^ null)));
}
//CHECK#2
if ((null ^ 1) !== 1) {
$ERROR('#2: (null ^ 1) === 1. Actual: ' + ((null ^ 1)));
}
//CHECK#3
if ((new Number(1) ^ null) !== 1) {
$ERROR('#3: (new Number(1) ^ null) === 1. Actual: ' + ((new Number(1) ^ null)));
}
//CHECK#4
if ((null ^ new Number(1)) !== 1) {
$ERROR('#4: (null ^ new Number(1)) === 1. Actual: ' + ((null ^ new Number(1))));
}
| PiotrDabkowski/Js2Py | tests/test_cases/language/expressions/bitwise-xor/S11.10.2_A3_T2.3.js | JavaScript | mit | 802 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {runServer} from '../../src/protractor/utils';
describe('Bazel protractor utils', () => {
it('should be able to start devserver', async() => {
// Test will automatically time out if the server couldn't be launched as expected.
await runServer('angular', 'packages/bazel/test/protractor-utils/fake-devserver', '--port', []);
});
});
| petebacondarwin/angular | packages/bazel/test/protractor-utils/index_test.ts | TypeScript | mit | 557 |
require 'mws/feeds/client'
| jack0331/peddler | lib/mws/feeds.rb | Ruby | mit | 27 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Remote.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.Services
{
public class PerformanceTrackerServiceTests
{
[Fact]
public void TestTooFewSamples()
{
// minimum sample is 100
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 80);
Assert.Empty(badAnalyzers);
}
[Fact]
public void TestTracking()
{
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 200);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 101.244432561581, 54.48, 21.8163001442628);
VerifyBadAnalyzer(badAnalyzers[1], "CSharpInlineDeclarationDiagnosticAnalyzer", 49.9389715502954, 26.6686092715232, 9.2987133054884);
VerifyBadAnalyzer(badAnalyzers[2], "VisualBasicRemoveUnnecessaryCastDiagnosticAnalyzer", 42.0967360557792, 23.277619047619, 7.25464266261805);
}
[Fact]
public void TestTrackingMaxSample()
{
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 300);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 85.6039521236341, 58.4542358078603, 18.4245217226717);
VerifyBadAnalyzer(badAnalyzers[1], "VisualBasic.UseAutoProperty.UseAutoPropertyAnalyzer", 45.0918385052674, 29.0622535211268, 9.13728667060397);
VerifyBadAnalyzer(badAnalyzers[2], "CSharpInlineDeclarationDiagnosticAnalyzer", 42.2014208750466, 28.7935371179039, 7.99261581900397);
}
[Fact]
public void TestTrackingRolling()
{
// data starting to rolling at 300 data points
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 400);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 76.2748443491852, 51.1698695652174, 17.3819563479479);
VerifyBadAnalyzer(badAnalyzers[1], "VisualBasic.UseAutoProperty.UseAutoPropertyAnalyzer", 43.5700167914005, 29.2597857142857, 9.21213873850298);
VerifyBadAnalyzer(badAnalyzers[2], "InlineDeclaration.CSharpInlineDeclarationDiagnosticAnalyzer", 36.4336594793033, 23.9764782608696, 7.43956680199015);
}
[Fact]
public void TestBadAnalyzerInfoPII()
{
var badAnalyzer1 = new ExpensiveAnalyzerInfo(true, "test", 0.1, 0.1, 0.1);
Assert.True(badAnalyzer1.PIISafeAnalyzerId == badAnalyzer1.AnalyzerId);
Assert.True(badAnalyzer1.PIISafeAnalyzerId == "test");
var badAnalyzer2 = new ExpensiveAnalyzerInfo(false, "test", 0.1, 0.1, 0.1);
Assert.True(badAnalyzer2.PIISafeAnalyzerId == badAnalyzer2.AnalyzerIdHash);
Assert.True(badAnalyzer2.PIISafeAnalyzerId == "test".GetHashCode().ToString());
}
private void VerifyBadAnalyzer(ExpensiveAnalyzerInfo analyzer, string analyzerId, double lof, double mean, double stddev)
{
Assert.True(analyzer.PIISafeAnalyzerId.IndexOf(analyzerId, StringComparison.OrdinalIgnoreCase) >= 0);
Assert.Equal(lof, analyzer.LocalOutlierFactor, precision: 4);
Assert.Equal(mean, analyzer.Average, precision: 4);
Assert.Equal(stddev, analyzer.AdjustedStandardDeviation, precision: 4);
}
private List<ExpensiveAnalyzerInfo> GetBadAnalyzers(string testFileName, int to)
{
var testFile = ReadTestFile(testFileName);
var (matrix, dataCount) = CreateMatrix(testFile);
to = Math.Min(to, dataCount);
var service = new PerformanceTrackerService(minLOFValue: 0, averageThreshold: 0, stddevThreshold: 0);
for (var i = 0; i < to; i++)
{
service.AddSnapshot(CreateSnapshots(matrix, i), unitCount: 100);
}
var badAnalyzerInfo = new List<ExpensiveAnalyzerInfo>();
service.GenerateReport(badAnalyzerInfo);
return badAnalyzerInfo;
}
private IEnumerable<AnalyzerPerformanceInfo> CreateSnapshots(Dictionary<string, double[]> matrix, int index)
{
foreach (var kv in matrix)
{
var timeSpan = kv.Value[index];
if (double.IsNaN(timeSpan))
{
continue;
}
yield return new AnalyzerPerformanceInfo(kv.Key, true, TimeSpan.FromMilliseconds(timeSpan));
}
}
private (Dictionary<string, double[]> matrix, int dataCount) CreateMatrix(string testFile)
{
var matrix = new Dictionary<string, double[]>();
var lines = testFile.Split('\n');
var expectedDataCount = GetExpectedDataCount(lines[0]);
for (var i = 1; i < lines.Length; i++)
{
if (lines[i].Trim().Length == 0)
{
continue;
}
var data = SkipAnalyzerId(lines[i]).Split(',');
Assert.Equal(data.Length, expectedDataCount);
var analyzerId = GetAnalyzerId(lines[i]);
var timeSpans = new double[expectedDataCount];
for (var j = 0; j < data.Length; j++)
{
double result;
if (!double.TryParse(data[j], NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result))
{
// no data for this analyzer for this particular run
result = double.NaN;
}
timeSpans[j] = result;
}
matrix[analyzerId] = timeSpans;
}
return (matrix, expectedDataCount);
}
private string GetAnalyzerId(string line)
{
return line.Substring(1, line.LastIndexOf('"') - 1);
}
private int GetExpectedDataCount(string header)
{
var data = header.Split(',');
return data.Length - 1;
}
private string SkipAnalyzerId(string line)
{
return line.Substring(line.LastIndexOf('"') + 2);
}
private string ReadTestFile(string name)
{
var assembly = typeof(PerformanceTrackerServiceTests).Assembly;
var resourceName = GetResourceName(assembly, name);
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream == null)
{
throw new InvalidOperationException($"Resource '{resourceName}' not found in {assembly.FullName}.");
}
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
private static string GetResourceName(Assembly assembly, string name)
{
var convert = name.Replace(@"\", ".");
return assembly.GetManifestResourceNames().Where(n => n.EndsWith(convert, StringComparison.OrdinalIgnoreCase)).First();
}
}
}
| genlu/roslyn | src/VisualStudio/Core/Test.Next/Services/PerformanceTrackerServiceTests.cs | C# | mit | 7,698 |
<?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_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Gdata_Extension
*/
require_once 'Zend/Gdata/Extension.php';
/**
* Represents the yt:releaseDate element
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_YouTube_Extension_ReleaseDate extends Zend_Gdata_Extension
{
protected $_rootElement = 'releaseDate';
protected $_rootNamespace = 'yt';
public function __construct($text = null)
{
$this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
parent::__construct();
$this->_text = $text;
}
}
| ramonornela/Zebra | library/Zend/Gdata/YouTube/Extension/ReleaseDate.php | PHP | mit | 1,444 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./2.9/type"), exports);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInR5cGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEscURBQTJCIn0= | AxelSparkster/axelsparkster.github.io | node_modules/tsutils/typeguard/type.js | JavaScript | mit | 357 |
import requests
from django.utils.translation import ugettext as _
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from ..base import ProviderException
from .provider import DoubanProvider
class DoubanOAuth2Adapter(OAuth2Adapter):
provider_id = DoubanProvider.id
access_token_url = 'https://www.douban.com/service/auth2/token'
authorize_url = 'https://www.douban.com/service/auth2/auth'
profile_url = 'https://api.douban.com/v2/user/~me'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'Bearer %s' % token.token}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
"""
Douban may return data like this:
{
'code': 128,
'request': 'GET /v2/user/~me',
'msg': 'user_is_locked:53358092'
}
"""
if 'id' not in extra_data:
msg = extra_data.get('msg', _('Invalid profile data'))
raise ProviderException(msg)
return self.get_provider().sociallogin_from_response(
request, extra_data)
oauth2_login = OAuth2LoginView.adapter_view(DoubanOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(DoubanOAuth2Adapter)
| okwow123/djangol2 | example/env/lib/python2.7/site-packages/allauth/socialaccount/providers/douban/views.py | Python | mit | 1,354 |
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
before_validation :camelize_title
validates_uniqueness_of :title
def camelize_title(role_title = self.title)
self.title = role_title.to_s.camelize
end
def self.[](title)
find_or_create_by_title(title.to_s.camelize)
end
end
| clanplaid/wow.clanplaid.net | vendor/plugins/authentication/app/models/role.rb | Ruby | mit | 313 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferencePropertiesTests
{
[Fact]
public void Constructor()
{
var m = new MetadataReferenceProperties();
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "goo"), embedInteropTypes: true);
AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "goo" }, m.Aliases);
Assert.True(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, m.Kind);
Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
}
[Fact]
public void Constructor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataReferenceProperties((MetadataImageKind)byte.MaxValue));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, embedInteropTypes: true));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("x\0x")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(new[] { "blah" }));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithEmbedInteropTypes(true));
}
[Fact]
public void WithXxx()
{
var a = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true);
Assert.Equal(a.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new[] { "goo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("goo", "aaa"), embedInteropTypes: true));
Assert.Equal(a.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false));
Assert.Equal(a.WithRecursiveAliases(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true, hasRecursiveAliases: true));
var m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
}
}
}
| abock/roslyn | src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferencePropertiesTests.cs | C# | mit | 4,674 |
package com.frostwire.jlibtorrent;
import com.frostwire.jlibtorrent.swig.dht_lookup_vector;
import com.frostwire.jlibtorrent.swig.dht_routing_bucket_vector;
import com.frostwire.jlibtorrent.swig.session_status;
import java.util.ArrayList;
import java.util.List;
/**
* Contains session wide state and counters.
*
* @author gubatron
* @author aldenml
*/
public final class SessionStatus {
private final session_status s;
public SessionStatus(session_status s) {
this.s = s;
}
public session_status getSwig() {
return s;
}
/**
* false as long as no incoming connections have been
* established on the listening socket. Every time you change the listen port, this will
* be reset to false.
*
* @return
*/
public boolean hasIncomingConnections() {
return s.getHas_incoming_connections();
}
/**
* the total download and upload rates accumulated
* from all torrents. This includes bittorrent protocol, DHT and an estimated TCP/IP
* protocol overhead.
*
* @return
*/
public int getUploadRate() {
return s.getUpload_rate();
}
/**
* the total download and upload rates accumulated
* from all torrents. This includes bittorrent protocol, DHT and an estimated TCP/IP
* protocol overhead.
*
* @return
*/
public int getDownloadRate() {
return s.getDownload_rate();
}
/**
* the total number of bytes downloaded and
* uploaded to and from all torrents. This also includes all the protocol overhead.
*
* @return
*/
public long getTotalDownload() {
return s.getTotal_download();
}
/**
* the total number of bytes downloaded and
* uploaded to and from all torrents. This also includes all the protocol overhead.
*
* @return
*/
public long getTotalUpload() {
return s.getTotal_upload();
}
/**
* the rate of the payload
* down- and upload only.
*
* @return
*/
public int getPayloadUploadRate() {
return s.getPayload_upload_rate();
}
/**
* the rate of the payload down- and upload only.
*
* @return
*/
public int getPayloadDownloadRate() {
return s.getPayload_download_rate();
}
/**
* the total transfers of payload
* only. The payload does not include the bittorrent protocol overhead, but only parts of the
* actual files to be downloaded.
*
* @return
*/
public long getTotalPayloadDownload() {
return s.getTotal_payload_download();
}
/**
* the total transfers of payload
* only. The payload does not include the bittorrent protocol overhead, but only parts of the
* actual files to be downloaded.
*
* @return
*/
public long getTotalPayloadUpload() {
return s.getTotal_payload_upload();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public int getIPOverheadUploadRate() {
return s.getIp_overhead_upload_rate();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public int getIPOverheadDownloadRate() {
return s.getIp_overhead_download_rate();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public long getTotalIPOverheadDownload() {
return s.getTotal_ip_overhead_download();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public long getTotalIPOverheadUpload() {
return s.getTotal_ip_overhead_upload();
}
/**
* The upload rate used by DHT traffic.
*
* @return
*/
public int getDHTUploadRate() {
return s.getDht_upload_rate();
}
/**
* The download rate used by DHT traffic.
*
* @return
*/
public int getDHTDownloadRate() {
return s.getDht_download_rate();
}
/**
* The total number of bytes received from the DHT.
*
* @return
*/
public long getTotalDHTDownload() {
return s.getTotal_dht_download();
}
/**
* The total number of bytes sent to the DHT.
*
* @return
*/
public long getTotalDHTUpload() {
return s.getTotal_dht_upload();
}
/*
// the upload and download rate used by tracker traffic. Also the total number
// of bytes sent and received to and from trackers.
int tracker_upload_rate;
int tracker_download_rate;
size_type total_tracker_download;
size_type total_tracker_upload;
// the number of bytes that has been received more than once.
// This can happen if a request from a peer times out and is requested from a different
// peer, and then received again from the first one. To make this lower, increase the
// ``request_timeout`` and the ``piece_timeout`` in the session settings.
size_type total_redundant_bytes;
// the number of bytes that was downloaded which later failed
// the hash-check.
size_type total_failed_bytes;
// the total number of peer connections this session has. This includes
// incoming connections that still hasn't sent their handshake or outgoing connections
// that still hasn't completed the TCP connection. This number may be slightly higher
// than the sum of all peers of all torrents because the incoming connections may not
// be assigned a torrent yet.
int num_peers;
// the current number of unchoked peers.
int num_unchoked;
// the current allowed number of unchoked peers.
int allowed_upload_slots;
// the number of peers that are
// waiting for more bandwidth quota from the torrent rate limiter.
int up_bandwidth_queue;
int down_bandwidth_queue;
// count the number of
// bytes the connections are waiting for to be able to send and receive.
int up_bandwidth_bytes_queue;
int down_bandwidth_bytes_queue;
// tells the number of
// seconds until the next optimistic unchoke change and the start of the next
// unchoke interval. These numbers may be reset prematurely if a peer that is
// unchoked disconnects or becomes notinterested.
int optimistic_unchoke_counter;
int unchoke_counter;
// the number of peers currently
// waiting on a disk write or disk read to complete before it receives or sends
// any more data on the socket. It'a a metric of how disk bound you are.
int disk_write_queue;
int disk_read_queue;
*/
/**
* Only available when built with DHT support. It is set to 0 if the DHT isn't running.
* <p/>
* When the DHT is running, ``dht_nodes`` is set to the number of nodes in the routing
* table. This number only includes *active* nodes, not cache nodes.
* <p/>
* These nodes are used to replace the regular nodes in the routing table in case any of them
* becomes unresponsive.
*
* @return
*/
public int getDHTNodes() {
return s.getDht_nodes();
}
/**
* Only available when built with DHT support. It is set to 0 if the DHT isn't running.
* <p/>
* When the DHT is running, ``dht_node_cache`` is set to the number of nodes in the node cache.
* <p/>
* These nodes are used to replace the regular nodes in the routing table in case any of them
* becomes unresponsive.
*
* @return
*/
public int getDHTNodeCache() {
return s.getDht_node_cache();
}
/**
* the number of torrents tracked by the DHT at the moment.
*
* @return
*/
public int getDHTTorrents() {
return s.getDht_torrents();
}
/**
* An estimation of the total number of nodes in the DHT network.
*
* @return
*/
public long getDHTGlobalNodes() {
return s.getDht_global_nodes();
}
/**
* a vector of the currently running DHT lookups.
*
* @return
*/
public List<DHTLookup> getActiveRequests() {
dht_lookup_vector v = s.getActive_requests();
int size = (int) v.size();
List<DHTLookup> l = new ArrayList<DHTLookup>(size);
for (int i = 0; i < size; i++) {
l.add(new DHTLookup(v.get(i)));
}
return l;
}
/**
* contains information about every bucket in the DHT routing table.
*
* @return
*/
public List<DHTRoutingBucket> getDHTRoutingTable() {
dht_routing_bucket_vector v = s.getDht_routing_table();
int size = (int) v.size();
List<DHTRoutingBucket> l = new ArrayList<DHTRoutingBucket>(size);
for (int i = 0; i < size; i++) {
l.add(new DHTRoutingBucket(v.get(i)));
}
return l;
}
/**
* the number of nodes allocated dynamically for a
* particular DHT lookup. This represents roughly the amount of memory used
* by the DHT.
*
* @return
*/
public int getDHTTotalAllocations() {
return s.getDht_total_allocations();
}
/**
* statistics on the uTP sockets.
*
* @return
*/
public UTPStatus getUTPStats() {
return new UTPStatus(s.getUtp_stats());
}
/**
* the number of known peers across all torrents. These are not necessarily
* connected peers, just peers we know of.
*
* @return
*/
public int getPeerlistSize() {
return s.getPeerlist_size();
}
}
| tchoulihan/frostwire-jlibtorrent | src/com/frostwire/jlibtorrent/SessionStatus.java | Java | mit | 9,844 |
var assert = require('assert');
var jsv = require('jsverify');
var R = require('..');
var eq = require('./shared/eq');
describe('compose', function() {
it('is a variadic function', function() {
eq(typeof R.compose, 'function');
eq(R.compose.length, 0);
});
it('performs right-to-left function composition', function() {
// f :: (String, Number?) -> ([Number] -> [Number])
var f = R.compose(R.map, R.multiply, parseInt);
eq(f.length, 2);
eq(f('10')([1, 2, 3]), [10, 20, 30]);
eq(f('10', 2)([1, 2, 3]), [2, 4, 6]);
});
it('passes context to functions', function() {
function x(val) {
return this.x * val;
}
function y(val) {
return this.y * val;
}
function z(val) {
return this.z * val;
}
var context = {
a: R.compose(x, y, z),
x: 4,
y: 2,
z: 1
};
eq(context.a(5), 40);
});
it('throws if given no arguments', function() {
assert.throws(
function() { R.compose(); },
function(err) {
return err.constructor === Error &&
err.message === 'compose requires at least one argument';
}
);
});
it('can be applied to one argument', function() {
var f = function(a, b, c) { return [a, b, c]; };
var g = R.compose(f);
eq(g.length, 3);
eq(g(1, 2, 3), [1, 2, 3]);
});
});
describe('compose properties', function() {
jsv.property('composes two functions', jsv.fn(), jsv.fn(), jsv.nat, function(f, g, x) {
return R.equals(R.compose(f, g)(x), f(g(x)));
});
jsv.property('associative', jsv.fn(), jsv.fn(), jsv.fn(), jsv.nat, function(f, g, h, x) {
var result = f(g(h(x)));
return R.all(R.equals(result), [
R.compose(f, g, h)(x),
R.compose(f, R.compose(g, h))(x),
R.compose(R.compose(f, g), h)(x)
]);
});
});
| angeloocana/ramda | test/compose.js | JavaScript | mit | 1,837 |
/*
* The MIT License
*
* Copyright (c) 2011, CloudBees, Inc.
*
* 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.
*/
package hudson.cli;
import hudson.remoting.ClassFilter;
import hudson.remoting.ObjectInputStreamEx;
import hudson.remoting.SocketChannelStream;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.AlgorithmParameterGenerator;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import org.jenkinsci.remoting.util.AnonymousClassWarnings;
/**
* @deprecated No longer used.
*/
@Deprecated
public class Connection {
public final InputStream in;
public final OutputStream out;
public final DataInputStream din;
public final DataOutputStream dout;
public Connection(Socket socket) throws IOException {
this(SocketChannelStream.in(socket),SocketChannelStream.out(socket));
}
public Connection(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
this.din = new DataInputStream(in);
this.dout = new DataOutputStream(out);
}
//
//
// Convenience methods
//
//
public void writeUTF(String msg) throws IOException {
dout.writeUTF(msg);
}
public String readUTF() throws IOException {
return din.readUTF();
}
public void writeBoolean(boolean b) throws IOException {
dout.writeBoolean(b);
}
public boolean readBoolean() throws IOException {
return din.readBoolean();
}
/**
* Sends a serializable object.
*/
public void writeObject(Object o) throws IOException {
ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(out);
oos.writeObject(o);
// don't close oss, which will close the underlying stream
// no need to flush either, given the way oos is implemented
}
/**
* Receives an object sent by {@link #writeObject(Object)}
*/
public <T> T readObject() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStreamEx(in,
getClass().getClassLoader(), ClassFilter.DEFAULT);
return (T)ois.readObject();
}
public void writeKey(Key key) throws IOException {
writeUTF(new String(Base64.encodeBase64(key.getEncoded())));
}
public X509EncodedKeySpec readKey() throws IOException {
byte[] otherHalf = Base64.decodeBase64(readUTF()); // for historical reasons, we don't use readByteArray()
return new X509EncodedKeySpec(otherHalf);
}
public void writeByteArray(byte[] data) throws IOException {
dout.writeInt(data.length);
dout.write(data);
}
public byte[] readByteArray() throws IOException {
int bufSize = din.readInt();
if (bufSize < 0) {
throw new IOException("DataInputStream unexpectedly returned negative integer");
}
byte[] buf = new byte[bufSize];
din.readFully(buf);
return buf;
}
/**
* Performs a Diffie-Hellman key exchange and produce a common secret between two ends of the connection.
*
* <p>
* DH is also useful as a coin-toss algorithm. Two parties get the same random number without trusting
* each other.
*/
public KeyAgreement diffieHellman(boolean side) throws IOException, GeneralSecurityException {
return diffieHellman(side,512);
}
public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
KeyPair keyPair;
PublicKey otherHalf;
if (side) {
AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
paramGen.init(keySize);
KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class));
keyPair = dh.generateKeyPair();
// send a half and get a half
writeKey(keyPair.getPublic());
otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
} else {
otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
keyPair = keyPairGen.generateKeyPair();
// send a half and get a half
writeKey(keyPair.getPublic());
}
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(keyPair.getPrivate());
ka.doPhase(otherHalf, true);
return ka;
}
/**
* Upgrades a connection with transport encryption by the specified symmetric cipher.
*
* @return
* A new {@link Connection} object that includes the transport encryption.
*/
public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException {
Cipher cout = Cipher.getInstance(algorithm);
cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherOutputStream o = new CipherOutputStream(out, cout);
Cipher cin = Cipher.getInstance(algorithm);
cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherInputStream i = new CipherInputStream(in, cin);
return new Connection(i,o);
}
/**
* Given a byte array that contains arbitrary number of bytes, digests or expands those bits into the specified
* number of bytes without loss of entropy.
*
* Cryptographic utility code.
*/
public static byte[] fold(byte[] bytes, int size) {
byte[] r = new byte[size];
for (int i=Math.max(bytes.length,size)-1; i>=0; i-- ) {
r[i%r.length] ^= bytes[i%bytes.length];
}
return r;
}
private String detectKeyAlgorithm(KeyPair kp) {
return detectKeyAlgorithm(kp.getPublic());
}
private String detectKeyAlgorithm(PublicKey kp) {
if (kp instanceof RSAPublicKey) return "RSA";
if (kp instanceof DSAPublicKey) return "DSA";
throw new IllegalArgumentException("Unknown public key type: "+kp);
}
/**
* Used in conjunction with {@link #verifyIdentity(byte[])} to prove
* that we actually own the private key of the given key pair.
*/
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
String algorithm = detectKeyAlgorithm(key);
writeUTF(algorithm);
writeKey(key.getPublic());
Signature sig = Signature.getInstance("SHA1with"+algorithm);
sig.initSign(key.getPrivate());
sig.update(key.getPublic().getEncoded());
sig.update(sharedSecret);
writeObject(sig.sign());
}
/**
* Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get.
*/
public PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, GeneralSecurityException {
try {
String serverKeyAlgorithm = readUTF();
PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey());
// verify the identity of the server
Signature sig = Signature.getInstance("SHA1with"+serverKeyAlgorithm);
sig.initVerify(spk);
sig.update(spk.getEncoded());
sig.update(sharedSecret);
sig.verify((byte[]) readObject());
return spk;
} catch (ClassNotFoundException e) {
throw new Error(e); // impossible
}
}
public void close() throws IOException {
in.close();
out.close();
}
}
| Vlatombe/jenkins | core/src/main/java/hudson/cli/Connection.java | Java | mit | 9,707 |
#include <utilities.h>
#include <fstream>
namespace Utilities
{
namespace Math
{
double degreesToRadians(double angle)
{
return (angle * PI) / 180;
}
double radiansToDegrees(double angle)
{
return angle * (180/PI);
}
}
namespace File
{
bool getFileContents(std::vector<uint8_t> &fileBuffer, const std::string &filePath)
{
std::ifstream inFileStream(filePath, std::ios::binary);
if (!inFileStream) {
return false;
}
inFileStream.seekg(0, std::ios::end);
auto fileLength = inFileStream.tellg();
inFileStream.seekg(0, std::ios::beg);
fileBuffer.resize(fileLength);
inFileStream.read(reinterpret_cast<char *>(fileBuffer.data()), fileLength);
return true;
}
}
}
| velocic/opengl-tutorial-solutions | 22-loading-3d-models/src/utilities.cpp | C++ | mit | 909 |
var Emitter = require("events").EventEmitter;
var shared;
function Bank(options) {
this.address = options.address;
this.io = options.io;
this.io.i2cConfig();
}
Bank.prototype.read = function(register, numBytes, callback) {
if (register) {
this.io.i2cRead(this.address, register, numBytes, callback);
} else {
this.io.i2cRead(this.address, numBytes, callback);
}
};
Bank.prototype.write = function(register, bytes) {
if (!Array.isArray(bytes)) {
bytes = [bytes];
}
this.io.i2cWrite(this.address, register, bytes);
};
// http://www.nr.edu/csc200/labs-ev3/ev3-user-guide-EN.pdf
function EVS(options) {
if (shared) {
return shared;
}
this.bank = {
a: new Bank({
address: EVS.BANK_A,
io: options.io,
}),
b: new Bank({
address: EVS.BANK_B,
io: options.io,
})
};
shared = this;
}
EVS.shieldPort = function(pin) {
var port = EVS[pin];
if (port === undefined) {
throw new Error("Invalid EVShield pin name");
}
var address, analog, bank, motor, mode, offset, sensor;
var endsWithS1 = false;
if (pin.startsWith("BA")) {
address = EVS.BANK_A;
bank = "a";
} else {
address = EVS.BANK_B;
bank = "b";
}
if (pin.includes("M")) {
motor = pin.endsWith("M1") ? EVS.S1 : EVS.S2;
}
if (pin.includes("S")) {
endsWithS1 = pin.endsWith("S1");
// Used for reading 2 byte integer values from raw sensors
analog = endsWithS1 ? EVS.S1_ANALOG : EVS.S2_ANALOG;
// Sensor Mode (1 or 2?)
mode = endsWithS1 ? EVS.S1_MODE : EVS.S2_MODE;
// Used for read registers
offset = endsWithS1 ? EVS.S1_OFFSET : EVS.S2_OFFSET;
// Used to address "sensor type"
sensor = endsWithS1 ? EVS.S1 : EVS.S2;
}
return {
address: address,
analog: analog,
bank: bank,
mode: mode,
motor: motor,
offset: offset,
port: port,
sensor: sensor,
};
};
EVS.isRawSensor = function(port) {
return port.analog === EVS.S1_ANALOG || port.analog === EVS.S2_ANALOG;
};
EVS.prototype = Object.create(Emitter.prototype, {
constructor: {
value: EVS
}
});
EVS.prototype.setup = function(port, type) {
this.bank[port.bank].write(port.mode, [type]);
};
EVS.prototype.read = function(port, register, numBytes, callback) {
if (port.sensor && port.offset && !EVS.isRawSensor(port)) {
register += port.offset;
}
this.bank[port.bank].read(register, numBytes, callback);
};
EVS.prototype.write = function(port, register, data) {
this.bank[port.bank].write(register, data);
};
/*
* Shield Registers
*/
EVS.BAS1 = 0x01;
EVS.BAS2 = 0x02;
EVS.BBS1 = 0x03;
EVS.BBS2 = 0x04;
EVS.BAM1 = 0x05;
EVS.BAM2 = 0x06;
EVS.BBM1 = 0x07;
EVS.BBM2 = 0x08;
EVS.BANK_A = 0x1A;
EVS.BANK_B = 0x1B;
EVS.S1 = 0x01;
EVS.S2 = 0x02;
EVS.M1 = 0x01;
EVS.M2 = 0x02;
EVS.MM = 0x03;
EVS.Type_NONE = 0x00;
EVS.Type_SWITCH = 0x01;
EVS.Type_ANALOG = 0x02;
EVS.Type_I2C = 0x09;
/*
* Sensor Mode NXT
*/
EVS.Type_NXT_LIGHT_REFLECTED = 0x03;
EVS.Type_NXT_LIGHT = 0x04;
EVS.Type_NXT_COLOR = 0x0D;
EVS.Type_NXT_COLOR_RGBRAW = 0x04;
EVS.Type_NXT_COLORRED = 0x0E;
EVS.Type_NXT_COLORGREEN = 0x0F;
EVS.Type_NXT_COLORBLUE = 0x10;
EVS.Type_NXT_COLORNONE = 0x11;
EVS.Type_DATABIT0_HIGH = 0x40;
/*
* Sensor Port Controls
*/
EVS.S1_MODE = 0x6F;
// EVS.S1_EV3_MODE = 0x6F;
EVS.S1_ANALOG = 0x70;
EVS.S1_OFFSET = 0;
EVS.S2_MODE = 0xA3;
// EVS.S2_EV3_MODE = 0x6F;
EVS.S2_ANALOG = 0xA4;
EVS.S2_OFFSET = 52;
/*
* Sensor Mode EV3
*/
EVS.Type_EV3_LIGHT_REFLECTED = 0x00;
EVS.Type_EV3_LIGHT = 0x01;
EVS.Type_EV3_COLOR = 0x02;
EVS.Type_EV3_COLOR_REFRAW = 0x03;
EVS.Type_EV3_COLOR_RGBRAW = 0x04;
EVS.Type_EV3_TOUCH = 0x12;
EVS.Type_EV3 = 0x13;
/*
* Sensor Read Registers
*/
EVS.Light = 0x83;
EVS.Bump = 0x84;
EVS.ColorMeasure = 0x83;
EVS.Proximity = 0x83;
EVS.Touch = 0x83;
EVS.Ultrasonic = 0x81;
EVS.Mode = 0x81;
/*
* Sensor Read Byte Counts
*/
EVS.Light_Bytes = 2;
EVS.Analog_Bytes = 2;
EVS.Bump_Bytes = 1;
EVS.ColorMeasure_Bytes = 2;
EVS.Proximity_Bytes = 2;
EVS.Touch_Bytes = 1;
/*
* Motor selection
*/
EVS.Motor_1 = 0x01;
EVS.Motor_2 = 0x02;
EVS.Motor_Both = 0x03;
/*
* Motor next action
*/
// stop and let the motor coast.
EVS.Motor_Next_Action_Float = 0x00;
// apply brakes, and resist change to tachometer, but if tach position is forcibly changed, do not restore position
EVS.Motor_Next_Action_Brake = 0x01;
// apply brakes, and restore externally forced change to tachometer
EVS.Motor_Next_Action_BrakeHold = 0x02;
EVS.Motor_Stop = 0x60;
EVS.Motor_Reset = 0x52;
/*
* Motor direction
*/
EVS.Motor_Reverse = 0x00;
EVS.Motor_Forward = 0x01;
/*
* Motor Tachometer movement
*/
// Move the tach to absolute value provided
EVS.Motor_Move_Absolute = 0x00;
// Move the tach relative to previous position
EVS.Motor_Move_Relative = 0x01;
/*
* Motor completion
*/
EVS.Motor_Completion_Dont_Wait = 0x00;
EVS.Motor_Completion_Wait_For = 0x01;
/*
* 0-100
*/
EVS.Speed_Full = 90;
EVS.Speed_Medium = 60;
EVS.Speed_Slow = 25;
/*
* Motor Port Controls
*/
EVS.CONTROL_SPEED = 0x01;
EVS.CONTROL_RAMP = 0x02;
EVS.CONTROL_RELATIVE = 0x04;
EVS.CONTROL_TACHO = 0x08;
EVS.CONTROL_BRK = 0x10;
EVS.CONTROL_ON = 0x20;
EVS.CONTROL_TIME = 0x40;
EVS.CONTROL_GO = 0x80;
EVS.STATUS_SPEED = 0x01;
EVS.STATUS_RAMP = 0x02;
EVS.STATUS_MOVING = 0x04;
EVS.STATUS_TACHO = 0x08;
EVS.STATUS_BREAK = 0x10;
EVS.STATUS_OVERLOAD = 0x20;
EVS.STATUS_TIME = 0x40;
EVS.STATUS_STALL = 0x80;
EVS.COMMAND = 0x41;
EVS.VOLTAGE = 0x6E;
EVS.SETPT_M1 = 0x42;
EVS.SPEED_M1 = 0x46;
EVS.TIME_M1 = 0x47;
EVS.CMD_B_M1 = 0x48;
EVS.CMD_A_M1 = 0x49;
EVS.SETPT_M2 = 0x4A;
EVS.SPEED_M2 = 0x4E;
EVS.TIME_M2 = 0x4F;
EVS.CMD_B_M2 = 0x50;
EVS.CMD_A_M2 = 0x51;
/*
* Motor Read registers.
*/
EVS.POSITION_M1 = 0x52;
EVS.POSITION_M2 = 0x56;
EVS.STATUS_M1 = 0x5A;
EVS.STATUS_M2 = 0x5B;
EVS.TASKS_M1 = 0x5C;
EVS.TASKS_M2 = 0x5D;
EVS.ENCODER_PID = 0x5E;
EVS.SPEED_PID = 0x64;
EVS.PASS_COUNT = 0x6A;
EVS.TOLERANCE = 0x6B;
/*
* Built-in components
*/
EVS.BTN_PRESS = 0xDA;
EVS.RGB_LED = 0xD7;
EVS.CENTER_RGB_LED = 0xDE;
module.exports = EVS;
| manorius/printing_with_node | node_modules/johnny-five/lib/evshield.js | JavaScript | mit | 6,044 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.api.editor.gutter;
public final class Gutters {
private Gutters() {
}
/** Logical identifer for the breakpoints gutter. */
public static final String BREAKPOINTS_GUTTER = "breakpoints";
/** Logical identifer for the line number gutter. */
public static final String LINE_NUMBERS_GUTTER = "lineNumbers";
/** Logical identifer for the annotations gutter. */
public static final String ANNOTATION_GUTTER = "annotation";
}
| gazarenkov/che-sketch | ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/gutter/Gutters.java | Java | epl-1.0 | 1,006 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.ssh.shared;
/**
* Constants for ssh API
*
* @author Sergii Leschenko
*/
public final class Constants {
public static final String LINK_REL_GENERATE_PAIR = "create pair";
public static final String LINK_REL_CREATE_PAIR = "create pair";
public static final String LINK_REL_GET_PAIRS = "get pairs";
public static final String LINK_REL_GET_PAIR = "get pair";
public static final String LINK_REL_REMOVE_PAIR = "remove pair";
private Constants() {}
}
| gazarenkov/che-sketch | wsmaster/che-core-api-ssh-shared/src/main/java/org/eclipse/che/api/ssh/shared/Constants.java | Java | epl-1.0 | 1,038 |
<?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_Validate
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Validate_Barcode_AdapterAbstract
*/
#require_once 'Zend/Validate/Barcode/AdapterAbstract.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_Barcode_Gtin14 extends Zend_Validate_Barcode_AdapterAbstract
{
/**
* Allowed barcode lengths
* @var integer
*/
protected $_length = 14;
/**
* Allowed barcode characters
* @var string
*/
protected $_characters = '0123456789';
/**
* Checksum function
* @var string
*/
protected $_checksum = '_gtin';
}
| T0MM0R/magento | web/lib/Zend/Validate/Barcode/Gtin14.php | PHP | gpl-2.0 | 1,429 |
<?php
/**
* @file
* Contains \Drupal\devel_generate\Plugin\DevelGenerate\ContentDevelGenerate.
*/
namespace Drupal\devel_generate\Plugin\DevelGenerate;
use Drupal\comment\CommentManagerInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\devel_generate\DevelGenerateBase;
use Drupal\field\Entity\FieldConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a ContentDevelGenerate plugin.
*
* @DevelGenerate(
* id = "content",
* label = @Translation("content"),
* description = @Translation("Generate a given number of content. Optionally delete current content."),
* url = "content",
* permission = "administer devel_generate",
* settings = {
* "num" = 50,
* "kill" = FALSE,
* "max_comments" = 0,
* "title_length" = 4
* }
* )
*/
class ContentDevelGenerate extends DevelGenerateBase implements ContainerFactoryPluginInterface {
/**
* The node storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeStorage;
/**
* The node type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeTypeStorage;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The comment manager service.
*
* @var \Drupal\comment\CommentManagerInterface
*/
protected $commentManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The url generator service.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param array $plugin_definition
* @param \Drupal\Core\Entity\EntityStorageInterface $node_storage
* The node storage.
* @param \Drupal\Core\Entity\EntityStorageInterface $node_type_storage
* The node type storage.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\comment\CommentManagerInterface $comment_manager
* The comment manager service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
* The url generator service.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
*/
public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityStorageInterface $node_storage, EntityStorageInterface $node_type_storage, ModuleHandlerInterface $module_handler, CommentManagerInterface $comment_manager = NULL, LanguageManagerInterface $language_manager, UrlGeneratorInterface $url_generator, DateFormatterInterface $date_formatter) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->moduleHandler = $module_handler;
$this->nodeStorage = $node_storage;
$this->nodeTypeStorage = $node_type_storage;
$this->commentManager = $comment_manager;
$this->languageManager = $language_manager;
$this->urlGenerator = $url_generator;
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$entity_manager = $container->get('entity.manager');
return new static(
$configuration, $plugin_id, $plugin_definition,
$entity_manager->getStorage('node'),
$entity_manager->getStorage('node_type'),
$container->get('module_handler'),
$container->has('comment.manager') ? $container->get('comment.manager') : NULL,
$container->get('language_manager'),
$container->get('url_generator'),
$container->get('date.formatter')
);
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$types = $this->nodeTypeStorage->loadMultiple();
if (empty($types)) {
$create_url = $this->urlGenerator->generateFromRoute('node.type_add');
$this->setMessage($this->t('You do not have any content types that can be generated. <a href="@create-type">Go create a new content type</a>', array('@create-type' => $create_url)), 'error', FALSE);
return;
}
$options = array();
foreach ($types as $type) {
$options[$type->id()] = array(
'type' => array('#markup' => $type->label()),
);
if ($this->commentManager) {
$comment_fields = $this->commentManager->getFields('node');
$map = array($this->t('Hidden'), $this->t('Closed'), $this->t('Open'));
$fields = array();
foreach ($comment_fields as $field_name => $info) {
// Find all comment fields for the bundle.
if (in_array($type->id(), $info['bundles'])) {
$instance = FieldConfig::loadByName('node', $type->id(), $field_name);
$default_value = $instance->getDefaultValueLiteral();
$default_mode = reset($default_value);
$fields[] = SafeMarkup::format('@field: !state', array(
'@field' => $instance->label(),
'!state' => $map[$default_mode['status']],
));
}
}
// @todo Refactor display of comment fields.
if (!empty($fields)) {
$options[$type->id()]['comments'] = array(
'data' => array(
'#theme' => 'item_list',
'#items' => $fields,
),
);
}
else {
$options[$type->id()]['comments'] = $this->t('No comment fields');
}
}
}
$header = array(
'type' => $this->t('Content type'),
);
if ($this->commentManager) {
$header['comments'] = array(
'data' => $this->t('Comments'),
'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
);
}
$form['node_types'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
);
$form['kill'] = array(
'#type' => 'checkbox',
'#title' => $this->t('<strong>Delete all content</strong> in these content types before generating new content.'),
'#default_value' => $this->getSetting('kill'),
);
$form['num'] = array(
'#type' => 'number',
'#title' => $this->t('How many nodes would you like to generate?'),
'#default_value' => $this->getSetting('num'),
'#required' => TRUE,
'#min' => 0,
);
$options = array(1 => $this->t('Now'));
foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) {
$options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
}
$form['time_range'] = array(
'#type' => 'select',
'#title' => $this->t('How far back in time should the nodes be dated?'),
'#description' => $this->t('Node creation dates will be distributed randomly from the current time, back to the selected time.'),
'#options' => $options,
'#default_value' => 604800,
);
$form['max_comments'] = array(
'#type' => $this->moduleHandler->moduleExists('comment') ? 'number' : 'value',
'#title' => $this->t('Maximum number of comments per node.'),
'#description' => $this->t('You must also enable comments for the content types you are generating. Note that some nodes will randomly receive zero comments. Some will receive the max.'),
'#default_value' => $this->getSetting('max_comments'),
'#min' => 0,
'#access' => $this->moduleHandler->moduleExists('comment'),
);
$form['title_length'] = array(
'#type' => 'number',
'#title' => $this->t('Maximum number of words in titles'),
'#default_value' => $this->getSetting('title_length'),
'#required' => TRUE,
'#min' => 1,
'#max' => 255,
);
$form['add_alias'] = array(
'#type' => 'checkbox',
'#disabled' => !$this->moduleHandler->moduleExists('path'),
'#description' => $this->t('Requires path.module'),
'#title' => $this->t('Add an url alias for each node.'),
'#default_value' => FALSE,
);
$form['add_statistics'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Add statistics for each node (node_counter table).'),
'#default_value' => TRUE,
'#access' => $this->moduleHandler->moduleExists('statistics'),
);
$options = array();
// We always need a language.
$languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
foreach ($languages as $langcode => $language) {
$options[$langcode] = $language->getName();
}
$form['add_language'] = array(
'#type' => 'select',
'#title' => $this->t('Set language on nodes'),
'#multiple' => TRUE,
'#description' => $this->t('Requires locale.module'),
'#options' => $options,
'#default_value' => array(
$this->languageManager->getDefaultLanguage()->getId(),
),
);
$form['#redirect'] = FALSE;
return $form;
}
/**
* {@inheritdoc}
*/
protected function generateElements(array $values) {
if ($values['num'] <= 50 && $values['max_comments'] <= 10) {
$this->generateContent($values);
}
else {
$this->generateBatchContent($values);
}
}
/**
* Method responsible for creating content when
* the number of elements is less than 50.
*/
private function generateContent($values) {
$values['node_types'] = array_filter($values['node_types']);
if (!empty($values['kill']) && $values['node_types']) {
$this->contentKill($values);
}
if (!empty($values['node_types'])) {
// Generate nodes.
$this->develGenerateContentPreNode($values);
$start = time();
for ($i = 1; $i <= $values['num']; $i++) {
$this->develGenerateContentAddNode($values);
if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
$now = time();
drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000) * 60) / ($now - $start))), 'ok');
$start = $now;
}
}
}
$this->setMessage($this->formatPlural($values['num'], '1 node created.', 'Finished creating @count nodes'));
}
/**
* Method responsible for creating content when
* the number of elements is greater than 50.
*/
private function generateBatchContent($values) {
// Setup the batch operations and save the variables.
$operations[] = array('devel_generate_operation', array($this, 'batchContentPreNode', $values));
// Add the kill operation.
if ($values['kill']) {
$operations[] = array('devel_generate_operation', array($this, 'batchContentKill', $values));
}
// Add the operations to create the nodes.
for ($num = 0; $num < $values['num']; $num ++) {
$operations[] = array('devel_generate_operation', array($this, 'batchContentAddNode', $values));
}
// Start the batch.
$batch = array(
'title' => $this->t('Generating Content'),
'operations' => $operations,
'finished' => 'devel_generate_batch_finished',
'file' => drupal_get_path('module', 'devel_generate') . '/devel_generate.batch.inc',
);
batch_set($batch);
}
public function batchContentPreNode($vars, &$context) {
$context['results'] = $vars;
$context['results']['num'] = 0;
$this->develGenerateContentPreNode($context['results']);
}
public function batchContentAddNode($vars, &$context) {
$this->develGenerateContentAddNode($context['results']);
$context['results']['num']++;
}
public function batchContentKill($vars, &$context) {
$this->contentKill($context['results']);
}
/**
* {@inheritdoc}
*/
public function validateDrushParams($args) {
$add_language = drush_get_option('languages');
if (!empty($add_language)) {
$add_language = explode(',', str_replace(' ', '', $add_language));
// Intersect with the enabled languages to make sure the language args
// passed are actually enabled.
$values['values']['add_language'] = array_intersect($add_language, array_keys($this->languageManager->getLanguages(LanguageInterface::STATE_ALL)));
}
$values['kill'] = drush_get_option('kill');
$values['title_length'] = 6;
$values['num'] = array_shift($args);
$values['max_comments'] = array_shift($args);
$all_types = array_keys(node_type_get_names());
$default_types = array_intersect(array('page', 'article'), $all_types);
$selected_types = _convert_csv_to_array(drush_get_option('types', $default_types));
if (empty($selected_types)) {
return drush_set_error('DEVEL_GENERATE_NO_CONTENT_TYPES', dt('No content types available'));
}
$values['node_types'] = array_combine($selected_types, $selected_types);
$node_types = array_filter($values['node_types']);
if (!empty($values['kill']) && empty($node_types)) {
return drush_set_error('DEVEL_GENERATE_INVALID_INPUT', dt('Please provide content type (--types) in which you want to delete the content.'));
}
return $values;
}
/**
* Deletes all nodes of given node types.
*
* @param array $values
* The input values from the settings form.
*/
protected function contentKill($values) {
$nids = $this->nodeStorage->getQuery()
->condition('type', $values['node_types'], 'IN')
->execute();
if (!empty($nids)) {
$nodes = $this->nodeStorage->loadMultiple($nids);
$this->nodeStorage->delete($nodes);
$this->setMessage($this->t('Deleted %count nodes.', array('%count' => count($nids))));
}
}
/**
* Return the same array passed as parameter
* but with an array of uids for the key 'users'.
*/
protected function develGenerateContentPreNode(&$results) {
// Get user id.
$users = $this->getUsers();
$users = array_merge($users, array('0'));
$results['users'] = $users;
}
/**
* Create one node. Used by both batch and non-batch code branches.
*/
protected function develGenerateContentAddNode(&$results) {
if (!isset($results['time_range'])) {
$results['time_range'] = 0;
}
$users = $results['users'];
$node_type = array_rand(array_filter($results['node_types']));
$uid = $users[array_rand($users)];
$node = $this->nodeStorage->create(array(
'nid' => NULL,
'type' => $node_type,
'title' => $this->getRandom()->sentences(mt_rand(1, $results['title_length']), TRUE),
'uid' => $uid,
'revision' => mt_rand(0, 1),
'status' => TRUE,
'promote' => mt_rand(0, 1),
'created' => REQUEST_TIME - mt_rand(0, $results['time_range']),
'langcode' => $this->getLangcode($results),
));
// A flag to let hook_node_insert() implementations know that this is a
// generated node.
$node->devel_generate = $results;
// Populate all fields with sample values.
$this->populateFields($node);
// See devel_generate_node_insert() for actions that happen before and after
// this save.
$node->save();
}
/**
* Determine language based on $results.
*/
protected function getLangcode($results) {
if (isset($results['add_language'])) {
$langcodes = $results['add_language'];
$langcode = $langcodes[array_rand($langcodes)];
}
else {
$langcode = $this->languageManager->getDefaultLanguage()->getId();
}
return $langcode;
}
/**
* Retrive 50 uids from the database.
*/
protected function getUsers() {
$users = array();
$result = db_query_range("SELECT uid FROM {users}", 0, 50);
foreach ($result as $record) {
$users[] = $record->uid;
}
return $users;
}
}
| eric-shell/badcamp-d8 | modules/devel/devel_generate/src/Plugin/DevelGenerate/ContentDevelGenerate.php | PHP | gpl-2.0 | 16,625 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for AD_ImpFormat
* @author Adempiere (generated)
* @version Release 3.8.0 - $Id$ */
public class X_AD_ImpFormat extends PO implements I_AD_ImpFormat, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20150223L;
/** Standard Constructor */
public X_AD_ImpFormat (Properties ctx, int AD_ImpFormat_ID, String trxName)
{
super (ctx, AD_ImpFormat_ID, trxName);
/** if (AD_ImpFormat_ID == 0)
{
setAD_ImpFormat_ID (0);
setAD_Table_ID (0);
setFormatType (null);
setName (null);
setProcessing (false);
} */
}
/** Load Constructor */
public X_AD_ImpFormat (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_ImpFormat[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Import Format.
@param AD_ImpFormat_ID Import Format */
public void setAD_ImpFormat_ID (int AD_ImpFormat_ID)
{
if (AD_ImpFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ImpFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ImpFormat_ID, Integer.valueOf(AD_ImpFormat_ID));
}
/** Get Import Format.
@return Import Format */
public int getAD_ImpFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ImpFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** FormatType AD_Reference_ID=209 */
public static final int FORMATTYPE_AD_Reference_ID=209;
/** Fixed Position = F */
public static final String FORMATTYPE_FixedPosition = "F";
/** Comma Separated = C */
public static final String FORMATTYPE_CommaSeparated = "C";
/** Tab Separated = T */
public static final String FORMATTYPE_TabSeparated = "T";
/** XML = X */
public static final String FORMATTYPE_XML = "X";
/** Custom Separator Char = U */
public static final String FORMATTYPE_CustomSeparatorChar = "U";
/** Set Format.
@param FormatType
Format of the data
*/
public void setFormatType (String FormatType)
{
set_Value (COLUMNNAME_FormatType, FormatType);
}
/** Get Format.
@return Format of the data
*/
public String getFormatType ()
{
return (String)get_Value(COLUMNNAME_FormatType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Separator Character.
@param SeparatorChar Separator Character */
public void setSeparatorChar (String SeparatorChar)
{
set_Value (COLUMNNAME_SeparatorChar, SeparatorChar);
}
/** Get Separator Character.
@return Separator Character */
public String getSeparatorChar ()
{
return (String)get_Value(COLUMNNAME_SeparatorChar);
}
} | TaymourReda/-https-github.com-adempiere-adempiere | base/src/org/compiere/model/X_AD_ImpFormat.java | Java | gpl-2.0 | 6,439 |
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2009 Eric Lafortune (eric@graphics.cornell.edu)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.obfuscate;
import proguard.classfile.*;
import proguard.classfile.util.*;
import proguard.classfile.visitor.*;
import java.io.PrintStream;
/**
* This ClassVisitor prints out the renamed classes and class members with
* their old names and new names.
*
* @see ClassRenamer
*
* @author Eric Lafortune
*/
public class MappingPrinter
extends SimplifiedVisitor
implements ClassVisitor,
MemberVisitor
{
private final PrintStream ps;
/**
* Creates a new MappingPrinter that prints to <code>System.out</code>.
*/
public MappingPrinter()
{
this(System.out);
}
/**
* Creates a new MappingPrinter that prints to the given stream.
* @param printStream the stream to which to print
*/
public MappingPrinter(PrintStream printStream)
{
this.ps = printStream;
}
// Implementations for ClassVisitor.
public void visitProgramClass(ProgramClass programClass)
{
String name = programClass.getName();
String newName = ClassObfuscator.newClassName(programClass);
ps.println(ClassUtil.externalClassName(name) +
" -> " +
ClassUtil.externalClassName(newName) +
":");
// Print out the class members.
programClass.fieldsAccept(this);
programClass.methodsAccept(this);
}
public void visitLibraryClass(LibraryClass libraryClass)
{
}
// Implementations for MemberVisitor.
public void visitProgramField(ProgramClass programClass, ProgramField programField)
{
String newName = MemberObfuscator.newMemberName(programField);
if (newName != null)
{
ps.println(" " +
//lineNumberRange(programClass, programField) +
ClassUtil.externalFullFieldDescription(
0,
programField.getName(programClass),
programField.getDescriptor(programClass)) +
" -> " +
newName);
}
}
public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
{
// Special cases: <clinit> and <init> are always kept unchanged.
// We can ignore them here.
String name = programMethod.getName(programClass);
if (name.equals(ClassConstants.INTERNAL_METHOD_NAME_CLINIT) ||
name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
{
return;
}
String newName = MemberObfuscator.newMemberName(programMethod);
if (newName != null)
{
ps.println(" " +
lineNumberRange(programClass, programMethod) +
ClassUtil.externalFullMethodDescription(
programClass.getName(),
0,
programMethod.getName(programClass),
programMethod.getDescriptor(programClass)) +
" -> " +
newName);
}
}
// Small utility methods.
/**
* Returns the line number range of the given class member, followed by a
* colon, or just an empty String if no range is available.
*/
private static String lineNumberRange(ProgramClass programClass, ProgramMember programMember)
{
String range = programMember.getLineNumberRange(programClass);
return range != null ?
(range + ":") :
"";
}
}
| shakalaca/ASUS_ZenFone_A450CG | external/proguard/src/proguard/obfuscate/MappingPrinter.java | Java | gpl-2.0 | 4,505 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "ags/engine/ac/dynobj/cc_gui.h"
#include "ags/engine/ac/dynobj/script_gui.h"
#include "ags/globals.h"
namespace AGS3 {
// return the type name of the object
const char *CCGUI::GetType() {
return "GUI";
}
// serialize the object into BUFFER (which is BUFSIZE bytes)
// return number of bytes used
int CCGUI::Serialize(const char *address, char *buffer, int bufsize) {
const ScriptGUI *shh = (const ScriptGUI *)address;
StartSerialize(buffer);
SerializeInt(shh->id);
return EndSerialize();
}
void CCGUI::Unserialize(int index, const char *serializedData, int dataSize) {
StartUnserialize(serializedData, dataSize);
int num = UnserializeInt();
ccRegisterUnserializedObject(index, &_G(scrGui)[num], this);
}
} // namespace AGS3
| vanfanel/scummvm | engines/ags/engine/ac/dynobj/cc_gui.cpp | C++ | gpl-2.0 | 1,695 |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "rel_job".
*
* @property integer $rj_id
* @property string $positiontype
* @property string $rj_name
* @property string $rj_dep
* @property string $work_type
* @property string $max_salary
* @property string $work_city
* @property string $work_year
* @property string $education
* @property string $work_tempt
* @property string $work_desc
* @property string $work_address
* @property integer $company_id
* @property integer $rj_status
* @property integer $addtime
* @property integer $m_id
* @property string $email
* @property integer $is_hot
* @property string $min_salary
* @property integer $is_ok
* @property string $lng
* @property string $lat
*/
class RelJob extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'rel_job';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['rj_name'], 'required'],
[['max_salary'], 'number'],
[['work_desc'], 'string'],
[['company_id', 'rj_status', 'addtime', 'm_id', 'is_hot', 'is_ok'], 'integer'],
[['positiontype', 'rj_dep', 'work_type'], 'string', 'max' => 30],
[['rj_name', 'lng', 'lat'], 'string', 'max' => 20],
[['work_city', 'work_year', 'education'], 'string', 'max' => 10],
[['work_tempt'], 'string', 'max' => 25],
[['work_address'], 'string', 'max' => 255],
[['email'], 'string', 'max' => 50],
[['min_salary'], 'string', 'max' => 220]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'rj_id' => 'Rj ID',
'positiontype' => 'Positiontype',
'rj_name' => 'Rj Name',
'rj_dep' => 'Rj Dep',
'work_type' => 'Work Type',
'max_salary' => 'Max Salary',
'work_city' => 'Work City',
'work_year' => 'Work Year',
'education' => 'Education',
'work_tempt' => 'Work Tempt',
'work_desc' => 'Work Desc',
'work_address' => 'Work Address',
'company_id' => 'Company ID',
'rj_status' => 'Rj Status',
'addtime' => 'Addtime',
'm_id' => 'M ID',
'email' => 'Email',
'is_hot' => 'Is Hot',
'min_salary' => 'Min Salary',
'is_ok' => 'Is Ok',
'lng' => 'Lng',
'lat' => 'Lat',
];
}
}
| zyweb/group5 | models/RelJob.php | PHP | gpl-2.0 | 2,597 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
/**
* Serializing an object containing a byte stream.
*/
abstract public class AbstractStreamSerializer extends AbstractSerializer
{
/**
* Writes the object to the output stream.
*/
@Override
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (out.addRef(obj)) {
return;
}
int ref = out.writeObjectBegin(getClassName(obj));
if (ref < -1) {
out.writeString("value");
InputStream is = null;
try {
is = getInputStream(obj);
} catch (Exception e) {
log.log(Level.WARNING, e.toString(), e);
}
if (is != null) {
try {
out.writeByteStream(is);
} finally {
is.close();
}
} else {
out.writeNull();
}
out.writeMapEnd();
}
else {
if (ref == -1) {
out.writeClassFieldLength(1);
out.writeString("value");
out.writeObjectBegin(getClassName(obj));
}
InputStream is = null;
try {
is = getInputStream(obj);
} catch (Exception e) {
log.log(Level.WARNING, e.toString(), e);
}
try {
if (is != null)
out.writeByteStream(is);
else
out.writeNull();
} finally {
if (is != null)
is.close();
}
}
}
protected String getClassName(Object obj)
{
return obj.getClass().getName();
}
abstract protected InputStream getInputStream(Object obj)
throws IOException;
}
| mdaniel/svn-caucho-com-resin | modules/hessian/src/com/caucho/hessian/io/AbstractStreamSerializer.java | Java | gpl-2.0 | 3,888 |
<?php defined( 'ABSPATH' ) or exit() ?>
<div class="wrap eventrocket cleanup">
<h2> <?php _e( 'Event Data Cleanup', 'eventrocket' ) ?> </h2>
<?php if ( ! $in_progress ): ?>
<p> <?php
_e( 'There may be occasions where you want to remove all traces of The Events Calendar and associated '
. 'plugins from the database, either because you no longer need it or because you want to start afresh. '
. 'This tool can help with that. <strong> Use with caution! </strong> ', 'eventrocket' );
?> </p>
<?php elseif ( $in_progress && 0 < max( $current_data ) ): ?>
<div class="updated">
<p> <?php _e( '<strong> Still working… </strong> please be patient while the remaining data is '
. 'removed.', 'eventrocket' ); ?>
<img src="<?php echo esc_url( admin_url( 'images/spinner.gif' ) ) ?>" />
</p>
<input type="hidden" name="keep_working" id="keep_working" value="<?php echo esc_attr( $action_url ) ?>" />
</div>
<?php elseif ( $in_progress && 0 === max( $current_data ) ): ?>
<div class="updated"> <p>
<?php _e( '<strong> Cleanup complete! </strong> Now get back to work. ', 'eventrocket' ); ?>
</p> </div>
<?php endif ?>
<?php if ( 0 === max( $current_data ) ): ?>
<p> <strong> <?php _e( 'No event related data found! You’re all set!', 'eventrocket') ?> </strong></p>
<?php else: ?>
<h4> <?php _e( 'Event data found within your database:', 'eventrocket' ) ?> </h4>
<dl>
<dt> <?php _e( 'Event objects', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['events'] ) ?> </dd>
<dt> <?php _e( 'Venue objects', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['venues'] ) ?> </dd>
<dt> <?php _e( 'Organizer objects', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['organizers'] ) ?> </dd>
<dt> <?php _e( 'User capabilities', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['capabilities'] ) ?> </dd>
<dt> <?php _e( 'Other settings', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['options'] ) ?> </dd>
</dl>
<?php if ( ! $in_progress ): ?>
<h4> <?php _e( 'Run the cleanup tool', 'eventrocket' ) ?> </h4>
<div class="hide-if-no-js">
<p id="cleanup_safety">
<input type="checkbox" name="user_confirms" id="user_confirms" value="1" />
<label for="user_confirms"> <?php _e( 'I understand the risks involved and acknowledge that running '
. 'this cleanup tool without first making a backup may be deemed an act of stupidity.',
'eventrocket' ) ?> </label>
</p>
</div>
<p id="do_cleanup"> <a href="<?php echo esc_attr( $action_url ) ?>" class="button-primary"><?php _e( 'Do cleanup', 'eventrocket' ) ?></a> </p>
<?php endif ?>
<?php endif ?>
</div> | evamichalcak/doartystuff | wp-content/plugins/event-rocket/templates/cleanup-screen.php | PHP | gpl-2.0 | 2,765 |
// license:BSD-3-Clause
// copyright-holders:Curt Coder
/*
TODO:
- tape input/output
- PL-80 plotter
- serial printer
- thermal printer
*/
#include "includes/comx35.h"
#include "formats/imageutl.h"
#include "softlist.h"
/***************************************************************************
PARAMETERS
***************************************************************************/
#define LOG 0
enum
{
COMX_TYPE_BINARY = 1,
COMX_TYPE_BASIC,
COMX_TYPE_BASIC_FM,
COMX_TYPE_RESERVED,
COMX_TYPE_DATA
};
/***************************************************************************
IMPLEMENTATION
***************************************************************************/
/*-------------------------------------------------
image_fread_memory - read image to memory
-------------------------------------------------*/
void comx35_state::image_fread_memory(device_image_interface &image, UINT16 addr, UINT32 count)
{
UINT8 *ram = m_ram->pointer() + (addr - 0x4000);
image.fread(ram, count);
}
/*-------------------------------------------------
QUICKLOAD_LOAD_MEMBER( comx35_state, comx35_comx )
-------------------------------------------------*/
QUICKLOAD_LOAD_MEMBER( comx35_state, comx35_comx )
{
address_space &program = m_maincpu->space(AS_PROGRAM);
UINT8 header[16] = {0};
int size = image.length();
if (size > m_ram->size())
{
return IMAGE_INIT_FAIL;
}
image.fread( header, 5);
if (header[1] != 'C' || header[2] != 'O' || header[3] != 'M' || header[4] != 'X' )
{
return IMAGE_INIT_FAIL;
}
switch (header[0])
{
case COMX_TYPE_BINARY:
/*
Type 1: pure machine code (i.e. no basic)
Byte 0 to 4: 1 - 'COMX'
Byte 5 and 6: Start address (1802 way; see above)
Byte 6 and 7: End address
Byte 9 and 10: Execution address
Byte 11 to Eof, should be stored in ram from start to end; execution address
'xxxx' for the CALL (@xxxx) basic statement to actually run the code.
*/
{
UINT16 start_address, end_address, run_address;
image.fread(header, 6);
start_address = pick_integer_be(header, 0, 2);
end_address = pick_integer_be(header, 2, 2);
run_address = pick_integer_be(header, 4, 2);
image_fread_memory(image, start_address, end_address - start_address);
popmessage("Type CALL (@%04x) to start program", run_address);
}
break;
case COMX_TYPE_BASIC:
/*
Type 2: Regular basic code or machine code followed by basic
Byte 0 to 4: 2 - 'COMX'
Byte 5 and 6: DEFUS value, to be stored on 0x4281 and 0x4282
Byte 7 and 8: EOP value, to be stored on 0x4283 and 0x4284
Byte 9 and 10: End array, start string to be stored on 0x4292 and 0x4293
Byte 11 and 12: start array to be stored on 0x4294 and 0x4295
Byte 13 and 14: EOD and end string to be stored on 0x4299 and 0x429A
Byte 15 to Eof to be stored on 0x4400 and onwards
Byte 0x4281-0x429A (or at least the ones above) should be set otherwise
BASIC won't 'see' the code.
*/
image_fread_memory(image, 0x4281, 4);
image_fread_memory(image, 0x4292, 4);
image_fread_memory(image, 0x4299, 2);
image_fread_memory(image, 0x4400, size);
break;
case COMX_TYPE_BASIC_FM:
/*
Type 3: F&M basic load
Not the most important! But we designed our own basic extension, you can
find it in the F&M basic folder as F&M Basic.comx. When you run this all
basic code should start at address 0x6700 instead of 0x4400 as from
0x4400-0x6700 the F&M basic stuff is loaded. So format is identical to Type
2 except Byte 15 to Eof should be stored on 0x6700 instead. .comx files of
this format can also be found in the same folder as the F&M basic.comx file.
*/
image_fread_memory(image, 0x4281, 4);
image_fread_memory(image, 0x4292, 4);
image_fread_memory(image, 0x4299, 2);
image_fread_memory(image, 0x6700, size);
break;
case COMX_TYPE_RESERVED:
/*
Type 4: Incorrect DATA format, I suggest to forget this one as it won't work
in most cases. Instead I left this one reserved and designed Type 5 instead.
*/
break;
case COMX_TYPE_DATA:
/*
Type 5: Data load
Byte 0 to 4: 5 - 'COMX'
Byte 5 and 6: Array length
Byte 7 to Eof: Basic 'data'
To load this first get the 'start array' from the running COMX, i.e. address
0x4295/0x4296. Calculate the EOD as 'start array' + length of the data (i.e.
file length - 7). Store the EOD back on 0x4299 and ox429A. Calculate the
'Start String' as 'start array' + 'Array length' (Byte 5 and 6). Store the
'Start String' on 0x4292/0x4293. Load byte 7 and onwards starting from the
'start array' value fetched from 0x4295/0x4296.
*/
{
UINT16 start_array, end_array, start_string, array_length;
image.fread(header, 2);
array_length = pick_integer_be(header, 0, 2);
start_array = (program.read_byte(0x4295) << 8) | program.read_byte(0x4296);
end_array = start_array + (size - 7);
program.write_byte(0x4299, end_array >> 8);
program.write_byte(0x429a, end_array & 0xff);
start_string = start_array + array_length;
program.write_byte(0x4292, start_string >> 8);
program.write_byte(0x4293, start_string & 0xff);
image_fread_memory(image, start_array, size);
}
break;
}
return IMAGE_INIT_PASS;
}
//**************************************************************************
// MEMORY ACCESS
//**************************************************************************
//-------------------------------------------------
// mem_r - memory read
//-------------------------------------------------
READ8_MEMBER( comx35_state::mem_r )
{
int extrom = 1;
UINT8 data = m_exp->mrd_r(space, offset, &extrom);
if (offset < 0x4000)
{
if (extrom) data = m_rom->base()[offset & 0x3fff];
}
else if (offset >= 0x4000 && offset < 0xc000)
{
data = m_ram->pointer()[offset - 0x4000];
}
else if (offset >= 0xf400 && offset < 0xf800)
{
data = m_vis->char_ram_r(space, offset & 0x3ff);
}
return data;
}
//-------------------------------------------------
// mem_w - memory write
//-------------------------------------------------
WRITE8_MEMBER( comx35_state::mem_w )
{
m_exp->mwr_w(space, offset, data);
if (offset >= 0x4000 && offset < 0xc000)
{
m_ram->pointer()[offset - 0x4000] = data;
}
else if (offset >= 0xf400 && offset < 0xf800)
{
m_vis->char_ram_w(space, offset & 0x3ff, data);
}
else if (offset >= 0xf800)
{
m_vis->page_ram_w(space, offset & 0x3ff, data);
}
}
//-------------------------------------------------
// io_r - I/O read
//-------------------------------------------------
READ8_MEMBER( comx35_state::io_r )
{
UINT8 data = m_exp->io_r(space, offset);
if (offset == 3)
{
data = m_kbe->read(space, 0);
}
return data;
}
//-------------------------------------------------
// io_w - I/O write
//-------------------------------------------------
WRITE8_MEMBER( comx35_state::io_w )
{
m_exp->io_w(space, offset, data);
if (offset >= 3)
{
cdp1869_w(space, offset, data);
}
}
//**************************************************************************
// ADDRESS MAPS
//**************************************************************************
//-------------------------------------------------
// ADDRESS_MAP( comx35_mem )
//-------------------------------------------------
static ADDRESS_MAP_START( comx35_mem, AS_PROGRAM, 8, comx35_state )
ADDRESS_MAP_UNMAP_HIGH
AM_RANGE(0x0000, 0xffff) AM_READWRITE(mem_r, mem_w)
ADDRESS_MAP_END
//-------------------------------------------------
// ADDRESS_MAP( comx35_io )
//-------------------------------------------------
static ADDRESS_MAP_START( comx35_io, AS_IO, 8, comx35_state )
ADDRESS_MAP_UNMAP_HIGH
AM_RANGE(0x00, 0x07) AM_READWRITE(io_r, io_w)
ADDRESS_MAP_END
//**************************************************************************
// INPUT PORTS
//**************************************************************************
//-------------------------------------------------
// INPUT_CHANGED_MEMBER( comx35_reset )
//-------------------------------------------------
INPUT_CHANGED_MEMBER( comx35_state::trigger_reset )
{
if (newval && BIT(m_d6->read(), 7))
{
machine_reset();
}
}
//-------------------------------------------------
// INPUT_PORTS( comx35 )
//-------------------------------------------------
static INPUT_PORTS_START( comx35 )
PORT_START("D1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("0 \xE2\x96\xA0") PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR('@')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('"')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('?')
PORT_START("D2")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('[')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(']')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR(':')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR(';')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_MINUS) PORT_CHAR('<') PORT_CHAR('(')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('=') PORT_CHAR('^')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('>') PORT_CHAR(')')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR('\\') PORT_CHAR('_')
PORT_START("D3")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_TILDE) PORT_CHAR('?')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_START("D4")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_START("D5")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_START("D6")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COLON) PORT_CHAR('+') PORT_CHAR('{')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR('-') PORT_CHAR('|')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR('*') PORT_CHAR('}')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('~')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("SPACE") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_CHAR(8)
PORT_START("D7")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D8")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("CR") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("ESC") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_UP) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_RIGHT) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_LEFT) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_DOWN) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("DEL") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D9")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D10")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D11")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("MODIFIERS")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("SHIFT") PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1) PORT_WRITE_LINE_DEVICE_MEMBER(CDP1871_TAG, cdp1871_device, shift_w)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("CNTL") PORT_CODE(KEYCODE_LCONTROL) PORT_CODE(KEYCODE_RCONTROL) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL)) PORT_CHAR(UCHAR_MAMEKEY(RCONTROL)) PORT_WRITE_LINE_DEVICE_MEMBER(CDP1871_TAG, cdp1871_device, control_w)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("RESET")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("RT") PORT_CODE(KEYCODE_F10) PORT_CHAR(UCHAR_MAMEKEY(F10)) PORT_CHANGED_MEMBER(DEVICE_SELF, comx35_state, trigger_reset, 0)
INPUT_PORTS_END
//**************************************************************************
// DEVICE CONFIGURATION
//**************************************************************************
//-------------------------------------------------
// COSMAC_INTERFACE( cosmac_intf )
//-------------------------------------------------
void comx35_state::check_interrupt()
{
m_maincpu->set_input_line(COSMAC_INPUT_LINE_INT, m_cr1 || m_int);
}
READ_LINE_MEMBER( comx35_state::clear_r )
{
return m_clear;
}
READ_LINE_MEMBER( comx35_state::ef2_r )
{
if (m_iden)
{
// interrupts disabled: PAL/NTSC
return m_vis->pal_ntsc_r();
}
else
{
// interrupts enabled: keyboard repeat
return m_kbe->rpt_r();
}
}
READ_LINE_MEMBER( comx35_state::ef4_r )
{
return m_exp->ef4_r(); // | (m_cassette->input() > 0.0f);
}
WRITE_LINE_MEMBER( comx35_state::q_w )
{
m_q = state;
if (m_iden && state)
{
// enable interrupts
m_iden = 0;
}
// cassette output
m_cassette->output(state ? +1.0 : -1.0);
// expansion bus
m_exp->q_w(state);
}
WRITE8_MEMBER( comx35_state::sc_w )
{
switch (data)
{
case COSMAC_STATE_CODE_S0_FETCH:
// not connected
break;
case COSMAC_STATE_CODE_S1_EXECUTE:
// every other S1 triggers a DMAOUT request
if (m_dma)
{
m_dma = 0;
if (!m_iden)
{
m_maincpu->set_input_line(COSMAC_INPUT_LINE_DMAOUT, ASSERT_LINE);
}
}
else
{
m_dma = 1;
}
break;
case COSMAC_STATE_CODE_S2_DMA:
// DMA acknowledge clears the DMAOUT request
m_maincpu->set_input_line(COSMAC_INPUT_LINE_DMAOUT, CLEAR_LINE);
break;
case COSMAC_STATE_CODE_S3_INTERRUPT:
// interrupt acknowledge clears the INT request
m_maincpu->set_input_line(COSMAC_INPUT_LINE_INT, CLEAR_LINE);
break;
}
}
//-------------------------------------------------
// COMX_EXPANSION_INTERFACE( expansion_intf )
//-------------------------------------------------
WRITE_LINE_MEMBER( comx35_state::irq_w )
{
m_int = state;
check_interrupt();
}
//**************************************************************************
// MACHINE INITIALIZATION
//**************************************************************************
//-------------------------------------------------
// device_timer - handler timer events
//-------------------------------------------------
void comx35_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
switch (id)
{
case TIMER_ID_RESET:
m_clear = 1;
break;
}
}
//-------------------------------------------------
// MACHINE_START( comx35 )
//-------------------------------------------------
void comx35_state::machine_start()
{
// clear the RAM since DOS card will go crazy if RAM is not all zeroes
UINT8 *ram = m_ram->pointer();
memset(ram, 0, m_ram->size());
// register for state saving
save_item(NAME(m_clear));
save_item(NAME(m_q));
save_item(NAME(m_iden));
save_item(NAME(m_dma));
save_item(NAME(m_int));
save_item(NAME(m_prd));
save_item(NAME(m_cr1));
}
void comx35_state::machine_reset()
{
m_exp->reset();
int t = RES_K(27) * CAP_U(1) * 1000; // t = R1 * C1
m_clear = 0;
m_iden = 1;
m_cr1 = 1;
m_int = CLEAR_LINE;
m_prd = CLEAR_LINE;
timer_set(attotime::from_msec(t), TIMER_ID_RESET);
}
//**************************************************************************
// MACHINE DRIVERS
//**************************************************************************
//-------------------------------------------------
// MACHINE_CONFIG( pal )
//-------------------------------------------------
static MACHINE_CONFIG_START( pal, comx35_state )
// basic system hardware
MCFG_CPU_ADD(CDP1802_TAG, CDP1802, CDP1869_CPU_CLK_PAL)
MCFG_CPU_PROGRAM_MAP(comx35_mem)
MCFG_CPU_IO_MAP(comx35_io)
MCFG_COSMAC_WAIT_CALLBACK(VCC)
MCFG_COSMAC_CLEAR_CALLBACK(READLINE(comx35_state, clear_r))
MCFG_COSMAC_EF2_CALLBACK(READLINE(comx35_state, ef2_r))
MCFG_COSMAC_EF4_CALLBACK(READLINE(comx35_state, ef4_r))
MCFG_COSMAC_Q_CALLBACK(WRITELINE(comx35_state, q_w))
MCFG_COSMAC_SC_CALLBACK(WRITE8(comx35_state, sc_w))
// sound and video hardware
MCFG_FRAGMENT_ADD(comx35_pal_video)
// peripheral hardware
MCFG_DEVICE_ADD(CDP1871_TAG, CDP1871, CDP1869_CPU_CLK_PAL/8)
MCFG_CDP1871_D1_CALLBACK(IOPORT("D1"))
MCFG_CDP1871_D2_CALLBACK(IOPORT("D2"))
MCFG_CDP1871_D3_CALLBACK(IOPORT("D3"))
MCFG_CDP1871_D4_CALLBACK(IOPORT("D4"))
MCFG_CDP1871_D5_CALLBACK(IOPORT("D5"))
MCFG_CDP1871_D6_CALLBACK(IOPORT("D6"))
MCFG_CDP1871_D7_CALLBACK(IOPORT("D7"))
MCFG_CDP1871_D8_CALLBACK(IOPORT("D8"))
MCFG_CDP1871_D9_CALLBACK(IOPORT("D9"))
MCFG_CDP1871_D10_CALLBACK(IOPORT("D10"))
MCFG_CDP1871_D11_CALLBACK(IOPORT("D11"))
MCFG_CDP1871_DA_CALLBACK(INPUTLINE(CDP1802_TAG, COSMAC_INPUT_LINE_EF3))
MCFG_QUICKLOAD_ADD("quickload", comx35_state, comx35_comx, "comx", 0)
MCFG_CASSETTE_ADD("cassette")
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_MOTOR_ENABLED | CASSETTE_SPEAKER_ENABLED)
// expansion bus
MCFG_COMX_EXPANSION_SLOT_ADD(EXPANSION_TAG, comx_expansion_cards, "eb")
MCFG_COMX_EXPANSION_SLOT_IRQ_CALLBACK(WRITELINE(comx35_state, irq_w))
// internal ram
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("32K")
// software lists
MCFG_SOFTWARE_LIST_ADD("flop_list", "comx35_flop")
MACHINE_CONFIG_END
//-------------------------------------------------
// MACHINE_CONFIG( ntsc )
//-------------------------------------------------
static MACHINE_CONFIG_START( ntsc, comx35_state )
// basic system hardware
MCFG_CPU_ADD(CDP1802_TAG, CDP1802, CDP1869_CPU_CLK_NTSC)
MCFG_CPU_PROGRAM_MAP(comx35_mem)
MCFG_CPU_IO_MAP(comx35_io)
MCFG_COSMAC_WAIT_CALLBACK(VCC)
MCFG_COSMAC_CLEAR_CALLBACK(READLINE(comx35_state, clear_r))
MCFG_COSMAC_EF2_CALLBACK(READLINE(comx35_state, ef2_r))
MCFG_COSMAC_EF4_CALLBACK(READLINE(comx35_state, ef4_r))
MCFG_COSMAC_Q_CALLBACK(WRITELINE(comx35_state, q_w))
MCFG_COSMAC_SC_CALLBACK(WRITE8(comx35_state, sc_w))
// sound and video hardware
MCFG_FRAGMENT_ADD(comx35_ntsc_video)
// peripheral hardware
MCFG_DEVICE_ADD(CDP1871_TAG, CDP1871, CDP1869_CPU_CLK_PAL/8)
MCFG_CDP1871_D1_CALLBACK(IOPORT("D1"))
MCFG_CDP1871_D2_CALLBACK(IOPORT("D2"))
MCFG_CDP1871_D3_CALLBACK(IOPORT("D3"))
MCFG_CDP1871_D4_CALLBACK(IOPORT("D4"))
MCFG_CDP1871_D5_CALLBACK(IOPORT("D5"))
MCFG_CDP1871_D6_CALLBACK(IOPORT("D6"))
MCFG_CDP1871_D7_CALLBACK(IOPORT("D7"))
MCFG_CDP1871_D8_CALLBACK(IOPORT("D8"))
MCFG_CDP1871_D9_CALLBACK(IOPORT("D9"))
MCFG_CDP1871_D10_CALLBACK(IOPORT("D10"))
MCFG_CDP1871_D11_CALLBACK(IOPORT("D11"))
MCFG_CDP1871_DA_CALLBACK(INPUTLINE(CDP1802_TAG, COSMAC_INPUT_LINE_EF3))
MCFG_QUICKLOAD_ADD("quickload", comx35_state, comx35_comx, "comx", 0)
MCFG_CASSETTE_ADD("cassette")
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_MOTOR_ENABLED | CASSETTE_SPEAKER_ENABLED)
// expansion bus
MCFG_COMX_EXPANSION_SLOT_ADD(EXPANSION_TAG, comx_expansion_cards, "eb")
MCFG_COMX_EXPANSION_SLOT_IRQ_CALLBACK(WRITELINE(comx35_state, irq_w))
// internal ram
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("32K")
// software lists
MCFG_SOFTWARE_LIST_ADD("flop_list", "comx35_flop")
MACHINE_CONFIG_END
//**************************************************************************
// ROMS
//**************************************************************************
//-------------------------------------------------
// ROM( comx35p )
//-------------------------------------------------
ROM_START( comx35p )
ROM_REGION( 0x4000, CDP1802_TAG, 0 )
ROM_DEFAULT_BIOS( "basic100" )
ROM_SYSTEM_BIOS( 0, "basic100", "COMX BASIC V1.00" )
ROMX_LOAD( "comx_10.u21", 0x0000, 0x4000, CRC(68d0db2d) SHA1(062328361629019ceed9375afac18e2b7849ce47), ROM_BIOS(1) )
ROM_SYSTEM_BIOS( 1, "basic101", "COMX BASIC V1.01" )
ROMX_LOAD( "comx_11.u21", 0x0000, 0x4000, CRC(609d89cd) SHA1(799646810510d8236fbfafaff7a73d5170990f16), ROM_BIOS(2) )
ROM_END
//-------------------------------------------------
// ROM( comx35n )
//-------------------------------------------------
#define rom_comx35n rom_comx35p
//**************************************************************************
// SYSTEM DRIVERS
//**************************************************************************
// YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME FLAGS
COMP( 1983, comx35p, 0, 0, pal, comx35, driver_device, 0, "Comx World Operations Ltd", "COMX 35 (PAL)", MACHINE_IMPERFECT_SOUND )
COMP( 1983, comx35n, comx35p,0, ntsc, comx35, driver_device, 0, "Comx World Operations Ltd", "COMX 35 (NTSC)", MACHINE_IMPERFECT_SOUND )
| h0tw1r3/mame | src/mame/drivers/comx35.cpp | C++ | gpl-2.0 | 23,542 |
var app = angular.module('site', ['ui.bootstrap', 'ngAria']);
app.factory('Backend', ['$http',
function($http) {
var get = function(url) {
return function() {
return $http.get(url).then(function(resp) {
return resp.data;
});
}
};
return {
featured: get('data/featured.json'),
orgs: get('data/organization.json')
}
}
])
.controller('MainCtrl', ['Backend', '$scope', 'filterFilter',
function(Backend, $scope, filterFilter) {
var self = this;
Backend.orgs().then(function(data) {
self.orgs = data;
});
Backend.featured().then(function(data) {
self.featured = data;
$.ajax({
url: 'https://popularrepostg.blob.core.windows.net/popularrepos/projects.json',
dataType: 'jsonp',
jsonpCallback: 'JSON_CALLBACK',
success: function(data) {
var projects = data[0].AllProjects;
$scope.currentPage = 1; //current page
$scope.maxSize = 5; //pagination max size
$scope.entryLimit = 36; //max rows for data table
/* init pagination with $scope.list */
$scope.noOfRepos = projects.length;
$scope.noOfPages = Math.ceil($scope.noOfRepos / $scope.entryLimit);
$scope.resultsSectionTitle = 'All Repos';
$scope.$watch('searchText', function(term) {
// Create $scope.filtered and then calculate $scope.noOfPages, no racing!
$scope.filtered = filterFilter(projects, term);
$scope.noOfRepos = $scope.filtered.length;
$scope.noOfPages = Math.ceil($scope.noOfRepos / $scope.entryLimit);
$scope.resultsSectionTitle = (!term) ? 'All Repos' : (($scope.noOfRepos == 0) ? 'Search results' : ($scope.noOfRepos + ' repositories found'));
});
var featuredProjects = new Array();
self.featured.forEach(function (name) {
for (var i = 0; i < projects.length; i++) {
var project = projects[i];
if (project.Name == name) {
featuredProjects.push(project);
return;
}
}
});
self.projects = projects;
self.featuredProjects = featuredProjects;
$scope.$apply();
}
});
$.ajax({
url: 'https://popularrepostg.blob.core.windows.net/popularrepos/projectssummary.json',
dataType: 'jsonp',
jsonpCallback: 'JSON_CALLBACK',
success: function (stats) {
if (stats != null) {
$scope.overAllStats = stats[0];
}
}
})
});
}
])
.filter('startFrom', function() {
return function(input, start) {
if (input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
| Gelvazio/ORGANIZACOES | microsoft.github.io/microsoft.github.io-master/js/main.js | JavaScript | gpl-2.0 | 3,518 |
# Copyright (c) 2016--2017 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
import sys
import cStringIO
import json
import zipfile
import os
from M2Crypto import X509
from spacewalk.satellite_tools.syncLib import log2
from spacewalk.server.rhnServer.satellite_cert import SatelliteCert
import constants
class Manifest(object):
"""Class containing relevant data from RHSM manifest."""
SIGNATURE_NAME = "signature"
INNER_ZIP_NAME = "consumer_export.zip"
ENTITLEMENTS_PATH = "export/entitlements"
CERTIFICATE_PATH = "export/extensions"
PRODUCTS_PATH = "export/products"
CONSUMER_INFO = "export/consumer.json"
META_INFO = "export/meta.json"
UPSTREAM_CONSUMER_PATH = "export/upstream_consumer"
def __init__(self, zip_path):
self.all_entitlements = []
self.manifest_repos = {}
self.sat5_certificate = None
self.satellite_version = None
self.consumer_credentials = None
self.uuid = None
self.name = None
self.ownerid = None
self.api_url = None
self.web_url = None
self.created = None
# Signature and signed data
self.signature = None
self.data = None
# Open manifest from path
top_zip = None
inner_zip = None
inner_file = None
# normalize path
zip_path = os.path.abspath(os.path.expanduser(zip_path))
try:
top_zip = zipfile.ZipFile(zip_path, 'r')
# Fetch inner zip file into memory
try:
# inner_file = top_zip.open(zip_path.split('.zip')[0] + '/' + self.INNER_ZIP_NAME)
inner_file = top_zip.open(self.INNER_ZIP_NAME)
self.data = inner_file.read()
inner_file_data = cStringIO.StringIO(self.data)
signature_file = top_zip.open(self.SIGNATURE_NAME)
self.signature = signature_file.read()
# Open the inner zip file
try:
inner_zip = zipfile.ZipFile(inner_file_data)
self._extract_consumer_info(inner_zip)
self._load_entitlements(inner_zip)
self._extract_certificate(inner_zip)
self._extract_meta_info(inner_zip)
self._extract_consumer_credentials(inner_zip)
finally:
if inner_zip is not None:
inner_zip.close()
finally:
if inner_file is not None:
inner_file.close()
finally:
if top_zip is not None:
top_zip.close()
def _extract_certificate(self, zip_file):
files = zip_file.namelist()
certificates_names = []
for f in files:
if f.startswith(self.CERTIFICATE_PATH) and f.endswith(".xml"):
certificates_names.append(f)
if len(certificates_names) >= 1:
# take only first file
cert_file = zip_file.open(certificates_names[0]) # take only first file
self.sat5_certificate = cert_file.read().strip()
cert_file.close()
# Save version too
sat5_cert = SatelliteCert()
sat5_cert.load(self.sat5_certificate)
self.satellite_version = getattr(sat5_cert, 'satellite-version')
else:
raise MissingSatelliteCertificateError("Satellite Certificate was not found in manifest.")
def _fill_product_repositories(self, zip_file, product):
product_file = zip_file.open(self.PRODUCTS_PATH + '/' + str(product.get_id()) + '.json')
product_data = json.load(product_file)
product_file.close()
try:
for content in product_data['productContent']:
content = content['content']
product.add_repository(content['label'], content['contentUrl'])
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in product '%s'" % product.get_id(), stream=sys.stderr)
raise
def _load_entitlements(self, zip_file):
files = zip_file.namelist()
entitlements_files = []
for f in files:
if f.startswith(self.ENTITLEMENTS_PATH) and f.endswith(".json"):
entitlements_files.append(f)
if len(entitlements_files) >= 1:
self.all_entitlements = []
for entitlement_file in entitlements_files:
entitlements = zip_file.open(entitlement_file)
# try block in try block - this is hack for python 2.4 compatibility
# to support finally
try:
try:
data = json.load(entitlements)
# Extract credentials
certs = data['certificates']
if len(certs) != 1:
raise IncorrectEntitlementsFileFormatError(
"Single certificate in entitlements file '%s' is expected, found: %d"
% (entitlement_file, len(certs)))
cert = certs[0]
credentials = Credentials(data['id'], cert['cert'], cert['key'])
# Extract product IDs
products = []
provided_products = data['pool']['providedProducts'] or []
derived_provided_products = data['pool']['derivedProvidedProducts'] or []
product_ids = [provided_product['productId'] for provided_product
in provided_products + derived_provided_products]
for product_id in set(product_ids):
product = Product(product_id)
self._fill_product_repositories(zip_file, product)
products.append(product)
# Skip entitlements not providing any products
if products:
entitlement = Entitlement(products, credentials)
self.all_entitlements.append(entitlement)
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % entitlement_file,
stream=sys.stderr)
raise
finally:
entitlements.close()
else:
refer_url = "%s%s" % (self.web_url, self.uuid)
if not refer_url.startswith("http"):
refer_url = "https://" + refer_url
raise IncorrectEntitlementsFileFormatError(
"No subscriptions were found in manifest.\n\nPlease refer to %s for setting up subscriptions."
% refer_url)
def _extract_consumer_info(self, zip_file):
files = zip_file.namelist()
found = False
for f in files:
if f == self.CONSUMER_INFO:
found = True
break
if found:
consumer_info = zip_file.open(self.CONSUMER_INFO)
try:
try:
data = json.load(consumer_info)
self.uuid = data['uuid']
self.name = data['name']
self.ownerid = data['owner']['key']
self.api_url = data['urlApi']
self.web_url = data['urlWeb']
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % self.CONSUMER_INFO,
stream=sys.stderr)
raise
finally:
consumer_info.close()
else:
raise MissingConsumerInfoError()
def _extract_meta_info(self, zip_file):
files = zip_file.namelist()
found = False
for f in files:
if f == self.META_INFO:
found = True
break
if found:
meta_info = zip_file.open(self.META_INFO)
try:
try:
data = json.load(meta_info)
self.created = data['created']
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % self.META_INFO, stream=sys.stderr)
raise
finally:
meta_info.close()
else:
raise MissingMetaInfoError()
def _extract_consumer_credentials(self, zip_file):
files = zip_file.namelist()
consumer_credentials = []
for f in files:
if f.startswith(self.UPSTREAM_CONSUMER_PATH) and f.endswith(".json"):
consumer_credentials.append(f)
if len(consumer_credentials) == 1:
upstream_consumer = zip_file.open(consumer_credentials[0])
try:
try:
data = json.load(upstream_consumer)
self.consumer_credentials = Credentials(data['id'], data['cert'], data['key'])
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % consumer_credentials[0],
stream=sys.stderr)
raise
finally:
upstream_consumer.close()
else:
raise IncorrectCredentialsError(
"ERROR: Single upstream consumer certificate expected, found %d." % len(consumer_credentials))
def get_all_entitlements(self):
return self.all_entitlements
def get_satellite_certificate(self):
return self.sat5_certificate
def get_satellite_version(self):
return self.satellite_version
def get_consumer_credentials(self):
return self.consumer_credentials
def get_name(self):
return self.name
def get_uuid(self):
return self.uuid
def get_ownerid(self):
return self.ownerid
def get_api_url(self):
return self.api_url
def get_created(self):
return self.created
def check_signature(self):
if self.signature and self.data:
certs = os.listdir(constants.CANDLEPIN_CA_CERT_DIR)
# At least one certificate has to match
for cert_name in certs:
cert_file = None
try:
try:
cert_file = open(constants.CANDLEPIN_CA_CERT_DIR + '/' + cert_name, 'r')
cert = X509.load_cert_string(cert_file.read())
except (IOError, X509.X509Error):
continue
finally:
if cert_file is not None:
cert_file.close()
pubkey = cert.get_pubkey()
pubkey.reset_context(md='sha256')
pubkey.verify_init()
pubkey.verify_update(self.data)
if pubkey.verify_final(self.signature):
return True
return False
class Entitlement(object):
def __init__(self, products, credentials):
if products and credentials:
self.products = products
self.credentials = credentials
else:
raise IncorrectEntitlementError()
def get_products(self):
return self.products
def get_credentials(self):
return self.credentials
class Credentials(object):
def __init__(self, identifier, cert, key):
if identifier:
self.id = identifier
else:
raise IncorrectCredentialsError(
"ERROR: ID of credentials has to be defined"
)
if cert and key:
self.cert = cert
self.key = key
else:
raise IncorrectCredentialsError(
"ERROR: Trying to create object with cert = %s and key = %s"
% (cert, key)
)
def get_id(self):
return self.id
def get_cert(self):
return self.cert
def get_key(self):
return self.key
class Product(object):
def __init__(self, identifier):
try:
self.id = int(identifier)
except ValueError:
raise IncorrectProductError(
"ERROR: Invalid product id: %s" % identifier
)
self.repositories = {}
def get_id(self):
return self.id
def get_repositories(self):
return self.repositories
def add_repository(self, label, url):
self.repositories[label] = url
class IncorrectProductError(Exception):
pass
class IncorrectEntitlementError(Exception):
pass
class IncorrectCredentialsError(Exception):
pass
class IncorrectEntitlementsFileFormatError(Exception):
pass
class MissingSatelliteCertificateError(Exception):
pass
class ManifestValidationError(Exception):
pass
class MissingConsumerInfoError(Exception):
pass
class MissingMetaInfoError(Exception):
pass
| ogajduse/spacewalk | backend/cdn_tools/manifest.py | Python | gpl-2.0 | 13,620 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Service\V1;
use Magento\TestFramework\TestCase\WebapiAbstract;
class OrderHoldTest extends WebapiAbstract
{
const SERVICE_VERSION = 'V1';
const SERVICE_NAME = 'salesOrderManagementV1';
/**
* @magentoApiDataFixture Magento/Sales/_files/order.php
*/
public function testOrderHold()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$order = $objectManager->get('Magento\Sales\Model\Order')->loadByIncrementId('100000001');
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/orders/' . $order->getId() . '/hold',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'hold',
],
];
$requestData = ['id' => $order->getId()];
$result = $this->_webApiCall($serviceInfo, $requestData);
$this->assertTrue($result);
}
}
| FPLD/project0 | vendor/magento/magento2-base/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderHoldTest.php | PHP | gpl-2.0 | 1,240 |
/*
* Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Provides user interface objects built according to the Basic look and feel.
* The Basic look and feel provides default behavior used by many look and feel
* packages. It contains components, layout managers, events, event listeners,
* and adapters. You can subclass the classes in this package to create your own
* customized look and feel.
* <p>
* These classes are designed to be used while the corresponding
* {@code LookAndFeel} class has been installed
* (<code>UIManager.setLookAndFeel(new <i>XXX</i>LookAndFeel())</code>).
* Using them while a different {@code LookAndFeel} is installed may produce
* unexpected results, including exceptions. Additionally, changing the
* {@code LookAndFeel} maintained by the {@code UIManager} without updating the
* corresponding {@code ComponentUI} of any {@code JComponent}s may also produce
* unexpected results, such as the wrong colors showing up, and is generally not
* encouraged.
* <p>
* <strong>Note:</strong>
* Most of the Swing API is <em>not</em> thread safe. For details, see
* <a
* href="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
* target="_top">Concurrency in Swing</a>,
* a section in
* <em><a href="https://docs.oracle.com/javase/tutorial/"
* target="_top">The Java Tutorial</a></em>.
*
* @since 1.2
* @serial exclude
*/
package javax.swing.plaf.basic;
| md-5/jdk10 | src/java.desktop/share/classes/javax/swing/plaf/basic/package-info.java | Java | gpl-2.0 | 2,590 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class Form, class Type>
inline Foam::Matrix<Form, Type>::Matrix()
:
v_(NULL),
n_(0),
m_(0)
{}
template<class Form, class Type>
inline Foam::autoPtr<Foam::Matrix<Form, Type> >
Foam::Matrix<Form, Type>::clone() const
{
return autoPtr<Matrix<Form, Type> >(new Matrix<Form, Type>(*this));
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Form, class Type>
inline const Foam::Matrix<Form, Type>& Foam::Matrix<Form, Type>::null()
{
return zero;
}
//- Return the number of rows
template<class Form, class Type>
inline Foam::label Foam::Matrix<Form, Type>::n() const
{
return n_;
}
template<class Form, class Type>
inline Foam::label Foam::Matrix<Form, Type>::m() const
{
return m_;
}
template<class Form, class Type>
inline Foam::label Foam::Matrix<Form, Type>::size() const
{
return n_*m_;
}
template<class Form, class Type>
inline void Foam::Matrix<Form, Type>::checki(const label i) const
{
if (!n_)
{
FatalErrorIn("Matrix<Form, Type>::checki(const label)")
<< "attempt to access element from zero sized row"
<< abort(FatalError);
}
else if (i<0 || i>=n_)
{
FatalErrorIn("Matrix<Form, Type>::checki(const label)")
<< "index " << i << " out of range 0 ... " << n_-1
<< abort(FatalError);
}
}
template<class Form, class Type>
inline void Foam::Matrix<Form, Type>::checkj(const label j) const
{
if (!m_)
{
FatalErrorIn("Matrix<Form, Type>::checkj(const label)")
<< "attempt to access element from zero sized column"
<< abort(FatalError);
}
else if (j<0 || j>=m_)
{
FatalErrorIn("Matrix<Form, Type>::checkj(const label)")
<< "index " << j << " out of range 0 ... " << m_-1
<< abort(FatalError);
}
}
// * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * //
template<class Form, class Type>
inline Type* Foam::Matrix<Form, Type>::operator[](const label i)
{
# ifdef FULLDEBUG
checki(i);
# endif
return v_[i];
}
template<class Form, class Type>
inline const Type* Foam::Matrix<Form, Type>::operator[](const label i) const
{
# ifdef FULLDEBUG
checki(i);
# endif
return v_[i];
}
// ************************************************************************* //
| WensiWu/openfoam-extend-foam-extend-3.1 | src/foam/matrices/Matrix/MatrixI.H | C++ | gpl-3.0 | 3,618 |
using UnityEngine;
/// <summary>
/// Functionality common to both NGUI and 2D sprites brought out into a single common parent.
/// Mostly contains everything related to drawing the sprite.
/// </summary>
public abstract class UIBasicSprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] protected Type mType = Type.Simple;
[HideInInspector][SerializeField] protected FillDirection mFillDirection = FillDirection.Radial360;
[Range(0f, 1f)]
[HideInInspector][SerializeField] protected float mFillAmount = 1.0f;
[HideInInspector][SerializeField] protected bool mInvert = false;
[HideInInspector][SerializeField] protected Flip mFlip = Flip.Nothing;
// Cached to avoid allocations
[System.NonSerialized] Rect mInnerUV = new Rect();
[System.NonSerialized] Rect mOuterUV = new Rect();
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn. It's virtual for legacy reasons (UISlicedSprite, UITiledSprite, UIFilledSprite).
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Whether the widget has a border for 9-slicing.
/// </summary>
public bool hasBorder
{
get
{
Vector4 br = border;
return (br.x != 0f || br.y != 0f || br.z != 0f || br.w != 0f);
}
}
/// <summary>
/// Whether the sprite's material is using a pre-multiplied alpha shader.
/// </summary>
public virtual bool premultipliedAlpha { get { return false; } }
/// <summary>
/// Size of the pixel. Overwritten in the NGUI sprite to pull a value from the atlas.
/// </summary>
public virtual float pixelSize { get { return 1f; } }
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
#region Fill Functions
// Static variables to reduce garbage collection
static protected Vector2[] mTempPos = new Vector2[4];
static protected Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Final widget's color passed to the draw buffer.
/// </summary>
Color32 drawingColor
{
get
{
Color colF = color;
colF.a = finalAlpha;
if (premultipliedAlpha) colF = NGUITools.ApplyPMA(colF);
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
colF.r = Mathf.GammaToLinearSpace(colF.r);
colF.g = Mathf.GammaToLinearSpace(colF.g);
colF.b = Mathf.GammaToLinearSpace(colF.b);
colF.a = Mathf.GammaToLinearSpace(colF.a);
}
return colF;
}
}
/// <summary>
/// Fill the draw buffers.
/// </summary>
protected void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner)
{
mOuterUV = outer;
mInnerUV = inner;
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
startPositionY, endPositionY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
Fill(verts, uvs, cols,
startPositionX, endPositionX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else // Corner
{
if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible) ||
(x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
}
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Helper function that adds the specified values to the buffers.
/// </summary>
static void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols,
float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion // Fill functions
}
| artandrtom/MyRepository | RacingCars/RacingCars/Assets/NGUI/Scripts/Internal/UIBasicSprite.cs | C# | gpl-3.0 | 25,566 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "PointEdgeWave.H"
#include "polyMesh.H"
#include "processorPolyPatch.H"
#include "cyclicPolyPatch.H"
#include "ggiPolyPatch.H"
#include "OPstream.H"
#include "IPstream.H"
#include "PstreamCombineReduceOps.H"
#include "debug.H"
#include "typeInfo.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
template <class Type>
Foam::scalar Foam::PointEdgeWave<Type>::propagationTol_ = 0.01;
// Offset labelList. Used for transferring from one cyclic half to the other.
template <class Type>
void Foam::PointEdgeWave<Type>::offset(const label val, labelList& elems)
{
forAll(elems, i)
{
elems[i] += val;
}
}
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
// Gets point-point correspondence. Is
// - list of halfA points (in cyclic patch points)
// - list of halfB points (can overlap with A!)
// - for every patchPoint its corresponding point
template <class Type>
void Foam::PointEdgeWave<Type>::calcCyclicAddressing()
{
label cycHalf = 0;
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<cyclicPolyPatch>(patch))
{
label halfSize = patch.size()/2;
SubList<face> halfAFaces
(
mesh_.faces(),
halfSize,
patch.start()
);
cycHalves_.set
(
cycHalf++,
new primitivePatch(halfAFaces, mesh_.points())
);
SubList<face> halfBFaces
(
mesh_.faces(),
halfSize,
patch.start() + halfSize
);
cycHalves_.set
(
cycHalf++,
new primitivePatch(halfBFaces, mesh_.points())
);
}
}
}
// Handle leaving domain. Implementation referred to Type
template <class Type>
void Foam::PointEdgeWave<Type>::leaveDomain
(
const polyPatch& meshPatch,
const primitivePatch& patch,
const labelList& patchPointLabels,
List<Type>& pointInfo
) const
{
const labelList& meshPoints = patch.meshPoints();
forAll(patchPointLabels, i)
{
label patchPointI = patchPointLabels[i];
const point& pt = patch.points()[meshPoints[patchPointI]];
pointInfo[i].leaveDomain(meshPatch, patchPointI, pt);
}
}
// Handle entering domain. Implementation referred to Type
template <class Type>
void Foam::PointEdgeWave<Type>::enterDomain
(
const polyPatch& meshPatch,
const primitivePatch& patch,
const labelList& patchPointLabels,
List<Type>& pointInfo
) const
{
const labelList& meshPoints = patch.meshPoints();
forAll(patchPointLabels, i)
{
label patchPointI = patchPointLabels[i];
const point& pt = patch.points()[meshPoints[patchPointI]];
pointInfo[i].enterDomain(meshPatch, patchPointI, pt);
}
}
// Transform. Implementation referred to Type
template <class Type>
void Foam::PointEdgeWave<Type>::transform
(
const tensorField& rotTensor,
List<Type>& pointInfo
) const
{
if (rotTensor.size() == 1)
{
const tensor& T = rotTensor[0];
forAll(pointInfo, i)
{
pointInfo[i].transform(T);
}
}
else
{
FatalErrorIn
(
"PointEdgeWave<Type>::transform(const tensorField&, List<Type>&)"
) << "Parallel cyclics not supported"
<< abort(FatalError);
forAll(pointInfo, i)
{
pointInfo[i].transform(rotTensor[i]);
}
}
}
// Update info for pointI, at position pt, with information from
// neighbouring edge.
// Updates:
// - changedPoint_, changedPoints_, nChangedPoints_,
// - statistics: nEvals_, nUnvisitedPoints_
template <class Type>
bool Foam::PointEdgeWave<Type>::updatePoint
(
const label pointI,
const label neighbourEdgeI,
const Type& neighbourInfo,
const scalar tol,
Type& pointInfo
)
{
nEvals_++;
bool wasValid = pointInfo.valid();
bool propagate =
pointInfo.updatePoint
(
mesh_,
pointI,
neighbourEdgeI,
neighbourInfo,
tol
);
if (propagate)
{
if (!changedPoint_[pointI])
{
changedPoint_[pointI] = true;
changedPoints_[nChangedPoints_++] = pointI;
}
}
if (!wasValid && pointInfo.valid())
{
--nUnvisitedPoints_;
}
return propagate;
}
// Update info for pointI, at position pt, with information from
// same point.
// Updates:
// - changedPoint_, changedPoints_, nChangedPoints_,
// - statistics: nEvals_, nUnvisitedPoints_
template <class Type>
bool Foam::PointEdgeWave<Type>::updatePoint
(
const label pointI,
const Type& neighbourInfo,
const scalar tol,
Type& pointInfo
)
{
nEvals_++;
bool wasValid = pointInfo.valid();
bool propagate =
pointInfo.updatePoint
(
mesh_,
pointI,
neighbourInfo,
tol
);
if (propagate)
{
if (!changedPoint_[pointI])
{
changedPoint_[pointI] = true;
changedPoints_[nChangedPoints_++] = pointI;
}
}
if (!wasValid && pointInfo.valid())
{
--nUnvisitedPoints_;
}
return propagate;
}
// Update info for edgeI, at position pt, with information from
// neighbouring point.
// Updates:
// - changedEdge_, changedEdges_, nChangedEdges_,
// - statistics: nEvals_, nUnvisitedEdge_
template <class Type>
bool Foam::PointEdgeWave<Type>::updateEdge
(
const label edgeI,
const label neighbourPointI,
const Type& neighbourInfo,
const scalar tol,
Type& edgeInfo
)
{
nEvals_++;
bool wasValid = edgeInfo.valid();
bool propagate =
edgeInfo.updateEdge
(
mesh_,
edgeI,
neighbourPointI,
neighbourInfo,
tol
);
if (propagate)
{
if (!changedEdge_[edgeI])
{
changedEdge_[edgeI] = true;
changedEdges_[nChangedEdges_++] = edgeI;
}
}
if (!wasValid && edgeInfo.valid())
{
--nUnvisitedEdges_;
}
return propagate;
}
// Check if patches of given type name are present
template <class Type>
template <class PatchType>
Foam::label Foam::PointEdgeWave<Type>::countPatchType() const
{
label nPatches = 0;
forAll(mesh_.boundaryMesh(), patchI)
{
if (isA<PatchType>(mesh_.boundaryMesh()[patchI]))
{
nPatches++;
}
}
return nPatches;
}
// Collect changed patch points
template <class Type>
void Foam::PointEdgeWave<Type>::getChangedPatchPoints
(
const primitivePatch& patch,
DynamicList<Type>& patchInfo,
DynamicList<label>& patchPoints,
DynamicList<label>& owner,
DynamicList<label>& ownerIndex
) const
{
const labelList& meshPoints = patch.meshPoints();
const faceList& localFaces = patch.localFaces();
const labelListList& pointFaces = patch.pointFaces();
forAll(meshPoints, patchPointI)
{
label meshPointI = meshPoints[patchPointI];
if (changedPoint_[meshPointI])
{
patchInfo.append(allPointInfo_[meshPointI]);
//Pout << "Sending " << meshPointI << " " << mesh_.points()[meshPointI] << " o = " << patchInfo[patchInfo.size()-1].origin() << " " << allPointInfo_[meshPointI] << endl;
patchPoints.append(patchPointI);
label patchFaceI = pointFaces[patchPointI][0];
const face& f = localFaces[patchFaceI];
label index = findIndex(f, patchPointI);
owner.append(patchFaceI);
ownerIndex.append(index);
}
}
patchInfo.shrink();
patchPoints.shrink();
owner.shrink();
ownerIndex.shrink();
}
// Update overall for changed patch points
template <class Type>
void Foam::PointEdgeWave<Type>::updateFromPatchInfo
(
const polyPatch& meshPatch,
const primitivePatch& patch,
const labelList& owner,
const labelList& ownerIndex,
List<Type>& patchInfo
)
{
const faceList& localFaces = patch.localFaces();
const labelList& meshPoints = patch.meshPoints();
// Get patch and mesh points.
labelList changedPatchPoints(patchInfo.size());
labelList changedMeshPoints(patchInfo.size());
forAll(owner, i)
{
label faceI = owner[i];
const face& f = localFaces[faceI];
label index = (f.size() - ownerIndex[i]) % f.size();
changedPatchPoints[i] = f[index];
changedMeshPoints[i] = meshPoints[f[index]];
}
// Adapt for entering domain
enterDomain(meshPatch, patch, changedPatchPoints, patchInfo);
// Merge received info
forAll(patchInfo, i)
{
updatePoint
(
changedMeshPoints[i],
patchInfo[i],
propagationTol_,
allPointInfo_[changedMeshPoints[i]]
);
}
}
// Transfer all the information to/from neighbouring processors
template <class Type>
void Foam::PointEdgeWave<Type>::handleProcPatches()
{
// 1. Send all point info on processor patches. Send as
// face label + offset in face.
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<processorPolyPatch>(patch))
{
// Get all changed points in relative addressing
DynamicList<Type> patchInfo(patch.nPoints());
DynamicList<label> patchPoints(patch.nPoints());
DynamicList<label> owner(patch.nPoints());
DynamicList<label> ownerIndex(patch.nPoints());
getChangedPatchPoints
(
patch,
patchInfo,
patchPoints,
owner,
ownerIndex
);
// Adapt for leaving domain
leaveDomain(patch, patch, patchPoints, patchInfo);
const processorPolyPatch& procPatch =
refCast<const processorPolyPatch>(patch);
if (debug)
{
Pout<< "Processor patch " << patchI << ' ' << patch.name()
<< " communicating with " << procPatch.neighbProcNo()
<< " Sending:" << patchInfo.size() << endl;
}
{
OPstream toNeighbour
(
Pstream::blocking,
procPatch.neighbProcNo()
);
toNeighbour << owner << ownerIndex << patchInfo;
}
}
}
//
// 2. Receive all point info on processor patches.
//
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<processorPolyPatch>(patch))
{
const processorPolyPatch& procPatch =
refCast<const processorPolyPatch>(patch);
List<Type> patchInfo;
labelList owner;
labelList ownerIndex;
{
IPstream fromNeighbour
(
Pstream::blocking,
procPatch.neighbProcNo()
);
fromNeighbour >> owner >> ownerIndex >> patchInfo;
}
if (debug)
{
Pout<< "Processor patch " << patchI << ' ' << patch.name()
<< " communicating with " << procPatch.neighbProcNo()
<< " Received:" << patchInfo.size() << endl;
}
// Apply transform to received data for non-parallel planes
if (!procPatch.parallel())
{
transform(procPatch.forwardT(), patchInfo);
}
updateFromPatchInfo
(
patch,
patch,
owner,
ownerIndex,
patchInfo
);
}
}
//
// 3. Handle all shared points
// (Note:irrespective if changed or not for now)
//
const globalMeshData& pd = mesh_.globalData();
List<Type> sharedData(pd.nGlobalPoints());
forAll(pd.sharedPointLabels(), i)
{
label meshPointI = pd.sharedPointLabels()[i];
// Fill my entries in the shared points
sharedData[pd.sharedPointAddr()[i]] = allPointInfo_[meshPointI];
}
// Combine on master. Reduce operator has to handle a list and call
// Type.updatePoint for all elements
combineReduce(sharedData, listUpdateOp<Type>());
forAll(pd.sharedPointLabels(), i)
{
label meshPointI = pd.sharedPointLabels()[i];
// Retrieve my entries from the shared points
updatePoint
(
meshPointI,
sharedData[pd.sharedPointAddr()[i]],
propagationTol_,
allPointInfo_[meshPointI]
);
}
}
template <class Type>
void Foam::PointEdgeWave<Type>::handleCyclicPatches()
{
// 1. Send all point info on cyclic patches. Send as
// face label + offset in face.
label cycHalf = 0;
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<cyclicPolyPatch>(patch))
{
const primitivePatch& halfA = cycHalves_[cycHalf++];
const primitivePatch& halfB = cycHalves_[cycHalf++];
// HalfA : get all changed points in relative addressing
DynamicList<Type> halfAInfo(halfA.nPoints());
DynamicList<label> halfAPoints(halfA.nPoints());
DynamicList<label> halfAOwner(halfA.nPoints());
DynamicList<label> halfAIndex(halfA.nPoints());
getChangedPatchPoints
(
halfA,
halfAInfo,
halfAPoints,
halfAOwner,
halfAIndex
);
// HalfB : get all changed points in relative addressing
DynamicList<Type> halfBInfo(halfB.nPoints());
DynamicList<label> halfBPoints(halfB.nPoints());
DynamicList<label> halfBOwner(halfB.nPoints());
DynamicList<label> halfBIndex(halfB.nPoints());
getChangedPatchPoints
(
halfB,
halfBInfo,
halfBPoints,
halfBOwner,
halfBIndex
);
// HalfA : adapt for leaving domain
leaveDomain(patch, halfA, halfAPoints, halfAInfo);
// HalfB : adapt for leaving domain
leaveDomain(patch, halfB, halfBPoints, halfBInfo);
// Apply rotation for non-parallel planes
const cyclicPolyPatch& cycPatch =
refCast<const cyclicPolyPatch>(patch);
if (!cycPatch.parallel())
{
// received data from half1
transform(cycPatch.forwardT(), halfAInfo);
// received data from half2
transform(cycPatch.forwardT(), halfBInfo);
}
if (debug)
{
Pout<< "Cyclic patch " << patchI << ' ' << patch.name()
<< " Changed on first half : " << halfAInfo.size()
<< " Changed on second half : " << halfBInfo.size()
<< endl;
}
// Half1: update with data from halfB
updateFromPatchInfo
(
patch,
halfA,
halfBOwner,
halfBIndex,
halfBInfo
);
// Half2: update with data from halfA
updateFromPatchInfo
(
patch,
halfB,
halfAOwner,
halfAIndex,
halfAInfo
);
if (debug)
{
//checkCyclic(patch);
}
}
}
}
// Update overall for changed patch points
template <class Type>
void Foam::PointEdgeWave<Type>::updateFromPatchInfo
(
const ggiPolyPatch& to,
const labelListList& shadowAddr,
const labelList& owner,
const labelList& ownerIndex,
List<Type>& patchInfo
)
{
//const labelList& meshPoints = to.meshPoints();
const pointField& points = to.points();
const List<face>& allFaces = mesh_.allFaces();
forAll(patchInfo, i)
{
label fID = to.shadow().zone()[owner[i]];
label pID = allFaces[fID][ownerIndex[i]];
point p = points[pID];
// Update in sending zone without propagation
if(fID >= mesh_.nFaces())
{
allPointInfo_[pID].updatePoint
(
mesh_,
pID,
patchInfo[i],
propagationTol_
);
}
const labelList& addr = shadowAddr[owner[i]];
if(addr.size() > 0)
{
label nearestPoint = -1;
label nearestFace = -1;
scalar dist = GREAT;
forAll(addr, saI)
{
label fID2 = to.zone()[addr[saI]];
const face& f = allFaces[fID2];
forAll(f, pI)
{
label pID2 = f[pI];
scalar d = magSqr(points[pID2] - p);
if(d < dist)
{
nearestFace = fID2;
nearestPoint = pID2;
dist = d;
}
else if(nearestPoint == pID2 && fID2 < mesh_.nFaces())
{
// Choose face in patch over face in zone
nearestFace = fID2;
}
}
}
patchInfo[i].enterDomain(to, nearestPoint, points[nearestPoint]);
if(nearestFace < mesh_.nFaces())
{
// Update in receiving patch with propagation
updatePoint
(
nearestPoint,
patchInfo[i],
propagationTol_,
allPointInfo_[nearestPoint]
);
}
else
{
// Update in receiving zone without propagation
allPointInfo_[nearestPoint].updatePoint
(
mesh_,
nearestPoint,
patchInfo[i],
propagationTol_
);
}
}
}
}
// Transfer all the information to/from neighbouring processors
template <class Type>
void Foam::PointEdgeWave<Type>::handleGgiPatches()
{
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<ggiPolyPatch>(patch))
{
const ggiPolyPatch& master = refCast<const ggiPolyPatch>(patch);
const ggiPolyPatch& slave = master.shadow();
if(master.master() && (master.localParallel() || master.size()))
{
// 1. Collect all point info on master side
DynamicList<Type> masterInfo(master.nPoints());
DynamicList<label> masterOwner(master.nPoints());
DynamicList<label> masterOwnerIndex(master.nPoints());
{
DynamicList<label> patchPoints(master.nPoints());
// Get all changed points in relative addressing
getChangedPatchPoints
(
master,
masterInfo,
patchPoints,
masterOwner,
masterOwnerIndex
);
forAll(masterOwner, i)
{
masterOwner[i] =
master.zoneAddressing()[masterOwner[i]];
}
// Adapt for leaving domain
leaveDomain(master, master, patchPoints, masterInfo);
if (debug)
{
Pout<< "Ggi patch " << master.index() << ' ' << master.name()
<< " Sending:" << masterInfo.size() << endl;
}
}
// 2. Collect all point info on slave side
DynamicList<Type> slaveInfo(slave.nPoints());
DynamicList<label> slaveOwner(slave.nPoints());
DynamicList<label> slaveOwnerIndex(slave.nPoints());
{
DynamicList<label> patchPoints(slave.nPoints());
// Get all changed points in relative addressing
getChangedPatchPoints
(
slave,
slaveInfo,
patchPoints,
slaveOwner,
slaveOwnerIndex
);
forAll(slaveOwner, i)
{
slaveOwner[i] =
slave.zoneAddressing()[slaveOwner[i]];
}
// Adapt for leaving domain
leaveDomain(slave, slave, patchPoints, slaveInfo);
if (debug)
{
Pout<< "Ggi patch " << slave.index() << ' ' << slave.name()
<< " Sending:" << slaveInfo.size() << endl;
}
}
if(!master.localParallel())
{
combineReduce(masterInfo, listAppendOp<Type>());
combineReduce(slaveInfo, listAppendOp<Type>());
combineReduce(masterOwner, listAppendOp<label>());
combineReduce(slaveOwner, listAppendOp<label>());
combineReduce(masterOwnerIndex, listAppendOp<label>());
combineReduce(slaveOwnerIndex, listAppendOp<label>());
}
// 3. Apply point info on master & slave side
if (debug)
{
Pout<< "Ggi patch " << slave.index() << ' ' << slave.name()
<< " Received:" << masterInfo.size() << endl;
Pout<< "Ggi patch " << master.index() << ' ' << master.name()
<< " Received:" << slaveInfo.size() << endl;
}
// Apply transform to received data for non-parallel planes
if (!master.parallel())
{
transform(master.forwardT(), masterInfo);
transform(slave.forwardT(), slaveInfo);
}
updateFromPatchInfo
(
slave,
master.patchToPatch().masterAddr(),
masterOwner,
masterOwnerIndex,
masterInfo
);
updateFromPatchInfo
(
master,
master.patchToPatch().slaveAddr(),
slaveOwner,
slaveOwnerIndex,
slaveInfo
);
}
}
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Iterate, propagating changedPointsInfo across mesh, until no change (or
// maxIter reached). Initial point values specified.
template <class Type>
Foam::PointEdgeWave<Type>::PointEdgeWave
(
const polyMesh& mesh,
const labelList& changedPoints,
const List<Type>& changedPointsInfo,
List<Type>& allPointInfo,
List<Type>& allEdgeInfo,
const label maxIter
)
:
mesh_(mesh),
allPointInfo_(allPointInfo),
allEdgeInfo_(allEdgeInfo),
changedPoint_(mesh_.nPoints(), false),
changedPoints_(mesh_.nPoints()),
nChangedPoints_(0),
changedEdge_(mesh_.nEdges(), false),
changedEdges_(mesh_.nEdges()),
nChangedEdges_(0),
nCyclicPatches_(countPatchType<cyclicPolyPatch>()),
nGgiPatches_(countPatchType<ggiPolyPatch>()),
cycHalves_(2*nCyclicPatches_),
nEvals_(0),
nUnvisitedPoints_(mesh_.nPoints()),
nUnvisitedEdges_(mesh_.nEdges())
{
if
(
allPointInfo_.size() != mesh_.nPoints()
&& allPointInfo_.size() != mesh_.allPoints().size()
)
{
FatalErrorIn
(
"PointEdgeWave<Type>::PointEdgeWave"
"(const polyMesh&, const labelList&, const List<Type>,"
" List<Type>&, List<Type>&, const label maxIter)"
) << "size of pointInfo work array is not equal to the number"
<< " of points in the mesh" << endl
<< " pointInfo :" << allPointInfo_.size() << endl
<< " mesh.nPoints:" << mesh_.nPoints()
<< exit(FatalError);
}
if (allEdgeInfo_.size() != mesh_.nEdges())
{
FatalErrorIn
(
"PointEdgeWave<Type>::PointEdgeWave"
"(const polyMesh&, const labelList&, const List<Type>,"
" List<Type>&, List<Type>&, const label maxIter)"
) << "size of edgeInfo work array is not equal to the number"
<< " of edges in the mesh" << endl
<< " edgeInfo :" << allEdgeInfo_.size() << endl
<< " mesh.nEdges:" << mesh_.nEdges()
<< exit(FatalError);
}
// Calculate cyclic halves addressing.
if (nCyclicPatches_ > 0)
{
calcCyclicAddressing();
}
// Set from initial changed points data
setPointInfo(changedPoints, changedPointsInfo);
if (debug)
{
Pout<< "Seed points : " << nChangedPoints_ << endl;
}
// Iterate until nothing changes
label iter = iterate(maxIter);
if ((maxIter > 0) && (iter >= maxIter))
{
FatalErrorIn
(
"PointEdgeWave<Type>::PointEdgeWave"
"(const polyMesh&, const labelList&, const List<Type>,"
" List<Type>&, List<Type>&, const label maxIter)"
) << "Maximum number of iterations reached. Increase maxIter." << nl
<< " maxIter:" << maxIter << endl
<< " nChangedPoints:" << nChangedPoints_ << endl
<< " nChangedEdges:" << nChangedEdges_ << endl
<< exit(FatalError);
}
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
template <class Type>
Foam::PointEdgeWave<Type>::~PointEdgeWave()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::getUnsetPoints() const
{
return nUnvisitedPoints_;
}
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::getUnsetEdges() const
{
return nUnvisitedEdges_;
}
// Copy point information into member data
template <class Type>
void Foam::PointEdgeWave<Type>::setPointInfo
(
const labelList& changedPoints,
const List<Type>& changedPointsInfo
)
{
forAll(changedPoints, changedPointI)
{
label pointI = changedPoints[changedPointI];
bool wasValid = allPointInfo_[pointI].valid();
// Copy info for pointI
allPointInfo_[pointI] = changedPointsInfo[changedPointI];
// Maintain count of unset points
if (!wasValid && allPointInfo_[pointI].valid())
{
--nUnvisitedPoints_;
}
// Mark pointI as changed, both on list and on point itself.
if (!changedPoint_[pointI])
{
changedPoint_[pointI] = true;
changedPoints_[nChangedPoints_++] = pointI;
}
}
}
// Propagate information from edge to point. Return number of points changed.
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::edgeToPoint()
{
for
(
label changedEdgeI = 0;
changedEdgeI < nChangedEdges_;
changedEdgeI++
)
{
label edgeI = changedEdges_[changedEdgeI];
if (!changedEdge_[edgeI])
{
FatalErrorIn("PointEdgeWave<Type>::edgeToPoint()")
<< "edge " << edgeI
<< " not marked as having been changed" << nl
<< "This might be caused by multiple occurences of the same"
<< " seed point." << abort(FatalError);
}
const Type& neighbourWallInfo = allEdgeInfo_[edgeI];
// Evaluate all connected points (= edge endpoints)
const edge& e = mesh_.edges()[edgeI];
forAll(e, eI)
{
Type& currentWallInfo = allPointInfo_[e[eI]];
if (currentWallInfo != neighbourWallInfo)
{
updatePoint
(
e[eI],
edgeI,
neighbourWallInfo,
propagationTol_,
currentWallInfo
);
}
}
// Reset status of edge
changedEdge_[edgeI] = false;
}
// Handled all changed edges by now
nChangedEdges_ = 0;
if (nCyclicPatches_ > 0)
{
// Transfer changed points across cyclic halves
handleCyclicPatches();
}
if (nGgiPatches_ > 0)
{
// Transfer changed points across cyclic halves
handleGgiPatches();
}
if (Pstream::parRun())
{
// Transfer changed points from neighbouring processors.
handleProcPatches();
}
if (debug)
{
Pout<< "Changed points : " << nChangedPoints_ << endl;
}
// Sum nChangedPoints over all procs
label totNChanged = nChangedPoints_;
reduce(totNChanged, sumOp<label>());
return totNChanged;
}
// Propagate information from point to edge. Return number of edges changed.
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::pointToEdge()
{
const labelListList& pointEdges = mesh_.pointEdges();
for
(
label changedPointI = 0;
changedPointI < nChangedPoints_;
changedPointI++
)
{
label pointI = changedPoints_[changedPointI];
if (!changedPoint_[pointI])
{
FatalErrorIn("PointEdgeWave<Type>::pointToEdge()")
<< "Point " << pointI
<< " not marked as having been changed" << nl
<< "This might be caused by multiple occurences of the same"
<< " seed point." << abort(FatalError);
}
const Type& neighbourWallInfo = allPointInfo_[pointI];
// Evaluate all connected edges
const labelList& edgeLabels = pointEdges[pointI];
forAll(edgeLabels, edgeLabelI)
{
label edgeI = edgeLabels[edgeLabelI];
Type& currentWallInfo = allEdgeInfo_[edgeI];
if (currentWallInfo != neighbourWallInfo)
{
updateEdge
(
edgeI,
pointI,
neighbourWallInfo,
propagationTol_,
currentWallInfo
);
}
}
// Reset status of point
changedPoint_[pointI] = false;
}
// Handled all changed points by now
nChangedPoints_ = 0;
if (debug)
{
Pout<< "Changed edges : " << nChangedEdges_ << endl;
}
// Sum nChangedPoints over all procs
label totNChanged = nChangedEdges_;
reduce(totNChanged, sumOp<label>());
return totNChanged;
}
// Iterate
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::iterate(const label maxIter)
{
if (nCyclicPatches_ > 0)
{
// Transfer changed points across cyclic halves
handleCyclicPatches();
}
if (nGgiPatches_ > 0)
{
// Transfer changed points across ggi patches
handleGgiPatches();
}
if (Pstream::parRun())
{
// Transfer changed points from neighbouring processors.
handleProcPatches();
}
nEvals_ = 0;
label iter = 0;
while(iter < maxIter)
{
if (debug)
{
Pout<< "Iteration " << iter << endl;
}
label nEdges = pointToEdge();
if (debug)
{
Pout<< "Total changed edges : " << nEdges << endl;
}
if (nEdges == 0)
{
break;
}
label nPoints = edgeToPoint();
if (debug)
{
Pout<< "Total changed points : " << nPoints << endl;
Pout<< "Total evaluations : " << nEvals_ << endl;
Pout<< "Remaining unvisited points: " << nUnvisitedPoints_ << endl;
Pout<< "Remaining unvisited edges : " << nUnvisitedEdges_ << endl;
Pout<< endl;
}
if (nPoints == 0)
{
break;
}
iter++;
}
return iter;
}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-foam-extend-3.0 | src/meshTools/PointEdgeWave/PointEdgeWave.C | C++ | gpl-3.0 | 34,391 |
using System;
using System.Linq;
using System.Windows.Forms;
using Rubberduck.Parsing.Grammar;
using Rubberduck.Parsing.Symbols;
using Rubberduck.Refactorings.Rename;
namespace Rubberduck.UI.Refactorings
{
public partial class RenameDialog : Form, IRenameView
{
public RenameDialog()
{
InitializeComponent();
InitializeCaptions();
Shown += RenameDialog_Shown;
NewNameBox.TextChanged += NewNameBox_TextChanged;
}
private void InitializeCaptions()
{
Text = RubberduckUI.RenameDialog_Caption;
OkButton.Text = RubberduckUI.OK;
CancelDialogButton.Text = RubberduckUI.CancelButtonText;
TitleLabel.Text = RubberduckUI.RenameDialog_TitleText;
InstructionsLabel.Text = RubberduckUI.RenameDialog_InstructionsLabelText;
NameLabel.Text = RubberduckUI.NameLabelText;
}
private void NewNameBox_TextChanged(object sender, EventArgs e)
{
NewName = NewNameBox.Text;
}
private void RenameDialog_Shown(object sender, EventArgs e)
{
NewNameBox.SelectAll();
NewNameBox.Focus();
}
private Declaration _target;
public Declaration Target
{
get { return _target; }
set
{
_target = value;
if (_target == null)
{
return;
}
NewName = _target.IdentifierName;
var declarationType =
RubberduckUI.ResourceManager.GetString("DeclarationType_" + _target.DeclarationType, RubberduckUI.Culture);
InstructionsLabel.Text = string.Format(RubberduckUI.RenameDialog_InstructionsLabelText, declarationType,
_target.IdentifierName);
}
}
public string NewName
{
get { return NewNameBox.Text; }
set
{
NewNameBox.Text = value;
ValidateNewName();
}
}
private void ValidateNewName()
{
var tokenValues = typeof(Tokens).GetFields().Select(item => item.GetValueDirect(new TypedReference())).Cast<string>().Select(item => item.ToLower());
OkButton.Enabled = NewName != Target.IdentifierName
&& char.IsLetter(NewName.FirstOrDefault())
&& !tokenValues.Contains(NewName.ToLower())
&& !NewName.Any(c => !char.IsLetterOrDigit(c) && c != '_');
InvalidNameValidationIcon.Visible = !OkButton.Enabled;
}
}
} | ptwales/Rubberduck | RetailCoder.VBE/UI/Refactorings/RenameDialog.cs | C# | gpl-3.0 | 2,733 |
/*******************************************************************************
**
** Photivo
**
** Copyright (C) 2008 Jos De Laender <jos.de_laender@telenet.be>
** Copyright (C) 2012-2013 Michael Munzert <mail@mm-log.com>
**
** This file is part of Photivo.
**
** Photivo is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License version 3
** as published by the Free Software Foundation.
**
** Photivo is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Photivo. If not, see <http://www.gnu.org/licenses/>.
**
*******************************************************************************/
#include "ptError.h"
#include "ptCalloc.h"
#include "ptImage8.h"
#include "ptImage.h"
#include "ptResizeFilters.h"
#include <cstdio>
#include <cstdlib>
#include <cassert>
//==============================================================================
ptImage8::ptImage8():
m_Width(0),
m_Height(0),
m_Colors(0),
m_ColorSpace(ptSpace_sRGB_D65),
m_SizeBytes(0)
{}
//==============================================================================
ptImage8::ptImage8(uint16_t AWidth,
uint16_t AHeight,
short ANrColors)
{
m_Image.clear();
m_ColorSpace = ptSpace_sRGB_D65;
setSize(AWidth, AHeight, ANrColors);
}
//==============================================================================
void ptImage8::setSize(uint16_t AWidth, uint16_t AHeight, int AColorCount) {
m_Width = AWidth;
m_Height = AHeight;
m_Colors = AColorCount;
m_SizeBytes = m_Width * m_Height * m_Colors;
m_Image.resize(m_Width * m_Height);
}
//==============================================================================
void ptImage8::fillColor(uint8_t ARed, uint8_t AGreen, uint8_t ABlue, uint8_t AAlpha) {
std::array<uint8_t, 4> hTemp = {{ARed, AGreen, ABlue, AAlpha}};
std::fill(std::begin(m_Image), std::end(m_Image), hTemp);
}
//==============================================================================
ptImage8::~ptImage8() {
// nothing to do
}
//==============================================================================
ptImage8* ptImage8::Set(const ptImage *Origin) {
assert(NULL != Origin);
assert(ptSpace_Lab != Origin->m_ColorSpace);
setSize(Origin->m_Width, Origin->m_Height, Origin->m_Colors);
m_ColorSpace = Origin->m_ColorSpace;
for (uint32_t i = 0; i < static_cast<uint32_t>(m_Width)*m_Height; i++) {
for (short c = 0; c < 3; c++) {
// Mind the R<->B swap !
m_Image[i][2-c] = Origin->m_Image[i][c]>>8;
}
m_Image[i][3] = 0xff;
}
return this;
}
//==============================================================================
ptImage8 *ptImage8::Set(const ptImage8 *Origin)
{
assert(NULL != Origin);
setSize(Origin->m_Width,
Origin->m_Height,
Origin->m_Colors);
m_ColorSpace = Origin->m_ColorSpace;
m_Image = Origin->m_Image;
return this;
}
//==============================================================================
void ptImage8::FromQImage(const QImage AImage)
{
setSize(AImage.width(), AImage.height(), 4);
m_ColorSpace = ptSpace_sRGB_D65;
memcpy((uint8_t (*)[4]) m_Image.data(), AImage.bits(), m_SizeBytes);
}
| tectronics/photivo | Sources/ptImage8.cpp | C++ | gpl-3.0 | 3,515 |
PhishingFramework::Application.routes.draw do
devise_for :admins
# image tracking routes.
get '/reports/image/:uid.png' => 'reports#image'
# only allow emails to be send from POST request
post '/email/preview_email/:id' => 'email#preview', as: 'preview_email'
post '/email/test_email/:id' => 'email#test', as: 'test_email'
post '/email/launch_email/:id' => 'email#launch', as: 'launch'
# only allow deletion from POST requests
get '/campaigns/delete_smtp_entry/:id' => 'campaigns#list'
get "reports/list"
get "reports/show"
get "reports/delete"
get "tools/emails" => "tools#emails"
get "tools/show_emails/:id" => "tools#show_emails", as: 'show_emails'
post "tools/enumerate_emails" => "tools#enumerate_emails"
delete "tools/emails/:id" => "tools#destroy_email", as: 'destroy_email'
get "tools/download_emails/:id" => "tools#download_emails", as: "download_emails"
get "tools/import_emails" => "tools#import_emails"
resources :campaigns do
collection do
get 'options'
get 'home'
get 'list'
get 'aboutus'
get 'victims'
get 'activity'
delete 'destroy'
end
member do
post 'clear_victims'
end
end
resources :blasts, only: [:show], shallow: true
resources :templates do
collection do
get 'list'
get 'restore'
get 'edit_email'
get 'update_attachment'
delete 'destroy'
end
end
resources :reports do
collection do
get 'list'
get 'stats'
get 'results'
get 'download_logs'
get 'download_stats'
get 'apache_logs'
get 'smtp'
get 'passwords'
post 'results'
delete 'clear'
end
member do
get 'download_excel'
end
end
resources :admin do
collection do
get 'list'
get 'global_settings'
put 'update_global_settings'
end
member do
get 'logins'
post 'approve'
post 'revoke'
delete 'destroy'
end
end
resources :clones do
member do
get 'download'
get 'preview'
end
end
resources :tools
root :to => 'campaigns#home'
match 'access', :to => 'access#menu', as: 'access', via: :get
require 'sidekiq/web'
authenticate :admin do
mount Sidekiq::Web => '/sidekiq'
end
require 'sidekiq/api'
match "queue-status" => proc { [200, {"Content-Type" => "text/plain"}, [Sidekiq::Queue.new.size < 100 ? "OK" : "UHOH" ]] }, via: :get
mount LetterOpenerWeb::Engine, at: 'letter_opener'
match ':controller(/:action(/:id))(.:format)', via: [:get, :post]
end
| zhuyue1314/phishing-frenzy | config/routes.rb | Ruby | gpl-3.0 | 2,411 |
<?php
/* ----------------------------------------------------------------------
* app/controllers/find/BrowseObjectsController.php
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2009-2013 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
require_once(__CA_LIB_DIR__."/ca/BaseBrowseController.php");
require_once(__CA_LIB_DIR__."/ca/Browse/ObjectBrowse.php");
require_once(__CA_LIB_DIR__."/core/GeographicMap.php");
class BrowseObjectsController extends BaseBrowseController {
# -------------------------------------------------------
/**
* Name of table for which this browse returns items
*/
protected $ops_tablename = 'ca_objects';
/**
* Number of items per results page
*/
protected $opa_items_per_page = array(8, 16, 24, 32);
/**
* List of result views supported for this browse
* Is associative array: keys are view labels, values are view specifier to be incorporated into view name
*/
protected $opa_views;
/**
* List of available result sorting fields
* Is associative array: values are display names for fields, keys are full fields names (table.field) to be used as sort
*/
protected $opa_sorts;
/**
* Name of "find" used to defined result context for ResultContext object
* Must be unique for the table and have a corresponding entry in find_navigation.conf
*/
protected $ops_find_type = 'basic_browse';
# -------------------------------------------------------
public function __construct(&$po_request, &$po_response, $pa_view_paths=null) {
parent::__construct($po_request, $po_response, $pa_view_paths);
$this->opo_browse = new ObjectBrowse($this->opo_result_context->getSearchExpression(), 'providence');
$this->opa_views = array(
'thumbnail' => _t('thumbnails'),
'full' => _t('full'),
'list' => _t('list'),
'editable' => _t('editable')
);
$this->opa_sorts = array_merge(array(
'ca_object_labels.name' => _t('title'),
'ca_objects.type_id' => _t('type'),
'ca_objects.idno_sort' => _t('idno')
), $this->opa_sorts);
}
# -------------------------------------------------------
public function Index($pa_options=null) {
JavascriptLoadManager::register('imageScroller');
JavascriptLoadManager::register('tabUI');
JavascriptLoadManager::register('panel');
parent::Index($pa_options);
}
# -------------------------------------------------------
/**
* Ajax action that returns info on a mapped location based upon the 'id' request parameter.
* 'id' is a list of object_ids to display information before. Each integer id is separated by a semicolon (";")
* The "ca_objects_results_map_balloon_html" view in Results/ is used to render the content.
*/
public function getMapItemInfo() {
$pa_object_ids = explode(';', $this->request->getParameter('id', pString));
$va_access_values = caGetUserAccessValues($this->request);
$this->view->setVar('ids', $pa_object_ids);
$this->view->setVar('access_values', $va_access_values);
$this->render("Results/ca_objects_results_map_balloon_html.php");
}
# -------------------------------------------------------
/**
* Returns string representing the name of the item the browse will return
*
* If $ps_mode is 'singular' [default] then the singular version of the name is returned, otherwise the plural is returned
*/
public function browseName($ps_mode='singular') {
return ($ps_mode === 'singular') ? _t('object') : _t('objects');
}
# -------------------------------------------------------
/**
* Returns string representing the name of this controller (minus the "Controller" part)
*/
public function controllerName() {
return 'BrowseObjects';
}
# -------------------------------------------------------
}
?> | libis/ca_babtekst | app/controllers/find/BrowseObjectsController.php | PHP | gpl-3.0 | 4,873 |
package org.thoughtcrime.securesms.crypto;
import androidx.annotation.NonNull;
import org.thoughtcrime.securesms.util.Hex;
import java.io.IOException;
public class DatabaseSecret {
private final byte[] key;
private final String encoded;
public DatabaseSecret(@NonNull byte[] key) {
this.key = key;
this.encoded = Hex.toStringCondensed(key);
}
public DatabaseSecret(@NonNull String encoded) throws IOException {
this.key = Hex.fromStringCondensed(encoded);
this.encoded = encoded;
}
public String asString() {
return encoded;
}
public byte[] asBytes() {
return key;
}
}
| jtracey/Signal-Android | src/org/thoughtcrime/securesms/crypto/DatabaseSecret.java | Java | gpl-3.0 | 627 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "UpwindFitData.H"
#include "surfaceFields.H"
#include "volFields.H"
#include "SVD.H"
#include "syncTools.H"
#include "extendedUpwindCellToFaceStencil.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class Polynomial>
Foam::UpwindFitData<Polynomial>::UpwindFitData
(
const fvMesh& mesh,
const extendedUpwindCellToFaceStencil& stencil,
const bool linearCorrection,
const scalar linearLimitFactor,
const scalar centralWeight
)
:
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>
(
mesh, stencil, linearCorrection, linearLimitFactor, centralWeight
),
owncoeffs_(mesh.nFaces()),
neicoeffs_(mesh.nFaces())
{
if (debug)
{
Info<< "Contructing UpwindFitData<Polynomial>" << endl;
}
calcFit();
if (debug)
{
Info<< "UpwindFitData<Polynomial>::UpwindFitData() :"
<< "Finished constructing polynomialFit data"
<< endl;
}
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Polynomial>
void Foam::UpwindFitData<Polynomial>::calcFit()
{
const fvMesh& mesh = this->mesh();
const surfaceScalarField& w = mesh.surfaceInterpolation::weights();
const surfaceScalarField::GeometricBoundaryField& bw = w.boundaryField();
// Owner stencil weights
// ~~~~~~~~~~~~~~~~~~~~~
// Get the cell/face centres in stencil order.
List<List<point> > stencilPoints(mesh.nFaces());
this->stencil().collectData
(
this->stencil().ownMap(),
this->stencil().ownStencil(),
mesh.C(),
stencilPoints
);
// find the fit coefficients for every owner
//Pout<< "-- Owner --" << endl;
for(label facei = 0; facei < mesh.nInternalFaces(); facei++)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit(owncoeffs_[facei], stencilPoints[facei], w[facei], facei);
//Pout<< " facei:" << facei
// << " at:" << mesh.faceCentres()[facei] << endl;
//forAll(owncoeffs_[facei], i)
//{
// Pout<< " point:" << stencilPoints[facei][i]
// << "\tweight:" << owncoeffs_[facei][i]
// << endl;
//}
}
forAll(bw, patchi)
{
const fvsPatchScalarField& pw = bw[patchi];
if (pw.coupled())
{
label facei = pw.patch().patch().start();
forAll(pw, i)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit
(
owncoeffs_[facei], stencilPoints[facei], pw[i], facei
);
facei++;
}
}
}
// Neighbour stencil weights
// ~~~~~~~~~~~~~~~~~~~~~~~~~
// Note:reuse stencilPoints since is major storage
this->stencil().collectData
(
this->stencil().neiMap(),
this->stencil().neiStencil(),
mesh.C(),
stencilPoints
);
// find the fit coefficients for every neighbour
//Pout<< "-- Neighbour --" << endl;
for(label facei = 0; facei < mesh.nInternalFaces(); facei++)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit(neicoeffs_[facei], stencilPoints[facei], w[facei], facei);
//Pout<< " facei:" << facei
// << " at:" << mesh.faceCentres()[facei] << endl;
//forAll(neicoeffs_[facei], i)
//{
// Pout<< " point:" << stencilPoints[facei][i]
// << "\tweight:" << neicoeffs_[facei][i]
// << endl;
//}
}
forAll(bw, patchi)
{
const fvsPatchScalarField& pw = bw[patchi];
if (pw.coupled())
{
label facei = pw.patch().patch().start();
forAll(pw, i)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit
(
neicoeffs_[facei], stencilPoints[facei], pw[i], facei
);
facei++;
}
}
}
}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-foam-extend-3.1 | src/finiteVolume/interpolation/surfaceInterpolation/schemes/UpwindFitScheme/UpwindFitData.C | C++ | gpl-3.0 | 5,777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.