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 |
|---|---|---|---|---|---|
/*
* Copyright 2015-2020 OpenCB
*
* 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.opencb.opencga.analysis.individual.qc;
import org.junit.Test;
import org.opencb.biodata.models.clinical.qc.MendelianErrorReport;
import org.opencb.biodata.models.clinical.qc.RelatednessReport;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.avro.IssueEntry;
import org.opencb.biodata.models.variant.avro.IssueType;
import org.opencb.opencga.analysis.family.qc.IBDComputation;
import org.opencb.opencga.core.common.JacksonUtils;
import org.opencb.opencga.core.exceptions.ToolException;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Paths;
import java.util.*;
import static org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.getResourceUri;
public class IndividualQcUtilsTest {
@Test
public void buildRelatednessReport() throws ToolException, IOException {
URI resourceUri = getResourceUri("ibd.genome");
File file = Paths.get(resourceUri.getPath()).toFile();
List<RelatednessReport.RelatednessScore> relatednessReport = IBDComputation.parseRelatednessScores(file);
System.out.println(JacksonUtils.getDefaultNonNullObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(relatednessReport));
}
@Test
public void parseMendelianError() throws IOException {
URI resourceUri = getResourceUri("mendelian.error.variants.json");
File file = Paths.get(resourceUri.getPath()).toFile();
List<Variant> variants = Arrays.asList(JacksonUtils.getDefaultNonNullObjectMapper().readValue(file, Variant[].class));
System.out.println(variants.size());
MendelianErrorReport mendelianErrorReport = buildMendelianErrorReport(variants.iterator(), variants.size());
System.out.println(JacksonUtils.getDefaultNonNullObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(mendelianErrorReport));
// List<Variant> variants = JacksonUtils.getDefaultNonNullObjectMapper().readerFor(Variant.class).readValue(path.toFile());
// System.out.println(variants.size());
}
@Test
public void parseKaryotypicSexThresholds() throws IOException {
URI resourceUri = getResourceUri("karyotypic_sex_thresholds.json");
File file = Paths.get(resourceUri.getPath()).toFile();
Map<String, Double> thresholds = JacksonUtils.getDefaultNonNullObjectMapper().readerFor(Map.class).readValue(file);
System.out.println(JacksonUtils.getDefaultNonNullObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(thresholds));
}
private MendelianErrorReport buildMendelianErrorReport(Iterator iterator, long numVariants) {
// Create auxiliary map
// sample chrom error count
Map<String, Map<String, Map<String, Integer>>> counter = new HashMap<>();
int numErrors = 0;
while (iterator.hasNext()) {
Variant variant = (Variant) iterator.next();
// Get sampleId and error code from variant issues
boolean foundError = false;
for (IssueEntry issue : variant.getStudies().get(0).getIssues()) {
if (IssueType.MENDELIAN_ERROR == issue.getType() || IssueType.DE_NOVO == issue.getType()) {
foundError = true;
String sampleId = issue.getSample().getSampleId();
String errorCode = issue.getSample().getData().get(0);
if (!counter.containsKey(sampleId)) {
counter.put(sampleId, new HashMap<>());
}
if (!counter.get(sampleId).containsKey(variant.getChromosome())) {
counter.get(sampleId).put(variant.getChromosome(), new HashMap<>());
}
int val = 0;
if (counter.get(sampleId).get(variant.getChromosome()).containsKey(errorCode)) {
val = counter.get(sampleId).get(variant.getChromosome()).get(errorCode);
}
counter.get(sampleId).get(variant.getChromosome()).put(errorCode, val + 1);
}
}
if (foundError) {
numErrors++;
}
}
// Create mendelian error report from auxiliary map
MendelianErrorReport meReport = new MendelianErrorReport();
meReport.setNumErrors(numErrors);
for (String sampleId : counter.keySet()) {
MendelianErrorReport.SampleAggregation sampleAgg = new MendelianErrorReport.SampleAggregation();
int numSampleErrors = 0;
for (String chrom : counter.get(sampleId).keySet()) {
int numChromErrors = counter.get(sampleId).get(chrom).values().stream().mapToInt(Integer::intValue).sum();
MendelianErrorReport.SampleAggregation.ChromosomeAggregation chromAgg = new MendelianErrorReport.SampleAggregation.ChromosomeAggregation();
chromAgg.setChromosome(chrom);
chromAgg.setNumErrors(numChromErrors);
chromAgg.setErrorCodeAggregation(counter.get(sampleId).get(chrom));
// Update sample aggregation
sampleAgg.getChromAggregation().add(chromAgg);
numSampleErrors += numChromErrors;
}
sampleAgg.setSample(sampleId);
sampleAgg.setNumErrors(numSampleErrors);
sampleAgg.setRatio(1.0d * numSampleErrors / numVariants);
meReport.getSampleAggregation().add(sampleAgg);
}
return meReport;
}
} | opencb/opencga | opencga-analysis/src/test/java/org/opencb/opencga/analysis/individual/qc/IndividualQcUtilsTest.java | Java | apache-2.0 | 6,198 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.siyeh.ig.redundancy;
import com.google.common.collect.ImmutableSet;
import com.intellij.codeInspection.ex.InspectionElementsMergerBase;
import com.intellij.util.ArrayUtilRt;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Set;
public class RedundantStringOperationMerger extends InspectionElementsMergerBase {
private static final String OLD_MERGER_NAME = "RedundantStringOperation";
private static final Set<String> OLD_SOURCE_NAMES = ImmutableSet.of("StringToString", "SubstringZero", "ConstantStringIntern");
@NotNull
@Override
public String getMergedToolName() {
return "StringOperationCanBeSimplified";
}
@Override
protected Element getSourceElement(@NotNull Map<String, Element> inspectionElements, @NotNull String sourceToolName) {
if (inspectionElements.containsKey(sourceToolName)) {
return inspectionElements.get(sourceToolName);
}
if (sourceToolName.equals(OLD_MERGER_NAME)) {//need to merge initial tools to get merged redundant string operations
return new InspectionElementsMergerBase(){
@NotNull
@Override
public String getMergedToolName() {
return OLD_MERGER_NAME;
}
@Override
public String @NotNull [] getSourceToolNames() {
return ArrayUtilRt.toStringArray(OLD_SOURCE_NAMES);
}
@Override
public Element merge(@NotNull Map<String, Element> inspectionElements) {
return super.merge(inspectionElements);
}
@Override
protected boolean writeMergedContent(@NotNull Element toolElement) {
return true;
}
}.merge(inspectionElements);
}
else if (OLD_SOURCE_NAMES.contains(sourceToolName)) {
Element merged = inspectionElements.get(OLD_MERGER_NAME);
if (merged != null) { // RedundantStringOperation already replaced the content
Element clone = merged.clone();
clone.setAttribute("class", sourceToolName);
return clone;
}
}
return null;
}
@Override
public String @NotNull [] getSourceToolNames() {
return new String[] {
"StringToString",
"SubstringZero",
"ConstantStringIntern",
"StringConstructor",
OLD_MERGER_NAME
};
}
@Override
public String @NotNull [] getSuppressIds() {
return new String[] {
"StringToString", "RedundantStringToString",
"SubstringZero", "ConstantStringIntern",
"RedundantStringConstructorCall", "StringConstructor", OLD_MERGER_NAME
};
}
}
| leafclick/intellij-community | plugins/InspectionGadgets/src/com/siyeh/ig/redundancy/RedundantStringOperationMerger.java | Java | apache-2.0 | 2,723 |
package com.app.annotation.aspect;
/**
* Created by baixiaokang on 17/1/31.
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Permission {
String[] value();
} | AndroidAdu/material-News | lib/src/main/java/com/app/annotation/aspect/Permission.java | Java | apache-2.0 | 363 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.module.impl;
import com.intellij.configurationStore.RenameableStateStorageManager;
import com.intellij.ide.highlighter.ModuleFileType;
import com.intellij.ide.plugins.ContainerDescriptor;
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.components.impl.stores.IComponentStore;
import com.intellij.openapi.components.impl.stores.ModuleStore;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleComponent;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.impl.scopes.ModuleScopeProviderImpl;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.roots.ExternalProjectSystemRegistry;
import com.intellij.openapi.roots.ProjectModelElement;
import com.intellij.openapi.roots.ProjectModelExternalSource;
import com.intellij.openapi.util.SimpleModificationTracker;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.serviceContainer.ComponentManagerImpl;
import com.intellij.util.xmlb.annotations.MapAnnotation;
import com.intellij.util.xmlb.annotations.Property;
import kotlin.Unit;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class ModuleImpl extends ComponentManagerImpl implements ModuleEx {
private static final Logger LOG = Logger.getInstance(ModuleImpl.class);
@NotNull private final Project myProject;
@Nullable protected VirtualFilePointer myImlFilePointer;
private volatile boolean isModuleAdded;
private String myName;
private final ModuleScopeProvider myModuleScopeProvider;
@ApiStatus.Internal
public ModuleImpl(@NotNull String name, @NotNull Project project, @NotNull String filePath) {
this(name, project);
myImlFilePointer = VirtualFilePointerManager.getInstance().create(
VfsUtilCore.pathToUrl(filePath), this,
new VirtualFilePointerListener() {
@Override
public void validityChanged(@NotNull VirtualFilePointer @NotNull [] pointers) {
if (myImlFilePointer == null) return;
VirtualFile virtualFile = myImlFilePointer.getFile();
if (virtualFile != null) {
((ModuleStore)getStore()).setPath(virtualFile.toNioPath(), virtualFile, false);
ModuleManager.getInstance(myProject).incModificationCount();
}
}
});
}
@ApiStatus.Internal
public ModuleImpl(@NotNull String name, @NotNull Project project, @Nullable VirtualFilePointer virtualFilePointer) {
this(name, project);
myImlFilePointer = virtualFilePointer;
}
@ApiStatus.Internal
public ModuleImpl(@NotNull String name, @NotNull Project project) {
super((ComponentManagerImpl)project);
registerServiceInstance(Module.class, this, ComponentManagerImpl.fakeCorePluginDescriptor);
myProject = project;
myModuleScopeProvider = new ModuleScopeProviderImpl(this);
myName = name;
}
@Override
public void init(@Nullable Runnable beforeComponentCreation) {
// do not measure (activityNamePrefix method not overridden by this class)
// because there are a lot of modules and no need to measure each one
registerComponents();
if (!isPersistent()) {
registerService(IComponentStore.class,
NonPersistentModuleStore.class,
ComponentManagerImpl.fakeCorePluginDescriptor,
true, ServiceDescriptor.PreloadMode.FALSE);
}
if (beforeComponentCreation != null) {
beforeComponentCreation.run();
}
createComponents(null);
}
private boolean isPersistent() {
return myImlFilePointer != null;
}
@Override
protected void setProgressDuringInit(@NotNull ProgressIndicator indicator) {
// Component loading progress is not reported for module, because at this stage minimal reporting unit it is the module itself.
// Stage "Loading modules" progress reported for each loaded module and module component count doesn't matter.
}
@Override
public final boolean isDisposed() {
// in case of light project in tests when it's temporarily disposed, the module should be treated as disposed too.
//noinspection TestOnlyProblems
return super.isDisposed() || ((ProjectEx)myProject).isLight() && myProject.isDisposed();
}
@Override
protected boolean isComponentSuitable(@NotNull ComponentConfig componentConfig) {
if (!super.isComponentSuitable(componentConfig)) {
return false;
}
Map<String, String> options = componentConfig.options;
if (options == null || options.isEmpty()) {
return true;
}
for (String optionName : options.keySet()) {
if ("workspace".equals(optionName) || "overrides".equals(optionName)) {
continue;
}
// we cannot filter using module options because at this moment module file data could be not loaded
String message = "Don't specify " + optionName + " in the component registration, transform component to service and implement your logic in your getInstance() method";
if (ApplicationManager.getApplication().isUnitTestMode()) {
LOG.error(message);
}
else {
LOG.warn(message);
}
}
return true;
}
@Override
@Nullable
public VirtualFile getModuleFile() {
if (myImlFilePointer == null) {
return null;
}
return myImlFilePointer.getFile();
}
@Override
public void rename(@NotNull String newName, boolean notifyStorage) {
myName = newName;
if (notifyStorage) {
((RenameableStateStorageManager)getStore().getStorageManager()).rename(newName + ModuleFileType.DOT_DEFAULT_EXTENSION);
}
}
protected @NotNull IComponentStore getStore() {
return Objects.requireNonNull(getService(IComponentStore.class));
}
@Override
public boolean canStoreSettings() {
return !(getStore() instanceof NonPersistentModuleStore);
}
@Override
@NotNull
public Path getModuleNioFile() {
if (!isPersistent()) {
return Paths.get("");
}
return getStore().getStorageManager().expandMacro(StoragePathMacros.MODULE_FILE);
}
@Override
public synchronized void dispose() {
isModuleAdded = false;
super.dispose();
}
@NotNull
@Override
protected ContainerDescriptor getContainerDescriptor(@NotNull IdeaPluginDescriptorImpl pluginDescriptor) {
return pluginDescriptor.moduleContainerDescriptor;
}
@Override
public void projectOpened() {
//noinspection deprecation
processInitializedComponents(ModuleComponent.class, (component, __) -> {
try {
//noinspection deprecation
component.projectOpened();
}
catch (Exception e) {
LOG.error(e);
}
return Unit.INSTANCE;
});
}
@Override
public void projectClosed() {
//noinspection deprecation
List<ModuleComponent> components = new ArrayList<>();
//noinspection deprecation
processInitializedComponents(ModuleComponent.class, (component, __) -> {
components.add(component);
return Unit.INSTANCE;
});
for (int i = components.size() - 1; i >= 0; i--) {
try {
//noinspection deprecation
components.get(i).projectClosed();
}
catch (Throwable e) {
LOG.error(e);
}
}
}
@Override
@NotNull
public Project getProject() {
return myProject;
}
@Override
@NotNull
public String getName() {
return myName;
}
@Override
public boolean isLoaded() {
return isModuleAdded;
}
@Override
public void moduleAdded() {
isModuleAdded = true;
//noinspection deprecation
processInitializedComponents(ModuleComponent.class, (component, __) -> {
//noinspection deprecation
component.moduleAdded();
return Unit.INSTANCE;
});
}
@Override
public void setOption(@NotNull String key, @Nullable String value) {
DeprecatedModuleOptionManager manager = getOptionManager();
if (value == null) {
if (manager.state.options.remove(key) != null) {
manager.incModificationCount();
}
}
else if (!value.equals(manager.state.options.put(key, value))) {
manager.incModificationCount();
}
}
@NotNull
private DeprecatedModuleOptionManager getOptionManager() {
//noinspection ConstantConditions
return ((Module)this).getService(DeprecatedModuleOptionManager.class);
}
@Override
public String getOptionValue(@NotNull String key) {
return getOptionManager().state.options.get(key);
}
@NotNull
@Override
public GlobalSearchScope getModuleScope() {
return myModuleScopeProvider.getModuleScope();
}
@NotNull
@Override
public GlobalSearchScope getModuleScope(boolean includeTests) {
return myModuleScopeProvider.getModuleScope(includeTests);
}
@NotNull
@Override
public GlobalSearchScope getModuleWithLibrariesScope() {
return myModuleScopeProvider.getModuleWithLibrariesScope();
}
@NotNull
@Override
public GlobalSearchScope getModuleWithDependenciesScope() {
return myModuleScopeProvider.getModuleWithDependenciesScope();
}
@NotNull
@Override
public GlobalSearchScope getModuleContentScope() {
return myModuleScopeProvider.getModuleContentScope();
}
@NotNull
@Override
public GlobalSearchScope getModuleContentWithDependenciesScope() {
return myModuleScopeProvider.getModuleContentWithDependenciesScope();
}
@NotNull
@Override
public GlobalSearchScope getModuleWithDependenciesAndLibrariesScope(boolean includeTests) {
return myModuleScopeProvider.getModuleWithDependenciesAndLibrariesScope(includeTests);
}
@NotNull
@Override
public GlobalSearchScope getModuleWithDependentsScope() {
return myModuleScopeProvider.getModuleWithDependentsScope();
}
@NotNull
@Override
public GlobalSearchScope getModuleTestsWithDependentsScope() {
return myModuleScopeProvider.getModuleTestsWithDependentsScope();
}
@NotNull
@Override
public GlobalSearchScope getModuleRuntimeScope(boolean includeTests) {
return myModuleScopeProvider.getModuleRuntimeScope(includeTests);
}
@Override
public void clearScopesCache() {
myModuleScopeProvider.clearCache();
}
@Override
public String toString() {
if (myName == null) return "Module (not initialized)";
return "Module: '" + getName() + "'" + (isDisposed() ? " (disposed)" : "");
}
@Override
public long getOptionsModificationCount() {
return getOptionManager().getModificationCount();
}
@ApiStatus.Internal
@State(name = "DeprecatedModuleOptionManager", useLoadedStateAsExisting = false /* doesn't make sense to check it */)
public static class DeprecatedModuleOptionManager extends SimpleModificationTracker implements PersistentStateComponent<DeprecatedModuleOptionManager.State>,
ProjectModelElement {
private final Module module;
DeprecatedModuleOptionManager(@NotNull Module module) {
this.module = module;
}
@Override
@Nullable
public ProjectModelExternalSource getExternalSource() {
if (state.options.size() > 1 || state.options.size() == 1 && !state.options.containsKey(Module.ELEMENT_TYPE) /* unrealistic case, but just to be sure */) {
return null;
}
return ExternalProjectSystemRegistry.getInstance().getExternalSource(module);
}
static final class State {
@Property(surroundWithTag = false)
@MapAnnotation(surroundKeyWithTag = false, surroundValueWithTag = false, surroundWithTag = false, entryTagName = "option")
public final Map<String, String> options = new HashMap<>();
}
private State state = new State();
@Nullable
@Override
public State getState() {
return state;
}
@Override
public void loadState(@NotNull State state) {
this.state = state;
}
}
}
| jwren/intellij-community | platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java | Java | apache-2.0 | 12,736 |
app.controller('PickerController', function ($scope, $modalInstance, itemColor) {
$scope.showCarrierColors = true;
$scope.brandColors = [
{
name: 'Brand Blue',
hex: '#276681'
},
{
name: 'Brand Green',
hex: '#66b245'
},
{
name: 'Brand Blue Desaturated',
hex: '#417c95'
},
{
name: 'Brand Green Desaturated',
hex: '#75b86f'
},
{
name: 'Bluest',
hex: '#5baebf'
},
{
name: 'Blue',
hex: '#66b7bb'
},
{
name: 'Blue Green',
hex: '#76beb6'
},
{
name: 'Green Blue',
hex: '#84c6ae'
},
{
name: 'Green',
hex: '#96cca7'
},
{
name: 'Greenest',
hex: '#a4d49a'
},
{
name: 'Level 2 Blend',
hex: '#7fced8'
},
{
name: 'Level 2 Blend',
hex: '#8fd4d6'
},
{
name: 'Level 2 Blend',
hex: '#a5d7d3'
},
{
name: 'Level 2 Blend',
hex: '#b5dcce'
},
{
name: 'Level 2 Blend',
hex: '#bfe0ca'
},
{
name: 'Level 2 Blend',
hex: '#c8e5c2'
},
{
name: 'Level 3 Blend',
hex: '#b0e2e7'
},
{
name: 'Level 3 Blend',
hex: '#bce5e6'
},
{
name: 'Level 3 Blend',
hex: '#c8e6e4'
},
{
name: 'Level 3 Blend',
hex: '#d3eae2'
},
{
name: 'Level 3 Blend',
hex: '#d8ecdf'
},
{
name: 'Level 3 Blend',
hex: '#ddefda'
},
{
name: 'Illustration Stroke Darkest',
hex: '#54636a'
},
{
name: 'Illustration Stroke Medium',
hex: '#7f8a8f'
},
{
name: 'Illustration Stroke Light',
hex: '#a9b1b4'
},
{
name: 'Illustration Stroke Lightest',
hex: '#d4d8da'
},
{
name: 'Yellow',
hex: '#f5db77'
},
{
name: 'Medium Yellow',
hex: '#f8e499'
},
{
name: 'Light Yellow',
hex: '#faedbb'
},
{
name: 'Lightest Yellow',
hex: '#fdf6dd'
},
{
name: 'Tang',
hex: '#f38871'
},
{
name: 'Medium Tang',
hex: '#f7a593'
},
{
name: 'Light Tang',
hex: '#fbc1b4'
},
{
name: 'Lightest Tang',
hex: '#ffded6'
},
{
name: 'Black',
hex: '#555555'
},
{
name: 'Dark Gray',
hex: '#797979'
},
{
name: 'Medium Gray',
hex: '#9c9c9c'
},
{
name: 'Light Gray',
hex: '#c0c0c0'
},
{
name: 'Lightest Gray',
hex: '#e3e3e3'
},
{
name: 'Off White',
hex: '#f9f9f9'
}
];
$scope.carrierColors = [
{
carrier: 'Verizon',
hex: '#ca5b59'
},
{
carrier: 'AT&T',
hex: '#5694b4'
},
{
carrier: 'T-Mobile',
hex: '#d45da0'
},
{
carrier: 'Sprint',
hex: '#e9b444'
},
{
carrier: 'Cricket',
hex: '#008752'
},
{
carrier: 'Cricket',
hex: '#439474'
},
{
carrier: 'MetroPCS',
hex: '#6764b3'
},
{
carrier: 'EE',
hex: '#2e9a9c'
},
{
carrier: 'O2',
hex: '#2566a8'
},
{
carrier: 'Orange',
hex: '#ff6c42'
},
{
carrier: 'Three',
hex: '#333333'
},
{
carrier: 'Vodafone',
hex: '#eb5247'
},
{
carrier: 'Bell',
hex: '#2876a5'
},
{
carrier: 'Leap',
hex: '#330066'
},
{
carrier: 'Rogers',
hex: '#d63e3e'
},
{
carrier: 'Telus',
hex: '#4e5cb5'
},
{
carrier: 'Videotron',
hex: '#fcc622'
},
{
carrier: 'Wind',
hex: '#ec7c23'
},
{
carrier: 'Tie',
hex: '#999999'
}
]
$scope.ok = function () {
$modalInstance.close(itemColor);
};
$scope.closeModal = function(color) {
$modalInstance.close(color);
}
}); | seanmthompson/D3-Chart-Generator | src/app/shared/colorpicker/pickerController.js | JavaScript | apache-2.0 | 3,420 |
/*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.mirror.declaration;
import java.lang.annotation.Annotation;
import java.util.Collection;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
/**
* Represents the declaration of a program element such as a package,
* class, or method. Each declaration represents a static, language-level
* construct (and not, for example, a runtime construct of the virtual
* machine), and typically corresponds one-to-one with a particular
* fragment of source code.
*
* <p> Declarations should be compared using the {@link #equals(Object)}
* method. There is no guarantee that any particular declaration will
* always be represented by the same object.
*
* @deprecated All components of this API have been superseded by the
* standardized annotation processing API. The replacement for the
* functionality of this interface is {@link
* javax.lang.model.element.Element}.
*
* @author Joseph D. Darcy
* @author Scott Seligman
*
* @see Declarations
* @see TypeMirror
* @since 1.5
*/
@Deprecated
@SuppressWarnings("deprecation")
public interface Declaration {
/**
* Tests whether an object represents the same declaration as this.
*
* @param obj the object to be compared with this declaration
* @return <tt>true</tt> if the specified object represents the same
* declaration as this
*/
boolean equals(Object obj);
/**
* Returns the text of the documentation ("javadoc") comment of
* this declaration.
*
* @return the documentation comment of this declaration, or <tt>null</tt>
* if there is none
*/
String getDocComment();
/**
* Returns the annotations that are directly present on this declaration.
*
* @return the annotations directly present on this declaration;
* an empty collection if there are none
*/
Collection<AnnotationMirror> getAnnotationMirrors();
/**
* Returns the annotation of this declaration having the specified
* type. The annotation may be either inherited or directly
* present on this declaration.
*
* <p> The annotation returned by this method could contain an element
* whose value is of type <tt>Class</tt>.
* This value cannot be returned directly: information necessary to
* locate and load a class (such as the class loader to use) is
* not available, and the class might not be loadable at all.
* Attempting to read a <tt>Class</tt> object by invoking the relevant
* method on the returned annotation
* will result in a {@link MirroredTypeException},
* from which the corresponding {@link TypeMirror} may be extracted.
* Similarly, attempting to read a <tt>Class[]</tt>-valued element
* will result in a {@link MirroredTypesException}.
*
* <blockquote>
* <i>Note:</i> This method is unlike
* others in this and related interfaces. It operates on run-time
* reflective information -- representations of annotation types
* currently loaded into the VM -- rather than on the mirrored
* representations defined by and used throughout these
* interfaces. It is intended for callers that are written to
* operate on a known, fixed set of annotation types.
* </blockquote>
*
* @param <A> the annotation type
* @param annotationType the <tt>Class</tt> object corresponding to
* the annotation type
* @return the annotation of this declaration having the specified type
*
* @see #getAnnotationMirrors()
*/
<A extends Annotation> A getAnnotation(Class<A> annotationType);
/**
* Returns the modifiers of this declaration, excluding annotations.
* Implicit modifiers, such as the <tt>public</tt> and <tt>static</tt>
* modifiers of interface members, are included.
*
* @return the modifiers of this declaration in undefined order;
* an empty collection if there are none
*/
Collection<Modifier> getModifiers();
/**
* Returns the simple (unqualified) name of this declaration.
* The name of a generic type does not include any reference
* to its formal type parameters.
* For example, the simple name of the interface declaration
* {@code java.util.Set<E>} is <tt>"Set"</tt>.
* If this declaration represents the empty package, an empty
* string is returned.
* If it represents a constructor, the simple name of its
* declaring class is returned.
*
* @return the simple name of this declaration
*/
String getSimpleName();
/**
* Returns the source position of the beginning of this declaration.
* Returns <tt>null</tt> if the position is unknown or not applicable.
*
* <p> This source position is intended for use in providing
* diagnostics, and indicates only approximately where a declaration
* begins.
*
* @return the source position of the beginning of this declaration,
* or null if the position is unknown or not applicable
*/
SourcePosition getPosition();
/**
* Applies a visitor to this declaration.
*
* @param v the visitor operating on this declaration
*/
void accept(DeclarationVisitor v);
}
| haikuowuya/android_system_code | src/com/sun/mirror/declaration/Declaration.java | Java | apache-2.0 | 5,514 |
package com.xsolla.android.sdk.data.model;
import java.util.List;
public class XHoldSubscriptionStatus {
private String status;
private List<XMessage> errors;
private XApi api;
public String getStatus() {
return status;
}
public List<XMessage> getErrors() {
return errors;
}
public String getErrorMsg() {
StringBuilder sb = new StringBuilder();
for (XMessage message : errors) {
sb.append(message.getMessage()).append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
@Override
public String toString() {
return "XHoldSubscription{" +
"status='" + status + '\'' +
", errors=" + errors +
", api=" + api +
'}';
}
}
| xsolla/xsolla-sdk-android | xsollasdk/src/main/java/com/xsolla/android/sdk/data/model/XHoldSubscriptionStatus.java | Java | apache-2.0 | 827 |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Evol.TMovie.Domain.Models.Entities;
using Evol.TMovie.Domain.QueryEntries.Parameters;
using Evol.Common;
using Evol.Domain.Data;
using Evol.Common.Data;
namespace Evol.TMovie.Domain.QueryEntries
{
public interface ISeatQueryEntry : IQueryEntry
{
Task<Seat> FindAsync(Guid id);
Task<List<Seat>> SelectAsync(SeatQueryParameter param);
Task<IPaged<Seat>> PagedAsync(SeatQueryParameter param, int pageIndex, int pageSize);
}
}
| supernebula/evol-core | src/Evol.TMovie.Domain/QueryEntries/ISeatQueryEntry.cs | C# | apache-2.0 | 549 |
package br.eti.arthurgregorio.fulljeearch.domain.security;
/**
*
* @author Arthur
*/
public interface ApplicationRoles {
public final String USER = "Usuario";
public final String ADMINISTRATOR = "Administrador";
}
| arthurgregorio/exemplos | FullJeeArch/src/main/java/br/eti/arthurgregorio/fulljeearch/domain/security/ApplicationRoles.java | Java | apache-2.0 | 228 |
namespace SharpGCalendar.Domain.Model
{
public enum Frequency
{
None = 0,
Daily = 1,
Weekly = 2,
Monthly = 4,
Yearly = 8
}
}
| jnicram/SharpGCalendar | backend-app/SharpGCalendar.Domain/Model/Frequency.cs | C# | apache-2.0 | 187 |
package com.almende.dialog.example.agent;
import java.io.Serializable;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import com.almende.dialog.Settings;
import com.almende.dialog.model.Answer;
import com.almende.dialog.model.Question;
import com.almende.util.ParallelInit;
import com.almende.util.twigmongo.QueryResultIterator;
import com.almende.util.twigmongo.TwigCompatibleMongoDatastore;
import com.almende.util.twigmongo.TwigCompatibleMongoDatastore.RootFindCommand;
import com.almende.util.twigmongo.annotations.Id;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@Path("yesno")
public class YesNoAgent {
static final ObjectMapper om =ParallelInit.getObjectMapper();
private static final String URL = "http://"+Settings.HOST+"/yesno/";
private static final String SOUNDURL = "http://ask4604.ask46.customers.luna.net/rest/";
private static final Logger log = Logger
.getLogger("DialogHandler");
public Question getQuestion(int question_no, String preferred_medium, String phonenumber) {
String questionURL = URL+"questions/"+question_no;
String answerYesURL = URL+"answers/0";
String answerNoURL = URL+"answers/1";
if (preferred_medium != null && preferred_medium.startsWith("audio")){
questionURL = this.getAudioFile(question_no);
answerYesURL= SOUNDURL+"14.wav";
answerNoURL= SOUNDURL+"14.wav";
}
Question question=new Question();
question.setRequester(URL+"id/");
question.setType("closed");
question.setQuestion_text(questionURL);
question.setAnswers(new ArrayList<Answer>(Arrays.asList(
new Answer(answerYesURL, URL+"questions/"+question_no+"?preferred_medium="+preferred_medium+"&pn="+phonenumber+"&answer=yes"),
new Answer(answerNoURL, URL+"questions/"+question_no+"?preferred_medium="+preferred_medium+"&pn="+phonenumber+"&answer=no"))));
return question;
}
@GET
@Path("/id/")
public Response getId(@QueryParam("preferred_language") String preferred_language){
ObjectNode node= om.createObjectNode();
node.put("url", URL);
node.put("nickname", "YesNo");
return Response.ok(node.toString()).build();
}
@GET
@Produces("application/json")
public Response firstQuestion(@QueryParam("preferred_medium") String preferred_medium, @QueryParam("remoteAddress") String responder, @QueryParam("requester") String requester){
int questionNo=0;
if(requester.contains("live") || requester.contains("0107421217")){
questionNo=1;
}
try {
responder = URLDecoder.decode(responder, "UTF-8");
} catch (Exception ex) {
log.severe(ex.getMessage());
}
Question question = getQuestion(questionNo, preferred_medium, responder);
return Response.ok(question.toJSON()).build();
}
@Path("/questions/{question_no}")
@POST
@Produces("application/json")
@Consumes("*/*")
public Response answerQuestion(@PathParam("question_no") String question_no, @QueryParam("preferred_medium") String preferred_medium,
@QueryParam("pn") String phonenumber, @QueryParam("answer") String answer){
Group group = this.getGroup("Group."+question_no+"."+answer);
group.addMember(phonenumber);
TwigCompatibleMongoDatastore datastore = new TwigCompatibleMongoDatastore();
datastore.store(group);
int responseQuestion=99;
String questionURL = URL+"questions/"+responseQuestion;
if (preferred_medium != null && preferred_medium.startsWith("audio")){
questionURL = this.getAudioFile(responseQuestion);
}
Question question=new Question();
question.setRequester(URL+"id/");
question.setType("comment");
question.setQuestion_text(questionURL);
return Response.ok( question.toJSON() ).build();
}
@Path("/questions/{question_no}")
@GET
@Produces("text/plain")
@Consumes("*/*")
public Response getQuestionText(@PathParam("question_no") String question_no ){
Integer questionNo = Integer.parseInt(question_no);
String result = "";
// These messages are now static but should be loaded from the LifeRay Database.
switch (questionNo){
case 0: result="Press 1 if you are available, press 2 if you are unavailable."; break;
case 1: result="Are you available?"; break;
case 99: result="Thank you for your input"; break;
default: result="Sorry, for some strange reason I don't have that question text available...";
}
return Response.ok(result).build();
}
@Path("/answers/{answer_no}")
@GET
@Produces("text/plain")
@Consumes("*/*")
public Response getAnswerText(@PathParam("answer_no") String answer_no, @QueryParam("preferred_medium") String prefered_mimeType){
Integer answerNo = Integer.parseInt(answer_no);
String result="";
// These messages can be static, because they are always the same.
switch (answerNo){
case 0: result="Yes"; break;
case 1: result="No"; break;
default: result="Sorry, for some strange reason I don't have that answer text available...";
}
return Response.ok(result).build();
}
// This urls will present the results
@Path("result")
@GET
public Response getResults() {
String result="";
ArrayList<Group> groups = (ArrayList<Group>) this.getAllGroups();
try {
result = om.writeValueAsString(groups);
} catch(Exception ex) {
ex.printStackTrace();
}
return Response.ok( result ).build();
}
// These functions should get there data from the liferay database.
// These are the audio files linked to the questions
public String getAudioFile(int question_no) {
switch(question_no) {
case 0: return SOUNDURL+"571.wav";
case 1: return SOUNDURL+"572.wav";
case 99: return SOUNDURL+"567.wav";
default: return SOUNDURL+"529.wav";
}
}
// These 2 functions are the group management
public Group getGroup(String id) {
TwigCompatibleMongoDatastore datastore = new TwigCompatibleMongoDatastore();
Group group = datastore.load(Group.class, id);
if(group!=null)
return group;
group = new Group();
group.setId(id);
return group;
}
public List<Group> getAllGroups() {
TwigCompatibleMongoDatastore datastore = new TwigCompatibleMongoDatastore();
RootFindCommand<Group> command = datastore.find()
.type(Group.class);
QueryResultIterator<Group> it = command.now();
List<Group> groups = new ArrayList<Group>();
while (it.hasNext()) {
groups.add(it.next());
}
return groups;
}
}
@SuppressWarnings("serial")
class Group implements Serializable {
public Group() {
this.members=new HashSet<String>();
}
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public Set<String> getMembers() {
return this.members;
}
public void addMember(String member) {
this.members.add(member);
}
@Id private String id=null;
private Set<String> members=null;
}
| almende/dialog | dialoghandler/src/main/java/com/almende/dialog/example/agent/YesNoAgent.java | Java | apache-2.0 | 7,159 |
package com.suscipio_solutions.consecro_mud.Commands;
import java.util.Vector;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMParms;
@SuppressWarnings("rawtypes")
public class NoFollow extends Follow
{
public NoFollow(){}
private final String[] access=I(new String[]{"NOFOLLOW","NOFOL"});
@Override public String[] getAccessWords(){return access;}
@Override
public boolean execute(MOB mob, Vector commands, int metaFlags)
throws java.io.IOException
{
if((commands.size()>1)&&(commands.elementAt(0) instanceof String))
{
if(((String)commands.elementAt(0)).equalsIgnoreCase("UNFOLLOW"))
{
unfollow(mob,((commands.size()>1)&&(commands.elementAt(1) instanceof String)&&(((String)commands.elementAt(1)).equalsIgnoreCase("QUIETLY"))));
return false;
}
MOB M=mob.fetchFollower(CMParms.combine(commands,1));
if((M==null)&&(mob.location()!=null))
{
M=mob.location().fetchInhabitant(CMParms.combine(commands,1));
if(M!=null)
mob.tell(L("@x1 is not following you!",M.name(mob)));
else
mob.tell(L("There is noone here called '@x1' following you!",CMParms.combine(commands,1)));
return false;
}
if((mob.location()!=null)&&(M!=null)&&(M.amFollowing()==mob))
{
nofollow(M,true,false);
return true;
}
mob.tell(L("There is noone called '@x1' following you!",CMParms.combine(commands,1)));
return false;
}
if(!mob.isAttribute(MOB.Attrib.NOFOLLOW))
{
mob.setAttribute(MOB.Attrib.NOFOLLOW,true);
//unfollow(mob,false);
mob.tell(L("You are no longer accepting new followers."));
}
else
{
mob.setAttribute(MOB.Attrib.NOFOLLOW,false);
mob.tell(L("You are now accepting new followers."));
}
return false;
}
@Override public boolean canBeOrdered(){return true;}
}
| ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Commands/NoFollow.java | Java | apache-2.0 | 1,837 |
/**
Copyright 2008 University of Rochester
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 edu.ur.ir.researcher;
import edu.ur.ir.FileSystem;
import edu.ur.ir.FileSystemType;
import edu.ur.persistent.CommonPersistent;
/**
* This is a link in the researcher folder. This
* creates a link between a link and a researcher
* folder
*
* @author Sharmila Ranganathan
*
*/
public class ResearcherLink extends CommonPersistent implements FileSystem{
/** Eclipse generated id */
private static final long serialVersionUID = 3144484183634385274L;
/** Link */
private String url;
/** researcher folder the link belongs to. */
private ResearcherFolder parentFolder;
/** Researcher the link belongs to */
private Researcher researcher;
/** represents the file system type for this researcher link */
private FileSystemType fileSystemType = FileSystemType.RESEARCHER_LINK;
/**
* Package protected constructor.
*/
ResearcherLink(){};
/**
* Create a researcher link with a null researcher folder. This means this
* is a root researcher link.
*
* @param linkVersion
*/
ResearcherLink(Researcher researcher, String link)
{
setResearcher(researcher);
setUrl(link);
}
/**
* Create a link between a folder and link.
*
* @param link - link to create a link with
* @param parentFolder - folder the link is in.
*/
ResearcherLink(Researcher researcher, ResearcherFolder parentFolder, String link)
{
if(link == null)
{
throw new IllegalStateException("link cannot be null");
}
setResearcher(researcher);
setUrl(link);
setParentFolder(parentFolder);
}
/**
* Returns the path for this linkVersion.
*
* The path is the path of the parent folder
*
* @return
*/
public String getPath()
{
String path = null;
if(parentFolder == null)
{
path = PATH_SEPERATOR;
}
else
{
path = parentFolder.getFullPath();
}
return path;
}
/**
* Overridden to string method.
*
* @see java.lang.Object#toString()
*/
public String toString()
{
StringBuffer sb = new StringBuffer("[ id = ");
sb.append(id);
sb.append( " path = ");
sb.append(getPath());
sb.append( " parent Folder = ");
sb.append(parentFolder);
sb.append(" name = ");
sb.append(name);
sb.append(" link = ");
sb.append(url);
sb.append("]");
return sb.toString();
}
/**
* Get the full path of this linkVersion. If there is
* no parent folder the path is just the name of
* the link.
*
* @return the full path.
*/
public String getFullPath()
{
return getPath() + getName();
}
/**
* Hash code for a researcher link.
*
* @see java.lang.Object#hashCode()
*/
public int hashCode()
{
int value = 0;
value += parentFolder == null ? 0 : parentFolder.hashCode();
value += getName() == null ? 0 : getName().hashCode();
value += researcher == null ? 0 : researcher.hashCode();
return value;
}
/**
* Equals method for a researcher link.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o)
{
if (this == o) return true;
if (!(o instanceof ResearcherLink)) return false;
final ResearcherLink other = (ResearcherLink) o;
if( (other.getName() != null && !other.getName().equals(getName())) ||
(other.getName() == null && getName() != null ) ) return false;
if( (other.getResearcher() != null && !other.getResearcher().equals(getResearcher())) ||
(other.getResearcher() == null && getResearcher() != null ) ) return false;
if( (other.getFullPath() != null && !other.getFullPath().equals(getFullPath())) ||
(other.getFullPath() == null && getFullPath() != null ) ) return false;
return true;
}
/**
* Returns the name of the link.
*
* @see edu.ur.simple.type.NameAware#getName()
*/
public String getName() {
return name;
}
/**
* Returns the description of the link.
*
* @see edu.ur.simple.type.DescriptionAware#getDescription()
*/
public String getDescription() {
return description;
}
/* (non-Javadoc)
* @see edu.ur.ir.FileSystem#getFileSystemType()
*/
public FileSystemType getFileSystemType() {
return fileSystemType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ResearcherFolder getParentFolder() {
return parentFolder;
}
public void setParentFolder(ResearcherFolder parentFolder) {
this.parentFolder = parentFolder;
}
public Researcher getResearcher() {
return researcher;
}
public void setResearcher(Researcher researcher) {
this.researcher = researcher;
}
}
| nate-rcl/irplus | ir_core/src/edu/ur/ir/researcher/ResearcherLink.java | Java | apache-2.0 | 5,358 |
package org.dbflute.erflute.db.impl.mysql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.dbflute.erflute.editor.model.dbimport.DBObject;
import org.dbflute.erflute.editor.model.dbimport.PreImportFromDBManager;
public class MySQLPreTableImportManager extends PreImportFromDBManager {
@Override
protected List<DBObject> importObjects(String[] types, String dbObjectType) throws SQLException {
final List<DBObject> list = new ArrayList<>();
ResultSet resultSet = null;
if (schemaList.isEmpty()) {
schemaList.add(null);
}
final String catalog = (8 <= metaData.getDriverMajorVersion()) ? dbSetting.getDatabase() : null;
for (final String schemaPattern : schemaList) {
try {
resultSet = metaData.getTables(catalog, schemaPattern, null, types);
while (resultSet.next()) {
final String schema = resultSet.getString("TABLE_SCHEM");
final String name = resultSet.getString("TABLE_NAME");
if (DBObject.TYPE_TABLE.equals(dbObjectType)) {
try {
getAutoIncrementColumnName(con, schema, name);
} catch (final SQLException e) {
e.printStackTrace();
// テーブル情報が取得できない場合(他のユーザの所有物などの場合)、
// このテーブルは使用しない。
continue;
}
}
final DBObject dbObject = new DBObject(schema, name, dbObjectType);
list.add(dbObject);
}
} finally {
if (resultSet != null) {
resultSet.close();
resultSet = null;
}
}
}
return list;
}
}
| dbflute-session/erflute | src/org/dbflute/erflute/db/impl/mysql/MySQLPreTableImportManager.java | Java | apache-2.0 | 2,037 |
/**
* Copyright 2016 Yahoo Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.common.metrics.impl;
import com.yahoo.athenz.common.metrics.Metric;
public class NoOpMetric implements Metric {
/**
* Constructs a new NoOpMetric object in which all methods are stubs.
* No metrics are recorded with this implementation.
*/
public NoOpMetric() {
}
@Override
public void increment(String metric) {
}
@Override
public void increment(String metric, String domainName) {
}
@Override
public void increment(String metric, String domainName, int count) {
}
@Override
public Object startTiming(String metric, String domainName) {
return null;
}
@Override
public void stopTiming(Object timerMetric) {
}
@Override
public void flush() {
}
@Override
public void quit() {
}
}
| tatyano/athenz | libs/java/server_common/src/main/java/com/yahoo/athenz/common/metrics/impl/NoOpMetric.java | Java | apache-2.0 | 1,436 |
app.service('UserService', ['$http', function($http) {
return {
getLogged: function(successCallback) {
$http.get('/api/user/logged').then(successCallback);
},
putPin: function(user, successCallback) {
$http.post('/api/user/pin/', user).then(successCallback);
}
};
}]); | jeffersonvenancio/BarzingaNow | python/web/app/services/user.js | JavaScript | apache-2.0 | 333 |
package ru.job4j.polymorphism;
/**
* Created on 01.09.2017.
*
* @author Aleks Sidorenko (alek.sidorenko1979@gmail.com).
* @version $Id$.
* @since 0.1.
*/
public class StubInput implements Input {
/**
* @param answers - array's param.
*/
private String[] answers;
/**
* @param position - param count position.
*/
private int position = 0;
/**
* Constructor.
* @param answers - array's param.
*/
public StubInput(String[] answers) {
this.answers = answers;
}
/**
* Method from interface.
* @param question - param of method interface.
* @return - string.
*/
public String ask(String question) {
return answers[position++];
}
}
| AlSidorenko/Junior | chapter_002/src/main/java/ru/job4j/polymorphism/StubInput.java | Java | apache-2.0 | 747 |
import { Component } from '@angular/core';
@Component({
selector: 'uxd-landing-page-feature-list',
template: '<ng-content></ng-content>',
styles: [':host { display: block; }'],
host: {
'class': 'row'
}
})
export class LandingPageFeatureListComponent {
} | UXAspects/UXAspects | docs/app/components/landing-page-feature-list/landing-page-feature-list.component.ts | TypeScript | apache-2.0 | 284 |
// Copyright 2015 The oauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki.
package odnoklassniki
import (
"github.com/coreos/mantle/Godeps/_workspace/src/golang.org/x/oauth2"
)
// Endpoint is Odnoklassniki's OAuth 2.0 endpoint.
var Endpoint = oauth2.Endpoint{
AuthURL: "https://www.odnoklassniki.ru/oauth/authorize",
TokenURL: "https://api.odnoklassniki.ru/oauth/token.do",
}
| mischief/mantle | Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go | GO | apache-2.0 | 557 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.undertow.attribute;
import io.undertow.server.HttpServerExchange;
/**
* The thread name
*
* @author Stuart Douglas
*/
public class ThreadNameAttribute implements ExchangeAttribute {
public static final String THREAD_NAME_SHORT = "%I";
public static final String THREAD_NAME = "%{THREAD_NAME}";
public static final ExchangeAttribute INSTANCE = new ThreadNameAttribute();
private ThreadNameAttribute() {
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
return Thread.currentThread().getName();
}
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
throw new ReadOnlyAttributeException("Thread name", newValue);
}
public static final class Builder implements ExchangeAttributeBuilder {
@Override
public String name() {
return "Thread name";
}
@Override
public ExchangeAttribute build(final String token) {
if (token.equals(THREAD_NAME) || token.equals(THREAD_NAME_SHORT)) {
return ThreadNameAttribute.INSTANCE;
}
return null;
}
}
}
| emag/codereading-undertow | core/src/main/java/io/undertow/attribute/ThreadNameAttribute.java | Java | apache-2.0 | 1,955 |
/**
* Copyright [2013-2014] [OHsystem]
*
* We spent a lot of time writing this code, so show some respect:
* - Do not remove this copyright notice anywhere (bot, website etc.)
* - We do not provide support to those who removed copyright notice
*
* OHSystem 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.
*
* You can contact the developers on: admin@ohsystem.net
* or join us directly here: http://forum.ohsystem.net/
*
* Visit us also on http://ohsystem.net/ and keep track always of the latest
* features and changes.
*
*
* This is modified from GHOST++: http://ohbotplusplus.googlecode.com/
*/
#include "../ohbot.h"
#include "stats.h"
//
// CStats
//
CStats :: CStats( CBaseGame *nGame ) : m_Game( nGame ), m_Locked( false )
{
}
CStats :: ~CStats( )
{
}
bool CStats :: ProcessAction( CIncomingAction *Action )
{
return false;
}
void CStats :: Save( COHBot *GHost, COHBotDB *DB, uint32_t GameID )
{
}
| m-unkel/OHSystem | ghost/src/stats/stats.cpp | C++ | apache-2.0 | 1,101 |
package org.techniche.technothlon.katana.tcd;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.techniche.technothlon.katana.R;
import org.techniche.technothlon.katana.db.TCDDatabase;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p/>
* TODO: Replace all uses of this class before publishing your app.
*/
public class TCDContent {
/**
* An array of sample (dummy) items.
*/
public static List<TCDQuestionMini> ITEMS = new ArrayList<TCDQuestionMini>();
/**
* A map of sample (dummy) items, by ID.
*/
public static Map<String, TCDQuestion> ITEM_MAP = new HashMap<String, TCDQuestion>();
private static String url = "http://localhost/technothlon/technocoupdoeil_app_gateway/android/?technocoupdoeil=fjalkfq2045rudacnavsofu0aswd988q29ra&lastFetchId=";
private static int download(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(
context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
long lastFetchID = sharedPref.getLong(context.getString(R.string.tcd_fetch_id), 0);
Log.d("Pref - log", lastFetchID + " from shared pref");
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
try {
JSONObject json = new JSONObject(downloadUrl(url + lastFetchID));
if (json.getString("status").equals("success")) {
TCDDatabase db = new TCDDatabase(context);
JSONArray questions = json.getJSONArray("questions");
lastFetchID = json.getLong("lastFetchId");
int count = json.getInt("questions_count"), lastID;
for (int i = 0; i < count; i++) {
JSONObject q = questions.getJSONObject(i);
JSONObject links = q.getJSONObject("links");
lastID = q.getInt("uniqueId");
db.insert(
lastID,
q.getString("id"),
q.getString("color"),
q.getString("title"),
q.getString("question"),
links.getString("facebook"),
links.getString("google"),
links.getString("tumblr"),
links.getString("answer"),
q.getString("by"),
q.getString("time"),
q.getString("answer")
);
Log.d("Database - log", lastID + " loaded in database");
}
db.close();
SharedPreferences.Editor edit = sharedPref.edit();
edit.putLong(context.getString(R.string.tcd_fetch_id), lastFetchID);
edit.commit();
} else if (json.getString("status").equals("reset")) {
TCDDatabase db = new TCDDatabase(context);
db.reset();
db.close();
SharedPreferences.Editor edit = sharedPref.edit();
edit.putLong(context.getString(R.string.tcd_fetch_id), 0);
edit.commit();
download(context);
}
final Context ct = context;
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(ct, "Sync Completed.", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return 0;
} catch (JSONException e) {
e.printStackTrace();
final Context ct = context;
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(ct, "Sync Failed.", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return 3;
} catch (IOException e) {
e.printStackTrace();
final Context ct = context;
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(ct, "Sync Failed.", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return 2;
}
} else {
final Context ct = context;
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(ct, "No network connection available.", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return 1;
}
}
private static String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("TCD latest downloads", "The response is: " + response);
int size = conn.getContentLength();
Log.d("TCD latest downloads", "The content-length is: " + size);
is = conn.getInputStream();
// Convert the InputStream into a string
return readTextResponse(is);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
private static String readTextResponse(InputStream inputStream) throws IOException {
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine);
}
return stringBuilder.toString();
}
public static void load(Context context) {
boolean update = ITEMS.isEmpty() ? false : true;
TCDDatabase helper = new TCDDatabase(context);
SQLiteDatabase db = helper.getReadableDatabase();
assert db != null;
Cursor c = db.rawQuery("SELECT * FROM " + TCDDatabase.Contracts.NAME + " ORDER BY " + TCDDatabase.Contracts.FIELD_TIME + " DESC, " + TCDDatabase.Contracts.FIELD_ID + " DESC", null);
Log.d("DB", c.getCount() + " object in database");
c.moveToFirst();
while (!c.isAfterLast()) {
addItem(new TCDQuestion(
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_ID)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_DISPLAY_ID)),
c.getInt(c.getColumnIndex(TCDDatabase.Contracts.FIELD_COLOR)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_TITLE)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_QUESTION)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_FACEBOOK)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_GOOGLE)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_TUMBLR)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_ANSWER_URL)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_BY)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_ANSWER)),
c.getString(c.getColumnIndex(TCDDatabase.Contracts.FIELD_TIME))
), update);
c.moveToNext();
}
c.close();
db.close();
}
private static void addItem(TCDQuestion item, boolean update) {
if (!ITEM_MAP.containsKey(item.uniqueId)) {
if (update) ITEMS.add(0, (new TCDQuestionMini(item.uniqueId)));
else ITEMS.add((new TCDQuestionMini(item.uniqueId)));
ITEM_MAP.put(item.uniqueId, item);
}
}
public abstract static class TCDLoader extends AsyncTask<Object, Integer, Integer> {
@Override
protected Integer doInBackground(Object[] params) {
int d = 4;
try {
d = download((Context) params[0]);
} catch (Exception e) {
e.printStackTrace();
} finally {
load((Context) params[0]);
}
return d;
}
@Override
protected void onPostExecute(Integer o) {
finished(o);
}
public abstract void finished(int result);
}
/**
* A dummy item representing a piece of content.
*/
public static class TCDQuestion {
public String id;
public String question;
public String facebook;
public String google;
public String tumblr;
public String answer_url;
public String by;
public String answer;
public String title;
public java.util.Date date = null;
public String dateString = "";
public int color = R.drawable.tcd_background_1;
public String uniqueId;
private String status;
private boolean ret = false;
public TCDQuestion(String uniqueId, String id, int color, String title, String question, String facebook, String google, String tumblr,
String answer_url, String by, String answer, String status) {
this.uniqueId = uniqueId;
this.id = id;
this.title = title;
this.question = question;
this.facebook = facebook;
this.google = google;
this.tumblr = tumblr;
this.answer_url = answer_url;
this.by = by;
this.color = getBackground(color);
this.answer = answer;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
this.date = sdf.parse(status);
} catch (ParseException e) {
e.printStackTrace();
}
sdf = new SimpleDateFormat("yyyy-MM-dd");
assert this.date != null;
this.dateString = sdf.format(this.date);
this.status = getStatus();
}
private int getBackground(int color) {
switch (color) {
case 10:
return R.drawable.tcd_background_2;
case 20:
return R.drawable.tcd_background_3;
case 30:
return R.drawable.tcd_background_4;
case 40:
return R.drawable.tcd_background_5;
case 50:
return R.drawable.tcd_background_6;
default:
return R.drawable.tcd_background_1;
}
}
public String getStatus() {
if (ret) return status;
long seconds = Math.abs(((new Date()).getTime() - date.getTime()) / 1000);
if (seconds < 60) status = "about " + seconds + " seconds ago";
else if (seconds < 3600) status = "about " + (seconds / 60) + " minutes ago";
else if (seconds < 86400) status = "about " + (seconds / 3600) + " hours ago";
else if (seconds < 172800) status = "yesterday";
else if (seconds < 345600) status = (seconds / 86400) + " days ago";
else {
ret = true;
status = dateString;
}
return status;
}
}
public static class TCDHolder {
public TextView id, title, question, status;
}
public static class TCDQuestionMini {
public String id;
public TCDQuestionMini(String id) {
this.id = id;
}
}
}
| znck/technothlon-android-app | katana/src/main/java/org/techniche/technothlon/katana/tcd/TCDContent.java | Java | apache-2.0 | 13,524 |
/*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.snmp.ctl;
import com.btisystems.pronx.ems.core.snmp.ISnmpConfiguration;
import com.btisystems.pronx.ems.core.snmp.ISnmpConfigurationFactory;
import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
import com.btisystems.pronx.ems.core.snmp.ISnmpSessionFactory;
import com.google.common.collect.Maps;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.alarm.Alarm;
import org.onosproject.alarm.AlarmId;
import org.onosproject.alarm.DefaultAlarm;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* DefaultSnmpController test class.
*/
public class DefaultSnmpControllerTest {
ISnmpSessionFactory mockSnmpSessionFactory = new MockISnmpSessionFactory();
DefaultSnmpController snmpController = new DefaultSnmpController();
DefaultSnmpDevice device = new DefaultSnmpDevice("1.1.1.1", 1, "test", "test");
ISnmpSession snmpSession = new ISnmpSessionAdapter();
long time = System.currentTimeMillis();
DefaultAlarm alarm = new DefaultAlarm.Builder(
AlarmId.alarmId(device.deviceId(), Long.toString(time)),
device.deviceId(), "SNMP alarm retrieval failed",
Alarm.SeverityLevel.CRITICAL,
time).build();
@Before
public void setUp() {
snmpController.factoryMap = Maps.newHashMap();
snmpController.factoryMap.put(1, mockSnmpSessionFactory);
}
@Test
public void testActivate() {
snmpController.activate(null);
assertTrue("Snmp session factory map should contain atleast one factory object",
snmpController.factoryMap.size() > 0);
}
@Test
public void testDeactivate() {
snmpController.deactivate();
assertEquals("Device map should be clear", 0, snmpController.getDevices().size());
assertEquals("Session map should be clear", 0, snmpController.sessionMap.size());
}
@Test
public void addDevice() {
snmpController.addDevice(device);
assertEquals("Controller should contain device", device, snmpController.getDevice(device.deviceId()));
}
/**
* tests session creation and get from map if already exists.
*/
@Test
public void getNotExistingSession() throws Exception {
addDevice();
assertEquals("Session should be created", snmpSession, snmpController.getSession(device.deviceId()));
assertEquals("Map should contain session", 1, snmpController.snmpDeviceMap.size());
assertEquals("Session should be fetched from map", snmpSession, snmpController.getSession(device.deviceId()));
}
@Test
public void removeDevice() {
addDevice();
snmpController.removeDevice(device.deviceId());
assertNull("Device shoudl not be present", snmpController.getDevice(device.deviceId()));
}
@Test
public void walkFailedAlarm() {
assertEquals("Alarms should be equals", alarm, snmpController.buildWalkFailedAlarm(device.deviceId()));
}
public class MockISnmpSessionFactory implements ISnmpSessionFactory {
@Override
public ISnmpSession createSession(ISnmpConfiguration configuration, String ipAddress) throws IOException {
new ISnmpSessionAdapter();
return snmpSession;
}
@Override
public ISnmpSession createSession(String ipAddress, String community)
throws IOException {
return snmpSession;
}
@Override
public ISnmpSession createSession(String ipAddress, String community,
String factoryName,
ISnmpConfigurationFactory.AccessType accessType)
throws IOException {
return snmpSession;
}
}
}
| opennetworkinglab/onos | protocols/snmp/ctl/src/test/java/org/onosproject/snmp/ctl/DefaultSnmpControllerTest.java | Java | apache-2.0 | 4,414 |
package com.zaaach.citypicker.db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import com.zaaach.citypicker.model.City;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* author Bro0cL on 2016/1/26.
*/
public class DBManager {
private static final String ASSETS_NAME = "china_cities.db";
private static final String DB_NAME = "china_cities.db";
private static final String TABLE_NAME = "city";
private static final String NAME = "name";
private static final String PINYIN = "pinyin";
private static final int BUFFER_SIZE = 1024;
private String DB_PATH;
private Context mContext;
public DBManager(Context context) {
this.mContext = context;
DB_PATH = File.separator + "data"
+ Environment.getDataDirectory().getAbsolutePath() + File.separator
+ context.getPackageName() + File.separator + "databases" + File.separator;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void copyDBFile(){
File dir = new File(DB_PATH);
if (!dir.exists()){
dir.mkdirs();
}
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbFile.exists()){
InputStream is;
OutputStream os;
try {
is = mContext.getResources().getAssets().open(ASSETS_NAME);
os = new FileOutputStream(dbFile);
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = is.read(buffer, 0, buffer.length)) > 0){
os.write(buffer, 0, length);
}
os.flush();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public List<City> getAllCities(){
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
List<City> result = new ArrayList<>();
City city;
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(NAME));
String pinyin = cursor.getString(cursor.getColumnIndex(PINYIN));
city = new City(name, pinyin);
result.add(city);
}
cursor.close();
db.close();
Collections.sort(result, new CityComparator());
return result;
}
public List<City> searchCity(final String keyword){
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME +" where name like \"%" + keyword
+ "%\" or pinyin like \"%" + keyword + "%\"", null);
List<City> result = new ArrayList<>();
City city;
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(NAME));
String pinyin = cursor.getString(cursor.getColumnIndex(PINYIN));
city = new City(name, pinyin);
result.add(city);
}
cursor.close();
db.close();
Collections.sort(result, new CityComparator());
return result;
}
/**
* sort by a-z
*/
private class CityComparator implements Comparator<City>{
@Override
public int compare(City lhs, City rhs) {
String a = lhs.getPinyin().substring(0, 1);
String b = rhs.getPinyin().substring(0, 1);
return a.compareTo(b);
}
}
}
| weiwenqiang/GitHub | SelectWidget/city/CityPicker/citypicker/src/main/java/com/zaaach/citypicker/db/DBManager.java | Java | apache-2.0 | 3,876 |
using Hyperstore.CodeAnalysis.Syntax;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hyperstore.CodeAnalysis.Compilation
{
public class HyperstoreCompiler
{
private readonly string _basePath;
private readonly string _outputDirectory;
private HyperstoreCompilation _compilation;
private const string OutputFileName = "Domains.g.cs";
public IEnumerable<Diagnostic> Diagnostics
{
get
{
return _compilation.GetDiagnostics();
}
}
public HyperstoreCompiler(string outputDirectory, string basePath = null)
{
_basePath = basePath;
_outputDirectory = outputDirectory;
}
public bool Run(string[] inputFiles)
{
if (inputFiles == null || inputFiles.Length == 0)
{
ClearOutputFile();
return false;
}
try
{
var trees = new HyperstoreSyntaxTree[inputFiles.Count()];
//if (trees.Length > 1)
//{
// Parallel.For(0, trees.Length, ix =>
// {
// var inputFile = inputFiles[ix];
// string content;
// string normalizedPath;
// if (OpenFile(inputFile, out content, out normalizedPath))
// {
// trees[ix] = HyperstoreSyntaxTree.ParseText(content, normalizedPath);
// }
// });
//}
//else
var i = 0;
foreach (var inputFile in inputFiles)
{
string content;
string normalizedPath;
if (OpenFile(inputFile, out content, out normalizedPath))
{
trees[i++] = HyperstoreSyntaxTree.ParseText(content, normalizedPath);
}
}
_compilation = HyperstoreCompilation.Create("C#", trees.Where(t => t != null));
if (_compilation.HasErrors)
{
ClearOutputFile();
return false;
}
var output = _compilation.Generate();
WriteOutputFile(output);
return true;
}
catch (Exception ex)
{
ClearOutputFile();
throw ex;
}
}
private void ClearOutputFile()
{
var tmp = MakeOutputFilePath();
OutputFilePath = null;
if (File.Exists(tmp))
File.Delete(tmp);
}
private void WriteOutputFile(string output)
{
OutputFilePath = MakeOutputFilePath();
Directory.CreateDirectory(Path.GetDirectoryName(OutputFilePath));
File.WriteAllText(OutputFilePath, output);
OutputFilePath = new FileInfo(OutputFilePath).FullName;
}
private string MakeOutputFilePath()
{
return Path.Combine(_outputDirectory, OutputFileName);
}
public bool OpenFile(string inputFile, out string content, out string normalizedPath)
{
content = null;
normalizedPath = _basePath != null ? Path.Combine(_basePath, inputFile) : inputFile;
if (!File.Exists(normalizedPath))
{
AddDiagnostic("File {0} not found.", normalizedPath);
return false;
}
using (var stream = File.OpenRead(normalizedPath))
{
using (var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
normalizedPath = stream.Name;
}
}
return true;
}
private void AddDiagnostic(string msg, params string[] args)
{
var diag = Diagnostic.Create(
args.Length == 0 ? msg : String.Format(msg, args),
DiagnosticSeverity.Error);
}
public string OutputFilePath { get; private set; }
}
}
| Hyperstore/Hyperstore.CodeAnalysis | Hyperstore.CodeAnalysis/Compilation/HyperstoreCompiler.cs | C# | apache-2.0 | 4,432 |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 automl from '@google-cloud/automl';
import * as dayjs from 'dayjs';
import * as express from 'express';
import { auth } from 'google-auth-library';
import * as morgan from 'morgan';
import {
AUTOML_API_SCOPE,
AUTOML_API_URL,
AUTOML_BUCKET_URL,
LOCATION,
PROJECT_ID,
} from './constants';
import { OperationMetadata } from './types';
export const app = express();
app.use(express.json());
app.use(morgan('combined'));
const client = new automl.v1beta1.AutoMlClient();
// Controls model type. For more options, see:
// https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models#imageclassificationmodelmetadata
const DEFAULT_MODEL_TYPE = 'mobile-high-accuracy-1';
const DEFAULT_TRAIN_BUDGET = 1;
const DATASET_NAME_REGEX = new RegExp('^[a-zA-Z_0-9]+$');
const MODEL_VERSION_FORMAT = 'vYYYYMMDDHHmmss';
const parent = client.locationPath(PROJECT_ID, LOCATION);
// A model as returned by AutoML /models response
interface Model {
name: string;
datasetId: string;
displayName: string;
createTime: string;
updateTime: string;
imageClassificationModelMetadata: {
trainBudget: string;
trainCost: string;
stopReason: string;
modelType: string;
};
}
interface ModelResp {
model: Model[];
}
/// create a new dataset
function createDataset(displayName: String): Promise<any> {
const dataset = {
name: displayName,
displayName,
imageClassificationDatasetMetadata: {
classificationType: 'MULTICLASS',
},
};
return client.createDataset({ parent, dataset });
}
const extractIdFromName = (datasetName: string): string => {
const parts = datasetName.split('/');
return parts[parts.length - 1];
};
/// returns the ID of a dataset of the format ICN** or null if not found
function getDatasetName(automlId: string): Promise<string | null> {
return client.listDatasets({ parent }).then((responses: any[]) => {
const datasets = responses[0];
for (const dataset of datasets) {
if (extractIdFromName(dataset['name']) === automlId) {
return dataset['name'];
}
}
return null;
});
}
/// initiates an operation on automl to start importing data for a dataset
async function importDataset(
name: string,
displayName: string,
labels: string
): Promise<OperationMetadata> {
const inputConfig = {
gcsSource: {
inputUris: [`${AUTOML_BUCKET_URL}/${displayName}/${labels}`],
},
};
return client
.importData({ name, inputConfig })
.then((responses: any[]) => responses[1]); // initial api response with operation metadata
}
/**
* List all datasets
*/
app.get('/datasets', async (req, res, next) => {
try {
const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] });
const url = `${AUTOML_API_URL}/datasets`;
const resp = await authClient.request({ url });
res.json(resp.data);
} catch (err) {
console.error(err);
next(err);
}
});
/**
* Endpoint to create a new dataset in automl. Requires a name parameter
*/
app.post('/datasets', async (req, res, next) => {
try {
const { displayName } = req.body;
if (displayName === undefined) {
res.status(400).send('Expected a dataset `displayName`');
return;
}
if (!displayName.match(DATASET_NAME_REGEX)) {
res
.status(400)
.send(
'The displayName contains a not allowed character, the' +
' only allowed ones are ASCII Latin letters A-Z and a-z, an underscore (_),' +
' and ASCII digits 0-9'
);
return;
}
console.info(`Attempting to create dataset: ${displayName}`);
const [response] = await createDataset(displayName);
res.json(response);
} catch (err) {
res.status(500);
res.json({message: err.message});
console.error(err);
}
});
/**
* Endpoint to delete dataset from automl
*/
app.delete('/datasets/:datasetId', async (req, res, next) => {
try {
const { datasetId } = req.params;
if (!datasetId) {
res.status(400).send(`Expected datasetId: ${datasetId}`);
return;
}
const name = await getDatasetName(datasetId);
if (name === null) {
res.status(404).send(`No dataset found for id: ${datasetId}`);
return;
}
const resp = await client.deleteDataset({ name });
console.log(resp);
res.json();
} catch (err) {
console.error(err);
res.status(500);
res.json({message: err.message});
}
});
/**
* Endpoint to initiate importing data for a dataset in automl.
*
* Inputs:
* - datasetId: string - automl ID of the dataset
* - name: string - display name of the dataset
* - labels: string - file name containing the labels information. e.g
* labels.csv
*/
app.post('/import', async (req, res, next) => {
const { name, labels, datasetId } = req.body;
if (!name) {
res.status(400).json({ error: 'Need a dataset name' });
return;
}
if (!datasetId) {
res.status(400).json({ error: 'Need a dataset Id' });
return;
}
if (!labels) {
res.status(400).json({ error: 'Need a path for labels file' });
return;
}
try {
const datasetName = await getDatasetName(datasetId);
if (datasetName === null) {
res.status(400).json({ error: 'Dataset not found' });
return;
}
const operationMetadata = await importDataset(datasetName, name, labels);
res.json(operationMetadata);
} catch (err) {
console.error(err);
res.status(500);
res.json({message: err.message});
}
});
/**
* Endpoint to initiate creation of a new model for the provided dataset
*
* Inputs
* - datasetId: string - automl ID of the dataset
* - trainBudget (optional)
* - modelType (optional)
* Calls the create model api on AutoML
* https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models/create
*
* Uses the rest API
*/
app.post('/train', async (req, res, next) => {
const { datasetId } = req.body;
if (!datasetId) {
res.status(400).json({ error: 'Need a dataset Id' });
return;
}
let { trainBudget, modelType } = req.body;
trainBudget = trainBudget === undefined ? DEFAULT_TRAIN_BUDGET : trainBudget;
modelType = modelType === undefined ? DEFAULT_MODEL_TYPE : modelType;
console.log(
`Using train budget: ${trainBudget}, and model type: ${modelType}`
);
try {
const datasetName = await getDatasetName(datasetId);
if (datasetName === null) {
res.status(400).json({ error: 'Dataset not found' });
return;
}
const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] });
const url = `${AUTOML_API_URL}/models`;
const resp = await authClient.request({
method: 'POST',
data: {
displayName: `${dayjs().format(MODEL_VERSION_FORMAT)}`,
dataset_id: datasetId,
imageClassificationModelMetadata: { trainBudget, modelType },
},
url,
});
const operationMetadata = resp.data as OperationMetadata;
res.json(operationMetadata);
} catch (err) {
console.error(err);
res.status(500);
res.json({message: err.message});
}
});
/**
* Exports a model in tflite format to a gcspath
*
* modelId - AutoML model ID: "ICN1119584480450950787",
* gcsPath - Path to which model is exported
* "gs://${AUTOML_BUCKET}/models/on-device/<folder_name>"
*
* Note the model will be generated in a folder with timestamp as name. For
* more, refer to
* https://cloud.google.com/vision/automl/alpha/docs/deploy#deployment_on_mobile_models_not_core_ml
*/
app.post('/export', async (req, res, next) => {
const { modelId, gcsPath } = req.body;
if (!modelId) {
res.status(400).send('need a model id: modelId');
return;
}
if (!gcsPath) {
res.status(400).send('need a gcs path: gcsPath');
return;
}
const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] });
const url = `${AUTOML_API_URL}/models/${modelId}:export`;
try {
const operationMetadata = await authClient
.request({
method: 'POST',
url,
data: {
output_config: {
model_format: 'tflite',
gcs_destination: {
output_uri_prefix: gcsPath,
},
},
},
})
.then(resp => resp.data as OperationMetadata);
res.json(operationMetadata);
} catch (err) {
console.error(err);
res.status(500);
res.json({message: err.message});
}
});
/**
* Exports the latest generated model for the dataset
*/
app.post('/exportlatestmodel', async (req, res, next) => {
const { datasetId, gcsPath } = req.body;
if (!datasetId) {
res.status(400).send('need a dataset id: datasetId');
return;
}
if (!gcsPath) {
res.status(400).send('need a gcs path: gcsPath');
return;
}
try {
// 1. Get all the models
const modelsResp = (await getAllModels()).data as ModelResp;
// 2. Filter the models for the provided dataset and get the latest model
const datasetModels = modelsResp.model.filter(
m =>
m.datasetId === datasetId &&
m.imageClassificationModelMetadata.modelType.startsWith('mobile-')
);
if (datasetModels === undefined) {
throw new Error('No models found for this dataset');
}
// 3. Find the latest (based on createTime) model
const latestModel = datasetModels.sort(
(m1, m2) =>
new Date(m2.createTime).getTime() - new Date(m1.createTime).getTime()
)[0];
// 3. Initiate its export
console.log('Initiating export for the latest model', latestModel);
const modelId = extractIdFromName(latestModel.name);
const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] });
const url = `${AUTOML_API_URL}/models/${modelId}:export`;
const operationMetadata = await authClient
.request({
method: 'POST',
url,
data: {
output_config: {
model_format: 'tflite',
gcs_destination: {
output_uri_prefix: gcsPath,
},
},
},
})
.then(resp => resp.data as OperationMetadata);
res.json(operationMetadata);
} catch (err) {
console.error(err);
res.status(500);
res.json({message: err.message});
}
});
/**
* List all models - trying out the REST API
*/
app.get('/models', async (req, res, next) => {
try {
const resp = await getAllModels();
res.json(resp.data);
} catch (err) {
console.error(err);
res.status(500);
res.json({message: err.message});
}
});
/** Queries all models from AutoML */
async function getAllModels() {
const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] });
const url = `${AUTOML_API_URL}/models`;
return authClient.request({ url });
}
| FirebaseExtended/mlkit-custom-image-classifier | functions/src/automlapi.ts | TypeScript | apache-2.0 | 11,363 |
//===-- ARMISelDAGToDAG.cpp - A dag to dag inst selector for ARM ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the ARM target.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMBaseInstrInfo.h"
#include "ARMTargetMachine.h"
#include "MCTargetDesc/ARMAddressingModes.h"
#include "Utils/ARMBaseInfo.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
#define DEBUG_TYPE "arm-isel"
static cl::opt<bool>
DisableShifterOp("disable-shifter-op", cl::Hidden,
cl::desc("Disable isel of shifter-op"),
cl::init(false));
//===--------------------------------------------------------------------===//
/// ARMDAGToDAGISel - ARM specific code to select ARM machine
/// instructions for SelectionDAG operations.
///
namespace {
class ARMDAGToDAGISel : public SelectionDAGISel {
/// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
/// make the right decision when generating code for different targets.
const ARMSubtarget *Subtarget;
public:
explicit ARMDAGToDAGISel(ARMBaseTargetMachine &tm, CodeGenOpt::Level OptLevel)
: SelectionDAGISel(tm, OptLevel) {}
bool runOnMachineFunction(MachineFunction &MF) override {
// Reset the subtarget each time through.
Subtarget = &MF.getSubtarget<ARMSubtarget>();
SelectionDAGISel::runOnMachineFunction(MF);
return true;
}
StringRef getPassName() const override { return "ARM Instruction Selection"; }
void PreprocessISelDAG() override;
/// getI32Imm - Return a target constant of type i32 with the specified
/// value.
inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
}
void Select(SDNode *N) override;
bool hasNoVMLxHazardUse(SDNode *N) const;
bool isShifterOpProfitable(const SDValue &Shift,
ARM_AM::ShiftOpc ShOpcVal, unsigned ShAmt);
bool SelectRegShifterOperand(SDValue N, SDValue &A,
SDValue &B, SDValue &C,
bool CheckProfitability = true);
bool SelectImmShifterOperand(SDValue N, SDValue &A,
SDValue &B, bool CheckProfitability = true);
bool SelectShiftRegShifterOperand(SDValue N, SDValue &A,
SDValue &B, SDValue &C) {
// Don't apply the profitability check
return SelectRegShifterOperand(N, A, B, C, false);
}
bool SelectShiftImmShifterOperand(SDValue N, SDValue &A,
SDValue &B) {
// Don't apply the profitability check
return SelectImmShifterOperand(N, A, B, false);
}
bool SelectAddLikeOr(SDNode *Parent, SDValue N, SDValue &Out);
bool SelectAddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
bool SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset, SDValue &Opc);
bool SelectCMOVPred(SDValue N, SDValue &Pred, SDValue &Reg) {
const ConstantSDNode *CN = cast<ConstantSDNode>(N);
Pred = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(N), MVT::i32);
Reg = CurDAG->getRegister(ARM::CPSR, MVT::i32);
return true;
}
bool SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc);
bool SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc);
bool SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc);
bool SelectAddrOffsetNone(SDValue N, SDValue &Base);
bool SelectAddrMode3(SDValue N, SDValue &Base,
SDValue &Offset, SDValue &Opc);
bool SelectAddrMode3Offset(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc);
bool IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset, bool FP16);
bool SelectAddrMode5(SDValue N, SDValue &Base, SDValue &Offset);
bool SelectAddrMode5FP16(SDValue N, SDValue &Base, SDValue &Offset);
bool SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,SDValue &Align);
bool SelectAddrMode6Offset(SDNode *Op, SDValue N, SDValue &Offset);
bool SelectAddrModePC(SDValue N, SDValue &Offset, SDValue &Label);
// Thumb Addressing Modes:
bool SelectThumbAddrModeRR(SDValue N, SDValue &Base, SDValue &Offset);
bool SelectThumbAddrModeRRSext(SDValue N, SDValue &Base, SDValue &Offset);
bool SelectThumbAddrModeImm5S(SDValue N, unsigned Scale, SDValue &Base,
SDValue &OffImm);
bool SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
SDValue &OffImm);
bool SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
SDValue &OffImm);
bool SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
SDValue &OffImm);
bool SelectThumbAddrModeSP(SDValue N, SDValue &Base, SDValue &OffImm);
// Thumb 2 Addressing Modes:
bool SelectT2AddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
bool SelectT2AddrModeImm8(SDValue N, SDValue &Base,
SDValue &OffImm);
bool SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
SDValue &OffImm);
bool SelectT2AddrModeSoReg(SDValue N, SDValue &Base,
SDValue &OffReg, SDValue &ShImm);
bool SelectT2AddrModeExclusive(SDValue N, SDValue &Base, SDValue &OffImm);
inline bool is_so_imm(unsigned Imm) const {
return ARM_AM::getSOImmVal(Imm) != -1;
}
inline bool is_so_imm_not(unsigned Imm) const {
return ARM_AM::getSOImmVal(~Imm) != -1;
}
inline bool is_t2_so_imm(unsigned Imm) const {
return ARM_AM::getT2SOImmVal(Imm) != -1;
}
inline bool is_t2_so_imm_not(unsigned Imm) const {
return ARM_AM::getT2SOImmVal(~Imm) != -1;
}
// Include the pieces autogenerated from the target description.
#include "ARMGenDAGISel.inc"
private:
void transferMemOperands(SDNode *Src, SDNode *Dst);
/// Indexed (pre/post inc/dec) load matching code for ARM.
bool tryARMIndexedLoad(SDNode *N);
bool tryT1IndexedLoad(SDNode *N);
bool tryT2IndexedLoad(SDNode *N);
/// SelectVLD - Select NEON load intrinsics. NumVecs should be
/// 1, 2, 3 or 4. The opcode arrays specify the instructions used for
/// loads of D registers and even subregs and odd subregs of Q registers.
/// For NumVecs <= 2, QOpcodes1 is not used.
void SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
const uint16_t *QOpcodes1);
/// SelectVST - Select NEON store intrinsics. NumVecs should
/// be 1, 2, 3 or 4. The opcode arrays specify the instructions used for
/// stores of D registers and even subregs and odd subregs of Q registers.
/// For NumVecs <= 2, QOpcodes1 is not used.
void SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
const uint16_t *QOpcodes1);
/// SelectVLDSTLane - Select NEON load/store lane intrinsics. NumVecs should
/// be 2, 3 or 4. The opcode arrays specify the instructions used for
/// load/store of D registers and Q registers.
void SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
unsigned NumVecs, const uint16_t *DOpcodes,
const uint16_t *QOpcodes);
/// SelectVLDDup - Select NEON load-duplicate intrinsics. NumVecs
/// should be 1, 2, 3 or 4. The opcode array specifies the instructions used
/// for loading D registers.
void SelectVLDDup(SDNode *N, bool IsIntrinsic, bool isUpdating,
unsigned NumVecs, const uint16_t *DOpcodes,
const uint16_t *QOpcodes0 = nullptr,
const uint16_t *QOpcodes1 = nullptr);
/// Try to select SBFX/UBFX instructions for ARM.
bool tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned);
// Select special operations if node forms integer ABS pattern
bool tryABSOp(SDNode *N);
bool tryReadRegister(SDNode *N);
bool tryWriteRegister(SDNode *N);
bool tryInlineAsm(SDNode *N);
void SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI);
void SelectCMP_SWAP(SDNode *N);
/// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
/// inline asm expressions.
bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
std::vector<SDValue> &OutOps) override;
// Form pairs of consecutive R, S, D, or Q registers.
SDNode *createGPRPairNode(EVT VT, SDValue V0, SDValue V1);
SDNode *createSRegPairNode(EVT VT, SDValue V0, SDValue V1);
SDNode *createDRegPairNode(EVT VT, SDValue V0, SDValue V1);
SDNode *createQRegPairNode(EVT VT, SDValue V0, SDValue V1);
// Form sequences of 4 consecutive S, D, or Q registers.
SDNode *createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
SDNode *createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
SDNode *createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
// Get the alignment operand for a NEON VLD or VST instruction.
SDValue GetVLDSTAlign(SDValue Align, const SDLoc &dl, unsigned NumVecs,
bool is64BitVector);
/// Returns the number of instructions required to materialize the given
/// constant in a register, or 3 if a literal pool load is needed.
unsigned ConstantMaterializationCost(unsigned Val) const;
/// Checks if N is a multiplication by a constant where we can extract out a
/// power of two from the constant so that it can be used in a shift, but only
/// if it simplifies the materialization of the constant. Returns true if it
/// is, and assigns to PowerOfTwo the power of two that should be extracted
/// out and to NewMulConst the new constant to be multiplied by.
bool canExtractShiftFromMul(const SDValue &N, unsigned MaxShift,
unsigned &PowerOfTwo, SDValue &NewMulConst) const;
/// Replace N with M in CurDAG, in a way that also ensures that M gets
/// selected when N would have been selected.
void replaceDAGValue(const SDValue &N, SDValue M);
};
}
/// isInt32Immediate - This method tests to see if the node is a 32-bit constant
/// operand. If so Imm will receive the 32-bit value.
static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
Imm = cast<ConstantSDNode>(N)->getZExtValue();
return true;
}
return false;
}
// isInt32Immediate - This method tests to see if a constant operand.
// If so Imm will receive the 32 bit value.
static bool isInt32Immediate(SDValue N, unsigned &Imm) {
return isInt32Immediate(N.getNode(), Imm);
}
// isOpcWithIntImmediate - This method tests to see if the node is a specific
// opcode and that it has a immediate integer right operand.
// If so Imm will receive the 32 bit value.
static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
return N->getOpcode() == Opc &&
isInt32Immediate(N->getOperand(1).getNode(), Imm);
}
/// Check whether a particular node is a constant value representable as
/// (N * Scale) where (N in [\p RangeMin, \p RangeMax).
///
/// \param ScaledConstant [out] - On success, the pre-scaled constant value.
static bool isScaledConstantInRange(SDValue Node, int Scale,
int RangeMin, int RangeMax,
int &ScaledConstant) {
assert(Scale > 0 && "Invalid scale!");
// Check that this is a constant.
const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Node);
if (!C)
return false;
ScaledConstant = (int) C->getZExtValue();
if ((ScaledConstant % Scale) != 0)
return false;
ScaledConstant /= Scale;
return ScaledConstant >= RangeMin && ScaledConstant < RangeMax;
}
void ARMDAGToDAGISel::PreprocessISelDAG() {
if (!Subtarget->hasV6T2Ops())
return;
bool isThumb2 = Subtarget->isThumb();
for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
E = CurDAG->allnodes_end(); I != E; ) {
SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
if (N->getOpcode() != ISD::ADD)
continue;
// Look for (add X1, (and (srl X2, c1), c2)) where c2 is constant with
// leading zeros, followed by consecutive set bits, followed by 1 or 2
// trailing zeros, e.g. 1020.
// Transform the expression to
// (add X1, (shl (and (srl X2, c1), (c2>>tz)), tz)) where tz is the number
// of trailing zeros of c2. The left shift would be folded as an shifter
// operand of 'add' and the 'and' and 'srl' would become a bits extraction
// node (UBFX).
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
unsigned And_imm = 0;
if (!isOpcWithIntImmediate(N1.getNode(), ISD::AND, And_imm)) {
if (isOpcWithIntImmediate(N0.getNode(), ISD::AND, And_imm))
std::swap(N0, N1);
}
if (!And_imm)
continue;
// Check if the AND mask is an immediate of the form: 000.....1111111100
unsigned TZ = countTrailingZeros(And_imm);
if (TZ != 1 && TZ != 2)
// Be conservative here. Shifter operands aren't always free. e.g. On
// Swift, left shifter operand of 1 / 2 for free but others are not.
// e.g.
// ubfx r3, r1, #16, #8
// ldr.w r3, [r0, r3, lsl #2]
// vs.
// mov.w r9, #1020
// and.w r2, r9, r1, lsr #14
// ldr r2, [r0, r2]
continue;
And_imm >>= TZ;
if (And_imm & (And_imm + 1))
continue;
// Look for (and (srl X, c1), c2).
SDValue Srl = N1.getOperand(0);
unsigned Srl_imm = 0;
if (!isOpcWithIntImmediate(Srl.getNode(), ISD::SRL, Srl_imm) ||
(Srl_imm <= 2))
continue;
// Make sure first operand is not a shifter operand which would prevent
// folding of the left shift.
SDValue CPTmp0;
SDValue CPTmp1;
SDValue CPTmp2;
if (isThumb2) {
if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1))
continue;
} else {
if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1) ||
SelectRegShifterOperand(N0, CPTmp0, CPTmp1, CPTmp2))
continue;
}
// Now make the transformation.
Srl = CurDAG->getNode(ISD::SRL, SDLoc(Srl), MVT::i32,
Srl.getOperand(0),
CurDAG->getConstant(Srl_imm + TZ, SDLoc(Srl),
MVT::i32));
N1 = CurDAG->getNode(ISD::AND, SDLoc(N1), MVT::i32,
Srl,
CurDAG->getConstant(And_imm, SDLoc(Srl), MVT::i32));
N1 = CurDAG->getNode(ISD::SHL, SDLoc(N1), MVT::i32,
N1, CurDAG->getConstant(TZ, SDLoc(Srl), MVT::i32));
CurDAG->UpdateNodeOperands(N, N0, N1);
}
}
/// hasNoVMLxHazardUse - Return true if it's desirable to select a FP MLA / MLS
/// node. VFP / NEON fp VMLA / VMLS instructions have special RAW hazards (at
/// least on current ARM implementations) which should be avoidded.
bool ARMDAGToDAGISel::hasNoVMLxHazardUse(SDNode *N) const {
if (OptLevel == CodeGenOpt::None)
return true;
if (!Subtarget->hasVMLxHazards())
return true;
if (!N->hasOneUse())
return false;
SDNode *Use = *N->use_begin();
if (Use->getOpcode() == ISD::CopyToReg)
return true;
if (Use->isMachineOpcode()) {
const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
CurDAG->getSubtarget().getInstrInfo());
const MCInstrDesc &MCID = TII->get(Use->getMachineOpcode());
if (MCID.mayStore())
return true;
unsigned Opcode = MCID.getOpcode();
if (Opcode == ARM::VMOVRS || Opcode == ARM::VMOVRRD)
return true;
// vmlx feeding into another vmlx. We actually want to unfold
// the use later in the MLxExpansion pass. e.g.
// vmla
// vmla (stall 8 cycles)
//
// vmul (5 cycles)
// vadd (5 cycles)
// vmla
// This adds up to about 18 - 19 cycles.
//
// vmla
// vmul (stall 4 cycles)
// vadd adds up to about 14 cycles.
return TII->isFpMLxInstruction(Opcode);
}
return false;
}
bool ARMDAGToDAGISel::isShifterOpProfitable(const SDValue &Shift,
ARM_AM::ShiftOpc ShOpcVal,
unsigned ShAmt) {
if (!Subtarget->isLikeA9() && !Subtarget->isSwift())
return true;
if (Shift.hasOneUse())
return true;
// R << 2 is free.
return ShOpcVal == ARM_AM::lsl &&
(ShAmt == 2 || (Subtarget->isSwift() && ShAmt == 1));
}
unsigned ARMDAGToDAGISel::ConstantMaterializationCost(unsigned Val) const {
if (Subtarget->isThumb()) {
if (Val <= 255) return 1; // MOV
if (Subtarget->hasV6T2Ops() &&
(Val <= 0xffff || // MOV
ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW
ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN
return 1;
if (Val <= 510) return 2; // MOV + ADDi8
if (~Val <= 255) return 2; // MOV + MVN
if (ARM_AM::isThumbImmShiftedVal(Val)) return 2; // MOV + LSL
} else {
if (ARM_AM::getSOImmVal(Val) != -1) return 1; // MOV
if (ARM_AM::getSOImmVal(~Val) != -1) return 1; // MVN
if (Subtarget->hasV6T2Ops() && Val <= 0xffff) return 1; // MOVW
if (ARM_AM::isSOImmTwoPartVal(Val)) return 2; // two instrs
}
if (Subtarget->useMovt()) return 2; // MOVW + MOVT
return 3; // Literal pool load
}
bool ARMDAGToDAGISel::canExtractShiftFromMul(const SDValue &N,
unsigned MaxShift,
unsigned &PowerOfTwo,
SDValue &NewMulConst) const {
assert(N.getOpcode() == ISD::MUL);
assert(MaxShift > 0);
// If the multiply is used in more than one place then changing the constant
// will make other uses incorrect, so don't.
if (!N.hasOneUse()) return false;
// Check if the multiply is by a constant
ConstantSDNode *MulConst = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!MulConst) return false;
// If the constant is used in more than one place then modifying it will mean
// we need to materialize two constants instead of one, which is a bad idea.
if (!MulConst->hasOneUse()) return false;
unsigned MulConstVal = MulConst->getZExtValue();
if (MulConstVal == 0) return false;
// Find the largest power of 2 that MulConstVal is a multiple of
PowerOfTwo = MaxShift;
while ((MulConstVal % (1 << PowerOfTwo)) != 0) {
--PowerOfTwo;
if (PowerOfTwo == 0) return false;
}
// Only optimise if the new cost is better
unsigned NewMulConstVal = MulConstVal / (1 << PowerOfTwo);
NewMulConst = CurDAG->getConstant(NewMulConstVal, SDLoc(N), MVT::i32);
unsigned OldCost = ConstantMaterializationCost(MulConstVal);
unsigned NewCost = ConstantMaterializationCost(NewMulConstVal);
return NewCost < OldCost;
}
void ARMDAGToDAGISel::replaceDAGValue(const SDValue &N, SDValue M) {
CurDAG->RepositionNode(N.getNode()->getIterator(), M.getNode());
ReplaceUses(N, M);
}
bool ARMDAGToDAGISel::SelectImmShifterOperand(SDValue N,
SDValue &BaseReg,
SDValue &Opc,
bool CheckProfitability) {
if (DisableShifterOp)
return false;
// If N is a multiply-by-constant and it's profitable to extract a shift and
// use it in a shifted operand do so.
if (N.getOpcode() == ISD::MUL) {
unsigned PowerOfTwo = 0;
SDValue NewMulConst;
if (canExtractShiftFromMul(N, 31, PowerOfTwo, NewMulConst)) {
HandleSDNode Handle(N);
SDLoc Loc(N);
replaceDAGValue(N.getOperand(1), NewMulConst);
BaseReg = Handle.getValue();
Opc = CurDAG->getTargetConstant(
ARM_AM::getSORegOpc(ARM_AM::lsl, PowerOfTwo), Loc, MVT::i32);
return true;
}
}
ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
// Don't match base register only case. That is matched to a separate
// lower complexity pattern with explicit register operand.
if (ShOpcVal == ARM_AM::no_shift) return false;
BaseReg = N.getOperand(0);
unsigned ShImmVal = 0;
ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!RHS) return false;
ShImmVal = RHS->getZExtValue() & 31;
Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectRegShifterOperand(SDValue N,
SDValue &BaseReg,
SDValue &ShReg,
SDValue &Opc,
bool CheckProfitability) {
if (DisableShifterOp)
return false;
ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
// Don't match base register only case. That is matched to a separate
// lower complexity pattern with explicit register operand.
if (ShOpcVal == ARM_AM::no_shift) return false;
BaseReg = N.getOperand(0);
unsigned ShImmVal = 0;
ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (RHS) return false;
ShReg = N.getOperand(1);
if (CheckProfitability && !isShifterOpProfitable(N, ShOpcVal, ShImmVal))
return false;
Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
SDLoc(N), MVT::i32);
return true;
}
// Determine whether an ISD::OR's operands are suitable to turn the operation
// into an addition, which often has more compact encodings.
bool ARMDAGToDAGISel::SelectAddLikeOr(SDNode *Parent, SDValue N, SDValue &Out) {
assert(Parent->getOpcode() == ISD::OR && "unexpected parent");
Out = N;
return CurDAG->haveNoCommonBitsSet(N, Parent->getOperand(1));
}
bool ARMDAGToDAGISel::SelectAddrModeImm12(SDValue N,
SDValue &Base,
SDValue &OffImm) {
// Match simple R + imm12 operands.
// Base only.
if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
!CurDAG->isBaseWithConstantOffset(N)) {
if (N.getOpcode() == ISD::FrameIndex) {
// Match frame index.
int FI = cast<FrameIndexSDNode>(N)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
if (N.getOpcode() == ARMISD::Wrapper &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
Base = N.getOperand(0);
} else
Base = N;
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
int RHSC = (int)RHS->getSExtValue();
if (N.getOpcode() == ISD::SUB)
RHSC = -RHSC;
if (RHSC > -0x1000 && RHSC < 0x1000) { // 12 bits
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
return true;
}
}
// Base only.
Base = N;
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset,
SDValue &Opc) {
if (N.getOpcode() == ISD::MUL &&
((!Subtarget->isLikeA9() && !Subtarget->isSwift()) || N.hasOneUse())) {
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
// X * [3,5,9] -> X + X * [2,4,8] etc.
int RHSC = (int)RHS->getZExtValue();
if (RHSC & 1) {
RHSC = RHSC & ~1;
ARM_AM::AddrOpc AddSub = ARM_AM::add;
if (RHSC < 0) {
AddSub = ARM_AM::sub;
RHSC = - RHSC;
}
if (isPowerOf2_32(RHSC)) {
unsigned ShAmt = Log2_32(RHSC);
Base = Offset = N.getOperand(0);
Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt,
ARM_AM::lsl),
SDLoc(N), MVT::i32);
return true;
}
}
}
}
if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
// ISD::OR that is equivalent to an ISD::ADD.
!CurDAG->isBaseWithConstantOffset(N))
return false;
// Leave simple R +/- imm12 operands for LDRi12
if (N.getOpcode() == ISD::ADD || N.getOpcode() == ISD::OR) {
int RHSC;
if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
-0x1000+1, 0x1000, RHSC)) // 12 bits.
return false;
}
// Otherwise this is R +/- [possibly shifted] R.
ARM_AM::AddrOpc AddSub = N.getOpcode() == ISD::SUB ? ARM_AM::sub:ARM_AM::add;
ARM_AM::ShiftOpc ShOpcVal =
ARM_AM::getShiftOpcForNode(N.getOperand(1).getOpcode());
unsigned ShAmt = 0;
Base = N.getOperand(0);
Offset = N.getOperand(1);
if (ShOpcVal != ARM_AM::no_shift) {
// Check to see if the RHS of the shift is a constant, if not, we can't fold
// it.
if (ConstantSDNode *Sh =
dyn_cast<ConstantSDNode>(N.getOperand(1).getOperand(1))) {
ShAmt = Sh->getZExtValue();
if (isShifterOpProfitable(Offset, ShOpcVal, ShAmt))
Offset = N.getOperand(1).getOperand(0);
else {
ShAmt = 0;
ShOpcVal = ARM_AM::no_shift;
}
} else {
ShOpcVal = ARM_AM::no_shift;
}
}
// Try matching (R shl C) + (R).
if (N.getOpcode() != ISD::SUB && ShOpcVal == ARM_AM::no_shift &&
!(Subtarget->isLikeA9() || Subtarget->isSwift() ||
N.getOperand(0).hasOneUse())) {
ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOperand(0).getOpcode());
if (ShOpcVal != ARM_AM::no_shift) {
// Check to see if the RHS of the shift is a constant, if not, we can't
// fold it.
if (ConstantSDNode *Sh =
dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) {
ShAmt = Sh->getZExtValue();
if (isShifterOpProfitable(N.getOperand(0), ShOpcVal, ShAmt)) {
Offset = N.getOperand(0).getOperand(0);
Base = N.getOperand(1);
} else {
ShAmt = 0;
ShOpcVal = ARM_AM::no_shift;
}
} else {
ShOpcVal = ARM_AM::no_shift;
}
}
}
// If Offset is a multiply-by-constant and it's profitable to extract a shift
// and use it in a shifted operand do so.
if (Offset.getOpcode() == ISD::MUL && N.hasOneUse()) {
unsigned PowerOfTwo = 0;
SDValue NewMulConst;
if (canExtractShiftFromMul(Offset, 31, PowerOfTwo, NewMulConst)) {
HandleSDNode Handle(Offset);
replaceDAGValue(Offset.getOperand(1), NewMulConst);
Offset = Handle.getValue();
ShAmt = PowerOfTwo;
ShOpcVal = ARM_AM::lsl;
}
}
Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc) {
unsigned Opcode = Op->getOpcode();
ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
? cast<LoadSDNode>(Op)->getAddressingMode()
: cast<StoreSDNode>(Op)->getAddressingMode();
ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
? ARM_AM::add : ARM_AM::sub;
int Val;
if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val))
return false;
Offset = N;
ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
unsigned ShAmt = 0;
if (ShOpcVal != ARM_AM::no_shift) {
// Check to see if the RHS of the shift is a constant, if not, we can't fold
// it.
if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
ShAmt = Sh->getZExtValue();
if (isShifterOpProfitable(N, ShOpcVal, ShAmt))
Offset = N.getOperand(0);
else {
ShAmt = 0;
ShOpcVal = ARM_AM::no_shift;
}
} else {
ShOpcVal = ARM_AM::no_shift;
}
}
Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc) {
unsigned Opcode = Op->getOpcode();
ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
? cast<LoadSDNode>(Op)->getAddressingMode()
: cast<StoreSDNode>(Op)->getAddressingMode();
ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
? ARM_AM::add : ARM_AM::sub;
int Val;
if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
if (AddSub == ARM_AM::sub) Val *= -1;
Offset = CurDAG->getRegister(0, MVT::i32);
Opc = CurDAG->getTargetConstant(Val, SDLoc(Op), MVT::i32);
return true;
}
return false;
}
bool ARMDAGToDAGISel::SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc) {
unsigned Opcode = Op->getOpcode();
ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
? cast<LoadSDNode>(Op)->getAddressingMode()
: cast<StoreSDNode>(Op)->getAddressingMode();
ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
? ARM_AM::add : ARM_AM::sub;
int Val;
if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
Offset = CurDAG->getRegister(0, MVT::i32);
Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, Val,
ARM_AM::no_shift),
SDLoc(Op), MVT::i32);
return true;
}
return false;
}
bool ARMDAGToDAGISel::SelectAddrOffsetNone(SDValue N, SDValue &Base) {
Base = N;
return true;
}
bool ARMDAGToDAGISel::SelectAddrMode3(SDValue N,
SDValue &Base, SDValue &Offset,
SDValue &Opc) {
if (N.getOpcode() == ISD::SUB) {
// X - C is canonicalize to X + -C, no need to handle it here.
Base = N.getOperand(0);
Offset = N.getOperand(1);
Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::sub, 0), SDLoc(N),
MVT::i32);
return true;
}
if (!CurDAG->isBaseWithConstantOffset(N)) {
Base = N;
if (N.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(N)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
Offset = CurDAG->getRegister(0, MVT::i32);
Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
MVT::i32);
return true;
}
// If the RHS is +/- imm8, fold into addr mode.
int RHSC;
if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
-256 + 1, 256, RHSC)) { // 8 bits.
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
Offset = CurDAG->getRegister(0, MVT::i32);
ARM_AM::AddrOpc AddSub = ARM_AM::add;
if (RHSC < 0) {
AddSub = ARM_AM::sub;
RHSC = -RHSC;
}
Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, RHSC), SDLoc(N),
MVT::i32);
return true;
}
Base = N.getOperand(0);
Offset = N.getOperand(1);
Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectAddrMode3Offset(SDNode *Op, SDValue N,
SDValue &Offset, SDValue &Opc) {
unsigned Opcode = Op->getOpcode();
ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
? cast<LoadSDNode>(Op)->getAddressingMode()
: cast<StoreSDNode>(Op)->getAddressingMode();
ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
? ARM_AM::add : ARM_AM::sub;
int Val;
if (isScaledConstantInRange(N, /*Scale=*/1, 0, 256, Val)) { // 12 bits.
Offset = CurDAG->getRegister(0, MVT::i32);
Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, Val), SDLoc(Op),
MVT::i32);
return true;
}
Offset = N;
Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, 0), SDLoc(Op),
MVT::i32);
return true;
}
bool ARMDAGToDAGISel::IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset,
bool FP16) {
if (!CurDAG->isBaseWithConstantOffset(N)) {
Base = N;
if (N.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(N)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
} else if (N.getOpcode() == ARMISD::Wrapper &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
Base = N.getOperand(0);
}
Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
SDLoc(N), MVT::i32);
return true;
}
// If the RHS is +/- imm8, fold into addr mode.
int RHSC;
const int Scale = FP16 ? 2 : 4;
if (isScaledConstantInRange(N.getOperand(1), Scale, -255, 256, RHSC)) {
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
ARM_AM::AddrOpc AddSub = ARM_AM::add;
if (RHSC < 0) {
AddSub = ARM_AM::sub;
RHSC = -RHSC;
}
if (FP16)
Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(AddSub, RHSC),
SDLoc(N), MVT::i32);
else
Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(AddSub, RHSC),
SDLoc(N), MVT::i32);
return true;
}
Base = N;
if (FP16)
Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(ARM_AM::add, 0),
SDLoc(N), MVT::i32);
else
Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectAddrMode5(SDValue N,
SDValue &Base, SDValue &Offset) {
return IsAddressingMode5(N, Base, Offset, /*FP16=*/ false);
}
bool ARMDAGToDAGISel::SelectAddrMode5FP16(SDValue N,
SDValue &Base, SDValue &Offset) {
return IsAddressingMode5(N, Base, Offset, /*FP16=*/ true);
}
bool ARMDAGToDAGISel::SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,
SDValue &Align) {
Addr = N;
unsigned Alignment = 0;
MemSDNode *MemN = cast<MemSDNode>(Parent);
if (isa<LSBaseSDNode>(MemN) ||
((MemN->getOpcode() == ARMISD::VST1_UPD ||
MemN->getOpcode() == ARMISD::VLD1_UPD) &&
MemN->getConstantOperandVal(MemN->getNumOperands() - 1) == 1)) {
// This case occurs only for VLD1-lane/dup and VST1-lane instructions.
// The maximum alignment is equal to the memory size being referenced.
unsigned MMOAlign = MemN->getAlignment();
unsigned MemSize = MemN->getMemoryVT().getSizeInBits() / 8;
if (MMOAlign >= MemSize && MemSize > 1)
Alignment = MemSize;
} else {
// All other uses of addrmode6 are for intrinsics. For now just record
// the raw alignment value; it will be refined later based on the legal
// alignment operands for the intrinsic.
Alignment = MemN->getAlignment();
}
Align = CurDAG->getTargetConstant(Alignment, SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectAddrMode6Offset(SDNode *Op, SDValue N,
SDValue &Offset) {
LSBaseSDNode *LdSt = cast<LSBaseSDNode>(Op);
ISD::MemIndexedMode AM = LdSt->getAddressingMode();
if (AM != ISD::POST_INC)
return false;
Offset = N;
if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(N)) {
if (NC->getZExtValue() * 8 == LdSt->getMemoryVT().getSizeInBits())
Offset = CurDAG->getRegister(0, MVT::i32);
}
return true;
}
bool ARMDAGToDAGISel::SelectAddrModePC(SDValue N,
SDValue &Offset, SDValue &Label) {
if (N.getOpcode() == ARMISD::PIC_ADD && N.hasOneUse()) {
Offset = N.getOperand(0);
SDValue N1 = N.getOperand(1);
Label = CurDAG->getTargetConstant(cast<ConstantSDNode>(N1)->getZExtValue(),
SDLoc(N), MVT::i32);
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// Thumb Addressing Modes
//===----------------------------------------------------------------------===//
static bool shouldUseZeroOffsetLdSt(SDValue N) {
// Negative numbers are difficult to materialise in thumb1. If we are
// selecting the add of a negative, instead try to select ri with a zero
// offset, so create the add node directly which will become a sub.
if (N.getOpcode() != ISD::ADD)
return false;
// Look for an imm which is not legal for ld/st, but is legal for sub.
if (auto C = dyn_cast<ConstantSDNode>(N.getOperand(1)))
return C->getSExtValue() < 0 && C->getSExtValue() >= -255;
return false;
}
bool ARMDAGToDAGISel::SelectThumbAddrModeRRSext(SDValue N, SDValue &Base,
SDValue &Offset) {
if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N)) {
ConstantSDNode *NC = dyn_cast<ConstantSDNode>(N);
if (!NC || !NC->isNullValue())
return false;
Base = Offset = N;
return true;
}
Base = N.getOperand(0);
Offset = N.getOperand(1);
return true;
}
bool ARMDAGToDAGISel::SelectThumbAddrModeRR(SDValue N, SDValue &Base,
SDValue &Offset) {
if (shouldUseZeroOffsetLdSt(N))
return false; // Select ri instead
return SelectThumbAddrModeRRSext(N, Base, Offset);
}
bool
ARMDAGToDAGISel::SelectThumbAddrModeImm5S(SDValue N, unsigned Scale,
SDValue &Base, SDValue &OffImm) {
if (shouldUseZeroOffsetLdSt(N)) {
Base = N;
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
if (!CurDAG->isBaseWithConstantOffset(N)) {
if (N.getOpcode() == ISD::ADD) {
return false; // We want to select register offset instead
} else if (N.getOpcode() == ARMISD::Wrapper &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
N.getOperand(0).getOpcode() != ISD::TargetConstantPool &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
Base = N.getOperand(0);
} else {
Base = N;
}
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
// If the RHS is + imm5 * scale, fold into addr mode.
int RHSC;
if (isScaledConstantInRange(N.getOperand(1), Scale, 0, 32, RHSC)) {
Base = N.getOperand(0);
OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
return true;
}
// Offset is too large, so use register offset instead.
return false;
}
bool
ARMDAGToDAGISel::SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
SDValue &OffImm) {
return SelectThumbAddrModeImm5S(N, 4, Base, OffImm);
}
bool
ARMDAGToDAGISel::SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
SDValue &OffImm) {
return SelectThumbAddrModeImm5S(N, 2, Base, OffImm);
}
bool
ARMDAGToDAGISel::SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
SDValue &OffImm) {
return SelectThumbAddrModeImm5S(N, 1, Base, OffImm);
}
bool ARMDAGToDAGISel::SelectThumbAddrModeSP(SDValue N,
SDValue &Base, SDValue &OffImm) {
if (N.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(N)->getIndex();
// Only multiples of 4 are allowed for the offset, so the frame object
// alignment must be at least 4.
MachineFrameInfo &MFI = MF->getFrameInfo();
if (MFI.getObjectAlignment(FI) < 4)
MFI.setObjectAlignment(FI, 4);
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
if (!CurDAG->isBaseWithConstantOffset(N))
return false;
if (N.getOperand(0).getOpcode() == ISD::FrameIndex) {
// If the RHS is + imm8 * scale, fold into addr mode.
int RHSC;
if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/4, 0, 256, RHSC)) {
Base = N.getOperand(0);
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
// For LHS+RHS to result in an offset that's a multiple of 4 the object
// indexed by the LHS must be 4-byte aligned.
MachineFrameInfo &MFI = MF->getFrameInfo();
if (MFI.getObjectAlignment(FI) < 4)
MFI.setObjectAlignment(FI, 4);
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
return true;
}
}
return false;
}
//===----------------------------------------------------------------------===//
// Thumb 2 Addressing Modes
//===----------------------------------------------------------------------===//
bool ARMDAGToDAGISel::SelectT2AddrModeImm12(SDValue N,
SDValue &Base, SDValue &OffImm) {
// Match simple R + imm12 operands.
// Base only.
if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
!CurDAG->isBaseWithConstantOffset(N)) {
if (N.getOpcode() == ISD::FrameIndex) {
// Match frame index.
int FI = cast<FrameIndexSDNode>(N)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
if (N.getOpcode() == ARMISD::Wrapper &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::TargetConstantPool)
return false; // We want to select t2LDRpci instead.
} else
Base = N;
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
if (SelectT2AddrModeImm8(N, Base, OffImm))
// Let t2LDRi8 handle (R - imm8).
return false;
int RHSC = (int)RHS->getZExtValue();
if (N.getOpcode() == ISD::SUB)
RHSC = -RHSC;
if (RHSC >= 0 && RHSC < 0x1000) { // 12 bits (unsigned)
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
return true;
}
}
// Base only.
Base = N;
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectT2AddrModeImm8(SDValue N,
SDValue &Base, SDValue &OffImm) {
// Match simple R - imm8 operands.
if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
!CurDAG->isBaseWithConstantOffset(N))
return false;
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
int RHSC = (int)RHS->getSExtValue();
if (N.getOpcode() == ISD::SUB)
RHSC = -RHSC;
if ((RHSC >= -255) && (RHSC < 0)) { // 8 bits (always negative)
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
return true;
}
}
return false;
}
bool ARMDAGToDAGISel::SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
SDValue &OffImm){
unsigned Opcode = Op->getOpcode();
ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
? cast<LoadSDNode>(Op)->getAddressingMode()
: cast<StoreSDNode>(Op)->getAddressingMode();
int RHSC;
if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x100, RHSC)) { // 8 bits.
OffImm = ((AM == ISD::PRE_INC) || (AM == ISD::POST_INC))
? CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32)
: CurDAG->getTargetConstant(-RHSC, SDLoc(N), MVT::i32);
return true;
}
return false;
}
bool ARMDAGToDAGISel::SelectT2AddrModeSoReg(SDValue N,
SDValue &Base,
SDValue &OffReg, SDValue &ShImm) {
// (R - imm8) should be handled by t2LDRi8. The rest are handled by t2LDRi12.
if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N))
return false;
// Leave (R + imm12) for t2LDRi12, (R - imm8) for t2LDRi8.
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
int RHSC = (int)RHS->getZExtValue();
if (RHSC >= 0 && RHSC < 0x1000) // 12 bits (unsigned)
return false;
else if (RHSC < 0 && RHSC >= -255) // 8 bits
return false;
}
// Look for (R + R) or (R + (R << [1,2,3])).
unsigned ShAmt = 0;
Base = N.getOperand(0);
OffReg = N.getOperand(1);
// Swap if it is ((R << c) + R).
ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(OffReg.getOpcode());
if (ShOpcVal != ARM_AM::lsl) {
ShOpcVal = ARM_AM::getShiftOpcForNode(Base.getOpcode());
if (ShOpcVal == ARM_AM::lsl)
std::swap(Base, OffReg);
}
if (ShOpcVal == ARM_AM::lsl) {
// Check to see if the RHS of the shift is a constant, if not, we can't fold
// it.
if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(OffReg.getOperand(1))) {
ShAmt = Sh->getZExtValue();
if (ShAmt < 4 && isShifterOpProfitable(OffReg, ShOpcVal, ShAmt))
OffReg = OffReg.getOperand(0);
else {
ShAmt = 0;
}
}
}
// If OffReg is a multiply-by-constant and it's profitable to extract a shift
// and use it in a shifted operand do so.
if (OffReg.getOpcode() == ISD::MUL && N.hasOneUse()) {
unsigned PowerOfTwo = 0;
SDValue NewMulConst;
if (canExtractShiftFromMul(OffReg, 3, PowerOfTwo, NewMulConst)) {
HandleSDNode Handle(OffReg);
replaceDAGValue(OffReg.getOperand(1), NewMulConst);
OffReg = Handle.getValue();
ShAmt = PowerOfTwo;
}
}
ShImm = CurDAG->getTargetConstant(ShAmt, SDLoc(N), MVT::i32);
return true;
}
bool ARMDAGToDAGISel::SelectT2AddrModeExclusive(SDValue N, SDValue &Base,
SDValue &OffImm) {
// This *must* succeed since it's used for the irreplaceable ldrex and strex
// instructions.
Base = N;
OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
if (N.getOpcode() != ISD::ADD || !CurDAG->isBaseWithConstantOffset(N))
return true;
ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!RHS)
return true;
uint32_t RHSC = (int)RHS->getZExtValue();
if (RHSC > 1020 || RHSC % 4 != 0)
return true;
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
OffImm = CurDAG->getTargetConstant(RHSC/4, SDLoc(N), MVT::i32);
return true;
}
//===--------------------------------------------------------------------===//
/// getAL - Returns a ARMCC::AL immediate node.
static inline SDValue getAL(SelectionDAG *CurDAG, const SDLoc &dl) {
return CurDAG->getTargetConstant((uint64_t)ARMCC::AL, dl, MVT::i32);
}
void ARMDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
}
bool ARMDAGToDAGISel::tryARMIndexedLoad(SDNode *N) {
LoadSDNode *LD = cast<LoadSDNode>(N);
ISD::MemIndexedMode AM = LD->getAddressingMode();
if (AM == ISD::UNINDEXED)
return false;
EVT LoadedVT = LD->getMemoryVT();
SDValue Offset, AMOpc;
bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
unsigned Opcode = 0;
bool Match = false;
if (LoadedVT == MVT::i32 && isPre &&
SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
Opcode = ARM::LDR_PRE_IMM;
Match = true;
} else if (LoadedVT == MVT::i32 && !isPre &&
SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
Opcode = ARM::LDR_POST_IMM;
Match = true;
} else if (LoadedVT == MVT::i32 &&
SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
Opcode = isPre ? ARM::LDR_PRE_REG : ARM::LDR_POST_REG;
Match = true;
} else if (LoadedVT == MVT::i16 &&
SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
Match = true;
Opcode = (LD->getExtensionType() == ISD::SEXTLOAD)
? (isPre ? ARM::LDRSH_PRE : ARM::LDRSH_POST)
: (isPre ? ARM::LDRH_PRE : ARM::LDRH_POST);
} else if (LoadedVT == MVT::i8 || LoadedVT == MVT::i1) {
if (LD->getExtensionType() == ISD::SEXTLOAD) {
if (SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
Match = true;
Opcode = isPre ? ARM::LDRSB_PRE : ARM::LDRSB_POST;
}
} else {
if (isPre &&
SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
Match = true;
Opcode = ARM::LDRB_PRE_IMM;
} else if (!isPre &&
SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
Match = true;
Opcode = ARM::LDRB_POST_IMM;
} else if (SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
Match = true;
Opcode = isPre ? ARM::LDRB_PRE_REG : ARM::LDRB_POST_REG;
}
}
}
if (Match) {
if (Opcode == ARM::LDR_PRE_IMM || Opcode == ARM::LDRB_PRE_IMM) {
SDValue Chain = LD->getChain();
SDValue Base = LD->getBasePtr();
SDValue Ops[]= { Base, AMOpc, getAL(CurDAG, SDLoc(N)),
CurDAG->getRegister(0, MVT::i32), Chain };
SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
MVT::Other, Ops);
transferMemOperands(N, New);
ReplaceNode(N, New);
return true;
} else {
SDValue Chain = LD->getChain();
SDValue Base = LD->getBasePtr();
SDValue Ops[]= { Base, Offset, AMOpc, getAL(CurDAG, SDLoc(N)),
CurDAG->getRegister(0, MVT::i32), Chain };
SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
MVT::Other, Ops);
transferMemOperands(N, New);
ReplaceNode(N, New);
return true;
}
}
return false;
}
bool ARMDAGToDAGISel::tryT1IndexedLoad(SDNode *N) {
LoadSDNode *LD = cast<LoadSDNode>(N);
EVT LoadedVT = LD->getMemoryVT();
ISD::MemIndexedMode AM = LD->getAddressingMode();
if (AM != ISD::POST_INC || LD->getExtensionType() != ISD::NON_EXTLOAD ||
LoadedVT.getSimpleVT().SimpleTy != MVT::i32)
return false;
auto *COffs = dyn_cast<ConstantSDNode>(LD->getOffset());
if (!COffs || COffs->getZExtValue() != 4)
return false;
// A T1 post-indexed load is just a single register LDM: LDM r0!, {r1}.
// The encoding of LDM is not how the rest of ISel expects a post-inc load to
// look however, so we use a pseudo here and switch it for a tLDMIA_UPD after
// ISel.
SDValue Chain = LD->getChain();
SDValue Base = LD->getBasePtr();
SDValue Ops[]= { Base, getAL(CurDAG, SDLoc(N)),
CurDAG->getRegister(0, MVT::i32), Chain };
SDNode *New = CurDAG->getMachineNode(ARM::tLDR_postidx, SDLoc(N), MVT::i32,
MVT::i32, MVT::Other, Ops);
transferMemOperands(N, New);
ReplaceNode(N, New);
return true;
}
bool ARMDAGToDAGISel::tryT2IndexedLoad(SDNode *N) {
LoadSDNode *LD = cast<LoadSDNode>(N);
ISD::MemIndexedMode AM = LD->getAddressingMode();
if (AM == ISD::UNINDEXED)
return false;
EVT LoadedVT = LD->getMemoryVT();
bool isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
SDValue Offset;
bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
unsigned Opcode = 0;
bool Match = false;
if (SelectT2AddrModeImm8Offset(N, LD->getOffset(), Offset)) {
switch (LoadedVT.getSimpleVT().SimpleTy) {
case MVT::i32:
Opcode = isPre ? ARM::t2LDR_PRE : ARM::t2LDR_POST;
break;
case MVT::i16:
if (isSExtLd)
Opcode = isPre ? ARM::t2LDRSH_PRE : ARM::t2LDRSH_POST;
else
Opcode = isPre ? ARM::t2LDRH_PRE : ARM::t2LDRH_POST;
break;
case MVT::i8:
case MVT::i1:
if (isSExtLd)
Opcode = isPre ? ARM::t2LDRSB_PRE : ARM::t2LDRSB_POST;
else
Opcode = isPre ? ARM::t2LDRB_PRE : ARM::t2LDRB_POST;
break;
default:
return false;
}
Match = true;
}
if (Match) {
SDValue Chain = LD->getChain();
SDValue Base = LD->getBasePtr();
SDValue Ops[]= { Base, Offset, getAL(CurDAG, SDLoc(N)),
CurDAG->getRegister(0, MVT::i32), Chain };
SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
MVT::Other, Ops);
transferMemOperands(N, New);
ReplaceNode(N, New);
return true;
}
return false;
}
/// Form a GPRPair pseudo register from a pair of GPR regs.
SDNode *ARMDAGToDAGISel::createGPRPairNode(EVT VT, SDValue V0, SDValue V1) {
SDLoc dl(V0.getNode());
SDValue RegClass =
CurDAG->getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
SDValue SubReg0 = CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
SDValue SubReg1 = CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
}
/// Form a D register from a pair of S registers.
SDNode *ARMDAGToDAGISel::createSRegPairNode(EVT VT, SDValue V0, SDValue V1) {
SDLoc dl(V0.getNode());
SDValue RegClass =
CurDAG->getTargetConstant(ARM::DPR_VFP2RegClassID, dl, MVT::i32);
SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
}
/// Form a quad register from a pair of D registers.
SDNode *ARMDAGToDAGISel::createDRegPairNode(EVT VT, SDValue V0, SDValue V1) {
SDLoc dl(V0.getNode());
SDValue RegClass = CurDAG->getTargetConstant(ARM::QPRRegClassID, dl,
MVT::i32);
SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
}
/// Form 4 consecutive D registers from a pair of Q registers.
SDNode *ARMDAGToDAGISel::createQRegPairNode(EVT VT, SDValue V0, SDValue V1) {
SDLoc dl(V0.getNode());
SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
MVT::i32);
SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
}
/// Form 4 consecutive S registers.
SDNode *ARMDAGToDAGISel::createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1,
SDValue V2, SDValue V3) {
SDLoc dl(V0.getNode());
SDValue RegClass =
CurDAG->getTargetConstant(ARM::QPR_VFP2RegClassID, dl, MVT::i32);
SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
SDValue SubReg2 = CurDAG->getTargetConstant(ARM::ssub_2, dl, MVT::i32);
SDValue SubReg3 = CurDAG->getTargetConstant(ARM::ssub_3, dl, MVT::i32);
const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
V2, SubReg2, V3, SubReg3 };
return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
}
/// Form 4 consecutive D registers.
SDNode *ARMDAGToDAGISel::createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1,
SDValue V2, SDValue V3) {
SDLoc dl(V0.getNode());
SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
MVT::i32);
SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
SDValue SubReg2 = CurDAG->getTargetConstant(ARM::dsub_2, dl, MVT::i32);
SDValue SubReg3 = CurDAG->getTargetConstant(ARM::dsub_3, dl, MVT::i32);
const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
V2, SubReg2, V3, SubReg3 };
return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
}
/// Form 4 consecutive Q registers.
SDNode *ARMDAGToDAGISel::createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1,
SDValue V2, SDValue V3) {
SDLoc dl(V0.getNode());
SDValue RegClass = CurDAG->getTargetConstant(ARM::QQQQPRRegClassID, dl,
MVT::i32);
SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
SDValue SubReg2 = CurDAG->getTargetConstant(ARM::qsub_2, dl, MVT::i32);
SDValue SubReg3 = CurDAG->getTargetConstant(ARM::qsub_3, dl, MVT::i32);
const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
V2, SubReg2, V3, SubReg3 };
return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
}
/// GetVLDSTAlign - Get the alignment (in bytes) for the alignment operand
/// of a NEON VLD or VST instruction. The supported values depend on the
/// number of registers being loaded.
SDValue ARMDAGToDAGISel::GetVLDSTAlign(SDValue Align, const SDLoc &dl,
unsigned NumVecs, bool is64BitVector) {
unsigned NumRegs = NumVecs;
if (!is64BitVector && NumVecs < 3)
NumRegs *= 2;
unsigned Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
if (Alignment >= 32 && NumRegs == 4)
Alignment = 32;
else if (Alignment >= 16 && (NumRegs == 2 || NumRegs == 4))
Alignment = 16;
else if (Alignment >= 8)
Alignment = 8;
else
Alignment = 0;
return CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
}
static bool isVLDfixed(unsigned Opc)
{
switch (Opc) {
default: return false;
case ARM::VLD1d8wb_fixed : return true;
case ARM::VLD1d16wb_fixed : return true;
case ARM::VLD1d64Qwb_fixed : return true;
case ARM::VLD1d32wb_fixed : return true;
case ARM::VLD1d64wb_fixed : return true;
case ARM::VLD1d64TPseudoWB_fixed : return true;
case ARM::VLD1d64QPseudoWB_fixed : return true;
case ARM::VLD1q8wb_fixed : return true;
case ARM::VLD1q16wb_fixed : return true;
case ARM::VLD1q32wb_fixed : return true;
case ARM::VLD1q64wb_fixed : return true;
case ARM::VLD1DUPd8wb_fixed : return true;
case ARM::VLD1DUPd16wb_fixed : return true;
case ARM::VLD1DUPd32wb_fixed : return true;
case ARM::VLD1DUPq8wb_fixed : return true;
case ARM::VLD1DUPq16wb_fixed : return true;
case ARM::VLD1DUPq32wb_fixed : return true;
case ARM::VLD2d8wb_fixed : return true;
case ARM::VLD2d16wb_fixed : return true;
case ARM::VLD2d32wb_fixed : return true;
case ARM::VLD2q8PseudoWB_fixed : return true;
case ARM::VLD2q16PseudoWB_fixed : return true;
case ARM::VLD2q32PseudoWB_fixed : return true;
case ARM::VLD2DUPd8wb_fixed : return true;
case ARM::VLD2DUPd16wb_fixed : return true;
case ARM::VLD2DUPd32wb_fixed : return true;
}
}
static bool isVSTfixed(unsigned Opc)
{
switch (Opc) {
default: return false;
case ARM::VST1d8wb_fixed : return true;
case ARM::VST1d16wb_fixed : return true;
case ARM::VST1d32wb_fixed : return true;
case ARM::VST1d64wb_fixed : return true;
case ARM::VST1q8wb_fixed : return true;
case ARM::VST1q16wb_fixed : return true;
case ARM::VST1q32wb_fixed : return true;
case ARM::VST1q64wb_fixed : return true;
case ARM::VST1d64TPseudoWB_fixed : return true;
case ARM::VST1d64QPseudoWB_fixed : return true;
case ARM::VST2d8wb_fixed : return true;
case ARM::VST2d16wb_fixed : return true;
case ARM::VST2d32wb_fixed : return true;
case ARM::VST2q8PseudoWB_fixed : return true;
case ARM::VST2q16PseudoWB_fixed : return true;
case ARM::VST2q32PseudoWB_fixed : return true;
}
}
// Get the register stride update opcode of a VLD/VST instruction that
// is otherwise equivalent to the given fixed stride updating instruction.
static unsigned getVLDSTRegisterUpdateOpcode(unsigned Opc) {
assert((isVLDfixed(Opc) || isVSTfixed(Opc))
&& "Incorrect fixed stride updating instruction.");
switch (Opc) {
default: break;
case ARM::VLD1d8wb_fixed: return ARM::VLD1d8wb_register;
case ARM::VLD1d16wb_fixed: return ARM::VLD1d16wb_register;
case ARM::VLD1d32wb_fixed: return ARM::VLD1d32wb_register;
case ARM::VLD1d64wb_fixed: return ARM::VLD1d64wb_register;
case ARM::VLD1q8wb_fixed: return ARM::VLD1q8wb_register;
case ARM::VLD1q16wb_fixed: return ARM::VLD1q16wb_register;
case ARM::VLD1q32wb_fixed: return ARM::VLD1q32wb_register;
case ARM::VLD1q64wb_fixed: return ARM::VLD1q64wb_register;
case ARM::VLD1d64Twb_fixed: return ARM::VLD1d64Twb_register;
case ARM::VLD1d64Qwb_fixed: return ARM::VLD1d64Qwb_register;
case ARM::VLD1d64TPseudoWB_fixed: return ARM::VLD1d64TPseudoWB_register;
case ARM::VLD1d64QPseudoWB_fixed: return ARM::VLD1d64QPseudoWB_register;
case ARM::VLD1DUPd8wb_fixed : return ARM::VLD1DUPd8wb_register;
case ARM::VLD1DUPd16wb_fixed : return ARM::VLD1DUPd16wb_register;
case ARM::VLD1DUPd32wb_fixed : return ARM::VLD1DUPd32wb_register;
case ARM::VLD1DUPq8wb_fixed : return ARM::VLD1DUPq8wb_register;
case ARM::VLD1DUPq16wb_fixed : return ARM::VLD1DUPq16wb_register;
case ARM::VLD1DUPq32wb_fixed : return ARM::VLD1DUPq32wb_register;
case ARM::VST1d8wb_fixed: return ARM::VST1d8wb_register;
case ARM::VST1d16wb_fixed: return ARM::VST1d16wb_register;
case ARM::VST1d32wb_fixed: return ARM::VST1d32wb_register;
case ARM::VST1d64wb_fixed: return ARM::VST1d64wb_register;
case ARM::VST1q8wb_fixed: return ARM::VST1q8wb_register;
case ARM::VST1q16wb_fixed: return ARM::VST1q16wb_register;
case ARM::VST1q32wb_fixed: return ARM::VST1q32wb_register;
case ARM::VST1q64wb_fixed: return ARM::VST1q64wb_register;
case ARM::VST1d64TPseudoWB_fixed: return ARM::VST1d64TPseudoWB_register;
case ARM::VST1d64QPseudoWB_fixed: return ARM::VST1d64QPseudoWB_register;
case ARM::VLD2d8wb_fixed: return ARM::VLD2d8wb_register;
case ARM::VLD2d16wb_fixed: return ARM::VLD2d16wb_register;
case ARM::VLD2d32wb_fixed: return ARM::VLD2d32wb_register;
case ARM::VLD2q8PseudoWB_fixed: return ARM::VLD2q8PseudoWB_register;
case ARM::VLD2q16PseudoWB_fixed: return ARM::VLD2q16PseudoWB_register;
case ARM::VLD2q32PseudoWB_fixed: return ARM::VLD2q32PseudoWB_register;
case ARM::VST2d8wb_fixed: return ARM::VST2d8wb_register;
case ARM::VST2d16wb_fixed: return ARM::VST2d16wb_register;
case ARM::VST2d32wb_fixed: return ARM::VST2d32wb_register;
case ARM::VST2q8PseudoWB_fixed: return ARM::VST2q8PseudoWB_register;
case ARM::VST2q16PseudoWB_fixed: return ARM::VST2q16PseudoWB_register;
case ARM::VST2q32PseudoWB_fixed: return ARM::VST2q32PseudoWB_register;
case ARM::VLD2DUPd8wb_fixed: return ARM::VLD2DUPd8wb_register;
case ARM::VLD2DUPd16wb_fixed: return ARM::VLD2DUPd16wb_register;
case ARM::VLD2DUPd32wb_fixed: return ARM::VLD2DUPd32wb_register;
}
return Opc; // If not one we handle, return it unchanged.
}
/// Returns true if the given increment is a Constant known to be equal to the
/// access size performed by a NEON load/store. This means the "[rN]!" form can
/// be used.
static bool isPerfectIncrement(SDValue Inc, EVT VecTy, unsigned NumVecs) {
auto C = dyn_cast<ConstantSDNode>(Inc);
return C && C->getZExtValue() == VecTy.getSizeInBits() / 8 * NumVecs;
}
void ARMDAGToDAGISel::SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
const uint16_t *DOpcodes,
const uint16_t *QOpcodes0,
const uint16_t *QOpcodes1) {
assert(NumVecs >= 1 && NumVecs <= 4 && "VLD NumVecs out-of-range");
SDLoc dl(N);
SDValue MemAddr, Align;
bool IsIntrinsic = !isUpdating; // By coincidence, all supported updating
// nodes are not intrinsics.
unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
return;
SDValue Chain = N->getOperand(0);
EVT VT = N->getValueType(0);
bool is64BitVector = VT.is64BitVector();
Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
unsigned OpcodeIndex;
switch (VT.getSimpleVT().SimpleTy) {
default: llvm_unreachable("unhandled vld type");
// Double-register operations:
case MVT::v8i8: OpcodeIndex = 0; break;
case MVT::v4f16:
case MVT::v4i16: OpcodeIndex = 1; break;
case MVT::v2f32:
case MVT::v2i32: OpcodeIndex = 2; break;
case MVT::v1i64: OpcodeIndex = 3; break;
// Quad-register operations:
case MVT::v16i8: OpcodeIndex = 0; break;
case MVT::v8f16:
case MVT::v8i16: OpcodeIndex = 1; break;
case MVT::v4f32:
case MVT::v4i32: OpcodeIndex = 2; break;
case MVT::v2f64:
case MVT::v2i64: OpcodeIndex = 3; break;
}
EVT ResTy;
if (NumVecs == 1)
ResTy = VT;
else {
unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
if (!is64BitVector)
ResTyElts *= 2;
ResTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, ResTyElts);
}
std::vector<EVT> ResTys;
ResTys.push_back(ResTy);
if (isUpdating)
ResTys.push_back(MVT::i32);
ResTys.push_back(MVT::Other);
SDValue Pred = getAL(CurDAG, dl);
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
SDNode *VLd;
SmallVector<SDValue, 7> Ops;
// Double registers and VLD1/VLD2 quad registers are directly supported.
if (is64BitVector || NumVecs <= 2) {
unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
QOpcodes0[OpcodeIndex]);
Ops.push_back(MemAddr);
Ops.push_back(Align);
if (isUpdating) {
SDValue Inc = N->getOperand(AddrOpIdx + 1);
bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
if (!IsImmUpdate) {
// We use a VLD1 for v1i64 even if the pseudo says vld2/3/4, so
// check for the opcode rather than the number of vector elements.
if (isVLDfixed(Opc))
Opc = getVLDSTRegisterUpdateOpcode(Opc);
Ops.push_back(Inc);
// VLD1/VLD2 fixed increment does not need Reg0 so only include it in
// the operands if not such an opcode.
} else if (!isVLDfixed(Opc))
Ops.push_back(Reg0);
}
Ops.push_back(Pred);
Ops.push_back(Reg0);
Ops.push_back(Chain);
VLd = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
} else {
// Otherwise, quad registers are loaded with two separate instructions,
// where one loads the even registers and the other loads the odd registers.
EVT AddrTy = MemAddr.getValueType();
// Load the even subregs. This is always an updating load, so that it
// provides the address to the second load for the odd subregs.
SDValue ImplDef =
SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, ResTy), 0);
const SDValue OpsA[] = { MemAddr, Align, Reg0, ImplDef, Pred, Reg0, Chain };
SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
ResTy, AddrTy, MVT::Other, OpsA);
Chain = SDValue(VLdA, 2);
// Load the odd subregs.
Ops.push_back(SDValue(VLdA, 1));
Ops.push_back(Align);
if (isUpdating) {
SDValue Inc = N->getOperand(AddrOpIdx + 1);
assert(isa<ConstantSDNode>(Inc.getNode()) &&
"only constant post-increment update allowed for VLD3/4");
(void)Inc;
Ops.push_back(Reg0);
}
Ops.push_back(SDValue(VLdA, 0));
Ops.push_back(Pred);
Ops.push_back(Reg0);
Ops.push_back(Chain);
VLd = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys, Ops);
}
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLd), {MemOp});
if (NumVecs == 1) {
ReplaceNode(N, VLd);
return;
}
// Extract out the subregisters.
SDValue SuperReg = SDValue(VLd, 0);
static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
ARM::qsub_3 == ARM::qsub_0 + 3,
"Unexpected subreg numbering");
unsigned Sub0 = (is64BitVector ? ARM::dsub_0 : ARM::qsub_0);
for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
ReplaceUses(SDValue(N, Vec),
CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
ReplaceUses(SDValue(N, NumVecs), SDValue(VLd, 1));
if (isUpdating)
ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLd, 2));
CurDAG->RemoveDeadNode(N);
}
void ARMDAGToDAGISel::SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
const uint16_t *DOpcodes,
const uint16_t *QOpcodes0,
const uint16_t *QOpcodes1) {
assert(NumVecs >= 1 && NumVecs <= 4 && "VST NumVecs out-of-range");
SDLoc dl(N);
SDValue MemAddr, Align;
bool IsIntrinsic = !isUpdating; // By coincidence, all supported updating
// nodes are not intrinsics.
unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
return;
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
SDValue Chain = N->getOperand(0);
EVT VT = N->getOperand(Vec0Idx).getValueType();
bool is64BitVector = VT.is64BitVector();
Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
unsigned OpcodeIndex;
switch (VT.getSimpleVT().SimpleTy) {
default: llvm_unreachable("unhandled vst type");
// Double-register operations:
case MVT::v8i8: OpcodeIndex = 0; break;
case MVT::v4f16:
case MVT::v4i16: OpcodeIndex = 1; break;
case MVT::v2f32:
case MVT::v2i32: OpcodeIndex = 2; break;
case MVT::v1i64: OpcodeIndex = 3; break;
// Quad-register operations:
case MVT::v16i8: OpcodeIndex = 0; break;
case MVT::v8f16:
case MVT::v8i16: OpcodeIndex = 1; break;
case MVT::v4f32:
case MVT::v4i32: OpcodeIndex = 2; break;
case MVT::v2f64:
case MVT::v2i64: OpcodeIndex = 3; break;
}
std::vector<EVT> ResTys;
if (isUpdating)
ResTys.push_back(MVT::i32);
ResTys.push_back(MVT::Other);
SDValue Pred = getAL(CurDAG, dl);
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
SmallVector<SDValue, 7> Ops;
// Double registers and VST1/VST2 quad registers are directly supported.
if (is64BitVector || NumVecs <= 2) {
SDValue SrcReg;
if (NumVecs == 1) {
SrcReg = N->getOperand(Vec0Idx);
} else if (is64BitVector) {
// Form a REG_SEQUENCE to force register allocation.
SDValue V0 = N->getOperand(Vec0Idx + 0);
SDValue V1 = N->getOperand(Vec0Idx + 1);
if (NumVecs == 2)
SrcReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
else {
SDValue V2 = N->getOperand(Vec0Idx + 2);
// If it's a vst3, form a quad D-register and leave the last part as
// an undef.
SDValue V3 = (NumVecs == 3)
? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,dl,VT), 0)
: N->getOperand(Vec0Idx + 3);
SrcReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
}
} else {
// Form a QQ register.
SDValue Q0 = N->getOperand(Vec0Idx);
SDValue Q1 = N->getOperand(Vec0Idx + 1);
SrcReg = SDValue(createQRegPairNode(MVT::v4i64, Q0, Q1), 0);
}
unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
QOpcodes0[OpcodeIndex]);
Ops.push_back(MemAddr);
Ops.push_back(Align);
if (isUpdating) {
SDValue Inc = N->getOperand(AddrOpIdx + 1);
bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
if (!IsImmUpdate) {
// We use a VST1 for v1i64 even if the pseudo says VST2/3/4, so
// check for the opcode rather than the number of vector elements.
if (isVSTfixed(Opc))
Opc = getVLDSTRegisterUpdateOpcode(Opc);
Ops.push_back(Inc);
}
// VST1/VST2 fixed increment does not need Reg0 so only include it in
// the operands if not such an opcode.
else if (!isVSTfixed(Opc))
Ops.push_back(Reg0);
}
Ops.push_back(SrcReg);
Ops.push_back(Pred);
Ops.push_back(Reg0);
Ops.push_back(Chain);
SDNode *VSt = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
// Transfer memoperands.
CurDAG->setNodeMemRefs(cast<MachineSDNode>(VSt), {MemOp});
ReplaceNode(N, VSt);
return;
}
// Otherwise, quad registers are stored with two separate instructions,
// where one stores the even registers and the other stores the odd registers.
// Form the QQQQ REG_SEQUENCE.
SDValue V0 = N->getOperand(Vec0Idx + 0);
SDValue V1 = N->getOperand(Vec0Idx + 1);
SDValue V2 = N->getOperand(Vec0Idx + 2);
SDValue V3 = (NumVecs == 3)
? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
: N->getOperand(Vec0Idx + 3);
SDValue RegSeq = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
// Store the even D registers. This is always an updating store, so that it
// provides the address to the second store for the odd subregs.
const SDValue OpsA[] = { MemAddr, Align, Reg0, RegSeq, Pred, Reg0, Chain };
SDNode *VStA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
MemAddr.getValueType(),
MVT::Other, OpsA);
CurDAG->setNodeMemRefs(cast<MachineSDNode>(VStA), {MemOp});
Chain = SDValue(VStA, 1);
// Store the odd D registers.
Ops.push_back(SDValue(VStA, 0));
Ops.push_back(Align);
if (isUpdating) {
SDValue Inc = N->getOperand(AddrOpIdx + 1);
assert(isa<ConstantSDNode>(Inc.getNode()) &&
"only constant post-increment update allowed for VST3/4");
(void)Inc;
Ops.push_back(Reg0);
}
Ops.push_back(RegSeq);
Ops.push_back(Pred);
Ops.push_back(Reg0);
Ops.push_back(Chain);
SDNode *VStB = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys,
Ops);
CurDAG->setNodeMemRefs(cast<MachineSDNode>(VStB), {MemOp});
ReplaceNode(N, VStB);
}
void ARMDAGToDAGISel::SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
unsigned NumVecs,
const uint16_t *DOpcodes,
const uint16_t *QOpcodes) {
assert(NumVecs >=2 && NumVecs <= 4 && "VLDSTLane NumVecs out-of-range");
SDLoc dl(N);
SDValue MemAddr, Align;
bool IsIntrinsic = !isUpdating; // By coincidence, all supported updating
// nodes are not intrinsics.
unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
return;
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
SDValue Chain = N->getOperand(0);
unsigned Lane =
cast<ConstantSDNode>(N->getOperand(Vec0Idx + NumVecs))->getZExtValue();
EVT VT = N->getOperand(Vec0Idx).getValueType();
bool is64BitVector = VT.is64BitVector();
unsigned Alignment = 0;
if (NumVecs != 3) {
Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
if (Alignment > NumBytes)
Alignment = NumBytes;
if (Alignment < 8 && Alignment < NumBytes)
Alignment = 0;
// Alignment must be a power of two; make sure of that.
Alignment = (Alignment & -Alignment);
if (Alignment == 1)
Alignment = 0;
}
Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
unsigned OpcodeIndex;
switch (VT.getSimpleVT().SimpleTy) {
default: llvm_unreachable("unhandled vld/vst lane type");
// Double-register operations:
case MVT::v8i8: OpcodeIndex = 0; break;
case MVT::v4f16:
case MVT::v4i16: OpcodeIndex = 1; break;
case MVT::v2f32:
case MVT::v2i32: OpcodeIndex = 2; break;
// Quad-register operations:
case MVT::v8f16:
case MVT::v8i16: OpcodeIndex = 0; break;
case MVT::v4f32:
case MVT::v4i32: OpcodeIndex = 1; break;
}
std::vector<EVT> ResTys;
if (IsLoad) {
unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
if (!is64BitVector)
ResTyElts *= 2;
ResTys.push_back(EVT::getVectorVT(*CurDAG->getContext(),
MVT::i64, ResTyElts));
}
if (isUpdating)
ResTys.push_back(MVT::i32);
ResTys.push_back(MVT::Other);
SDValue Pred = getAL(CurDAG, dl);
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
SmallVector<SDValue, 8> Ops;
Ops.push_back(MemAddr);
Ops.push_back(Align);
if (isUpdating) {
SDValue Inc = N->getOperand(AddrOpIdx + 1);
bool IsImmUpdate =
isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
Ops.push_back(IsImmUpdate ? Reg0 : Inc);
}
SDValue SuperReg;
SDValue V0 = N->getOperand(Vec0Idx + 0);
SDValue V1 = N->getOperand(Vec0Idx + 1);
if (NumVecs == 2) {
if (is64BitVector)
SuperReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
else
SuperReg = SDValue(createQRegPairNode(MVT::v4i64, V0, V1), 0);
} else {
SDValue V2 = N->getOperand(Vec0Idx + 2);
SDValue V3 = (NumVecs == 3)
? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
: N->getOperand(Vec0Idx + 3);
if (is64BitVector)
SuperReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
else
SuperReg = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
}
Ops.push_back(SuperReg);
Ops.push_back(getI32Imm(Lane, dl));
Ops.push_back(Pred);
Ops.push_back(Reg0);
Ops.push_back(Chain);
unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
QOpcodes[OpcodeIndex]);
SDNode *VLdLn = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLdLn), {MemOp});
if (!IsLoad) {
ReplaceNode(N, VLdLn);
return;
}
// Extract the subregisters.
SuperReg = SDValue(VLdLn, 0);
static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
ARM::qsub_3 == ARM::qsub_0 + 3,
"Unexpected subreg numbering");
unsigned Sub0 = is64BitVector ? ARM::dsub_0 : ARM::qsub_0;
for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
ReplaceUses(SDValue(N, Vec),
CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
ReplaceUses(SDValue(N, NumVecs), SDValue(VLdLn, 1));
if (isUpdating)
ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdLn, 2));
CurDAG->RemoveDeadNode(N);
}
void ARMDAGToDAGISel::SelectVLDDup(SDNode *N, bool IsIntrinsic,
bool isUpdating, unsigned NumVecs,
const uint16_t *DOpcodes,
const uint16_t *QOpcodes0,
const uint16_t *QOpcodes1) {
assert(NumVecs >= 1 && NumVecs <= 4 && "VLDDup NumVecs out-of-range");
SDLoc dl(N);
SDValue MemAddr, Align;
unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
return;
SDValue Chain = N->getOperand(0);
EVT VT = N->getValueType(0);
bool is64BitVector = VT.is64BitVector();
unsigned Alignment = 0;
if (NumVecs != 3) {
Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
if (Alignment > NumBytes)
Alignment = NumBytes;
if (Alignment < 8 && Alignment < NumBytes)
Alignment = 0;
// Alignment must be a power of two; make sure of that.
Alignment = (Alignment & -Alignment);
if (Alignment == 1)
Alignment = 0;
}
Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
unsigned OpcodeIndex;
switch (VT.getSimpleVT().SimpleTy) {
default: llvm_unreachable("unhandled vld-dup type");
case MVT::v8i8:
case MVT::v16i8: OpcodeIndex = 0; break;
case MVT::v4i16:
case MVT::v8i16:
case MVT::v4f16:
case MVT::v8f16:
OpcodeIndex = 1; break;
case MVT::v2f32:
case MVT::v2i32:
case MVT::v4f32:
case MVT::v4i32: OpcodeIndex = 2; break;
case MVT::v1f64:
case MVT::v1i64: OpcodeIndex = 3; break;
}
unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
if (!is64BitVector)
ResTyElts *= 2;
EVT ResTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, ResTyElts);
std::vector<EVT> ResTys;
ResTys.push_back(ResTy);
if (isUpdating)
ResTys.push_back(MVT::i32);
ResTys.push_back(MVT::Other);
SDValue Pred = getAL(CurDAG, dl);
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
SDNode *VLdDup;
if (is64BitVector || NumVecs == 1) {
SmallVector<SDValue, 6> Ops;
Ops.push_back(MemAddr);
Ops.push_back(Align);
unsigned Opc = is64BitVector ? DOpcodes[OpcodeIndex] :
QOpcodes0[OpcodeIndex];
if (isUpdating) {
// fixed-stride update instructions don't have an explicit writeback
// operand. It's implicit in the opcode itself.
SDValue Inc = N->getOperand(2);
bool IsImmUpdate =
isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
if (NumVecs <= 2 && !IsImmUpdate)
Opc = getVLDSTRegisterUpdateOpcode(Opc);
if (!IsImmUpdate)
Ops.push_back(Inc);
// FIXME: VLD3 and VLD4 haven't been updated to that form yet.
else if (NumVecs > 2)
Ops.push_back(Reg0);
}
Ops.push_back(Pred);
Ops.push_back(Reg0);
Ops.push_back(Chain);
VLdDup = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
} else if (NumVecs == 2) {
const SDValue OpsA[] = { MemAddr, Align, Pred, Reg0, Chain };
SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex],
dl, ResTys, OpsA);
Chain = SDValue(VLdA, 1);
const SDValue OpsB[] = { MemAddr, Align, Pred, Reg0, Chain };
VLdDup = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys, OpsB);
} else {
SDValue ImplDef =
SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, ResTy), 0);
const SDValue OpsA[] = { MemAddr, Align, ImplDef, Pred, Reg0, Chain };
SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex],
dl, ResTys, OpsA);
SDValue SuperReg = SDValue(VLdA, 0);
Chain = SDValue(VLdA, 1);
const SDValue OpsB[] = { MemAddr, Align, SuperReg, Pred, Reg0, Chain };
VLdDup = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys, OpsB);
}
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLdDup), {MemOp});
// Extract the subregisters.
if (NumVecs == 1) {
ReplaceUses(SDValue(N, 0), SDValue(VLdDup, 0));
} else {
SDValue SuperReg = SDValue(VLdDup, 0);
static_assert(ARM::dsub_7 == ARM::dsub_0 + 7, "Unexpected subreg numbering");
unsigned SubIdx = is64BitVector ? ARM::dsub_0 : ARM::qsub_0;
for (unsigned Vec = 0; Vec != NumVecs; ++Vec) {
ReplaceUses(SDValue(N, Vec),
CurDAG->getTargetExtractSubreg(SubIdx+Vec, dl, VT, SuperReg));
}
}
ReplaceUses(SDValue(N, NumVecs), SDValue(VLdDup, 1));
if (isUpdating)
ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdDup, 2));
CurDAG->RemoveDeadNode(N);
}
bool ARMDAGToDAGISel::tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned) {
if (!Subtarget->hasV6T2Ops())
return false;
unsigned Opc = isSigned
? (Subtarget->isThumb() ? ARM::t2SBFX : ARM::SBFX)
: (Subtarget->isThumb() ? ARM::t2UBFX : ARM::UBFX);
SDLoc dl(N);
// For unsigned extracts, check for a shift right and mask
unsigned And_imm = 0;
if (N->getOpcode() == ISD::AND) {
if (isOpcWithIntImmediate(N, ISD::AND, And_imm)) {
// The immediate is a mask of the low bits iff imm & (imm+1) == 0
if (And_imm & (And_imm + 1))
return false;
unsigned Srl_imm = 0;
if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL,
Srl_imm)) {
assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
// Mask off the unnecessary bits of the AND immediate; normally
// DAGCombine will do this, but that might not happen if
// targetShrinkDemandedConstant chooses a different immediate.
And_imm &= -1U >> Srl_imm;
// Note: The width operand is encoded as width-1.
unsigned Width = countTrailingOnes(And_imm) - 1;
unsigned LSB = Srl_imm;
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
if ((LSB + Width + 1) == N->getValueType(0).getSizeInBits()) {
// It's cheaper to use a right shift to extract the top bits.
if (Subtarget->isThumb()) {
Opc = isSigned ? ARM::t2ASRri : ARM::t2LSRri;
SDValue Ops[] = { N->getOperand(0).getOperand(0),
CurDAG->getTargetConstant(LSB, dl, MVT::i32),
getAL(CurDAG, dl), Reg0, Reg0 };
CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
return true;
}
// ARM models shift instructions as MOVsi with shifter operand.
ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(ISD::SRL);
SDValue ShOpc =
CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, LSB), dl,
MVT::i32);
SDValue Ops[] = { N->getOperand(0).getOperand(0), ShOpc,
getAL(CurDAG, dl), Reg0, Reg0 };
CurDAG->SelectNodeTo(N, ARM::MOVsi, MVT::i32, Ops);
return true;
}
assert(LSB + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
SDValue Ops[] = { N->getOperand(0).getOperand(0),
CurDAG->getTargetConstant(LSB, dl, MVT::i32),
CurDAG->getTargetConstant(Width, dl, MVT::i32),
getAL(CurDAG, dl), Reg0 };
CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
return true;
}
}
return false;
}
// Otherwise, we're looking for a shift of a shift
unsigned Shl_imm = 0;
if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, Shl_imm)) {
assert(Shl_imm > 0 && Shl_imm < 32 && "bad amount in shift node!");
unsigned Srl_imm = 0;
if (isInt32Immediate(N->getOperand(1), Srl_imm)) {
assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
// Note: The width operand is encoded as width-1.
unsigned Width = 32 - Srl_imm - 1;
int LSB = Srl_imm - Shl_imm;
if (LSB < 0)
return false;
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
assert(LSB + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
SDValue Ops[] = { N->getOperand(0).getOperand(0),
CurDAG->getTargetConstant(LSB, dl, MVT::i32),
CurDAG->getTargetConstant(Width, dl, MVT::i32),
getAL(CurDAG, dl), Reg0 };
CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
return true;
}
}
// Or we are looking for a shift of an and, with a mask operand
if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, And_imm) &&
isShiftedMask_32(And_imm)) {
unsigned Srl_imm = 0;
unsigned LSB = countTrailingZeros(And_imm);
// Shift must be the same as the ands lsb
if (isInt32Immediate(N->getOperand(1), Srl_imm) && Srl_imm == LSB) {
assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
unsigned MSB = 31 - countLeadingZeros(And_imm);
// Note: The width operand is encoded as width-1.
unsigned Width = MSB - LSB;
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
assert(Srl_imm + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
SDValue Ops[] = { N->getOperand(0).getOperand(0),
CurDAG->getTargetConstant(Srl_imm, dl, MVT::i32),
CurDAG->getTargetConstant(Width, dl, MVT::i32),
getAL(CurDAG, dl), Reg0 };
CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
return true;
}
}
if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
unsigned LSB = 0;
if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL, LSB) &&
!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRA, LSB))
return false;
if (LSB + Width > 32)
return false;
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
assert(LSB + Width <= 32 && "Shouldn't create an invalid ubfx");
SDValue Ops[] = { N->getOperand(0).getOperand(0),
CurDAG->getTargetConstant(LSB, dl, MVT::i32),
CurDAG->getTargetConstant(Width - 1, dl, MVT::i32),
getAL(CurDAG, dl), Reg0 };
CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
return true;
}
return false;
}
/// Target-specific DAG combining for ISD::XOR.
/// Target-independent combining lowers SELECT_CC nodes of the form
/// select_cc setg[ge] X, 0, X, -X
/// select_cc setgt X, -1, X, -X
/// select_cc setl[te] X, 0, -X, X
/// select_cc setlt X, 1, -X, X
/// which represent Integer ABS into:
/// Y = sra (X, size(X)-1); xor (add (X, Y), Y)
/// ARM instruction selection detects the latter and matches it to
/// ARM::ABS or ARM::t2ABS machine node.
bool ARMDAGToDAGISel::tryABSOp(SDNode *N){
SDValue XORSrc0 = N->getOperand(0);
SDValue XORSrc1 = N->getOperand(1);
EVT VT = N->getValueType(0);
if (Subtarget->isThumb1Only())
return false;
if (XORSrc0.getOpcode() != ISD::ADD || XORSrc1.getOpcode() != ISD::SRA)
return false;
SDValue ADDSrc0 = XORSrc0.getOperand(0);
SDValue ADDSrc1 = XORSrc0.getOperand(1);
SDValue SRASrc0 = XORSrc1.getOperand(0);
SDValue SRASrc1 = XORSrc1.getOperand(1);
ConstantSDNode *SRAConstant = dyn_cast<ConstantSDNode>(SRASrc1);
EVT XType = SRASrc0.getValueType();
unsigned Size = XType.getSizeInBits() - 1;
if (ADDSrc1 == XORSrc1 && ADDSrc0 == SRASrc0 &&
XType.isInteger() && SRAConstant != nullptr &&
Size == SRAConstant->getZExtValue()) {
unsigned Opcode = Subtarget->isThumb2() ? ARM::t2ABS : ARM::ABS;
CurDAG->SelectNodeTo(N, Opcode, VT, ADDSrc0);
return true;
}
return false;
}
/// We've got special pseudo-instructions for these
void ARMDAGToDAGISel::SelectCMP_SWAP(SDNode *N) {
unsigned Opcode;
EVT MemTy = cast<MemSDNode>(N)->getMemoryVT();
if (MemTy == MVT::i8)
Opcode = ARM::CMP_SWAP_8;
else if (MemTy == MVT::i16)
Opcode = ARM::CMP_SWAP_16;
else if (MemTy == MVT::i32)
Opcode = ARM::CMP_SWAP_32;
else
llvm_unreachable("Unknown AtomicCmpSwap type");
SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3),
N->getOperand(0)};
SDNode *CmpSwap = CurDAG->getMachineNode(
Opcode, SDLoc(N),
CurDAG->getVTList(MVT::i32, MVT::i32, MVT::Other), Ops);
MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
ReplaceUses(SDValue(N, 0), SDValue(CmpSwap, 0));
ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 2));
CurDAG->RemoveDeadNode(N);
}
static Optional<std::pair<unsigned, unsigned>>
getContiguousRangeOfSetBits(const APInt &A) {
unsigned FirstOne = A.getBitWidth() - A.countLeadingZeros() - 1;
unsigned LastOne = A.countTrailingZeros();
if (A.countPopulation() != (FirstOne - LastOne + 1))
return Optional<std::pair<unsigned,unsigned>>();
return std::make_pair(FirstOne, LastOne);
}
void ARMDAGToDAGISel::SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI) {
assert(N->getOpcode() == ARMISD::CMPZ);
SwitchEQNEToPLMI = false;
if (!Subtarget->isThumb())
// FIXME: Work out whether it is profitable to do this in A32 mode - LSL and
// LSR don't exist as standalone instructions - they need the barrel shifter.
return;
// select (cmpz (and X, C), #0) -> (LSLS X) or (LSRS X) or (LSRS (LSLS X))
SDValue And = N->getOperand(0);
if (!And->hasOneUse())
return;
SDValue Zero = N->getOperand(1);
if (!isa<ConstantSDNode>(Zero) || !cast<ConstantSDNode>(Zero)->isNullValue() ||
And->getOpcode() != ISD::AND)
return;
SDValue X = And.getOperand(0);
auto C = dyn_cast<ConstantSDNode>(And.getOperand(1));
if (!C)
return;
auto Range = getContiguousRangeOfSetBits(C->getAPIntValue());
if (!Range)
return;
// There are several ways to lower this:
SDNode *NewN;
SDLoc dl(N);
auto EmitShift = [&](unsigned Opc, SDValue Src, unsigned Imm) -> SDNode* {
if (Subtarget->isThumb2()) {
Opc = (Opc == ARM::tLSLri) ? ARM::t2LSLri : ARM::t2LSRri;
SDValue Ops[] = { Src, CurDAG->getTargetConstant(Imm, dl, MVT::i32),
getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
CurDAG->getRegister(0, MVT::i32) };
return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
} else {
SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), Src,
CurDAG->getTargetConstant(Imm, dl, MVT::i32),
getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
}
};
if (Range->second == 0) {
// 1. Mask includes the LSB -> Simply shift the top N bits off
NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
ReplaceNode(And.getNode(), NewN);
} else if (Range->first == 31) {
// 2. Mask includes the MSB -> Simply shift the bottom N bits off
NewN = EmitShift(ARM::tLSRri, X, Range->second);
ReplaceNode(And.getNode(), NewN);
} else if (Range->first == Range->second) {
// 3. Only one bit is set. We can shift this into the sign bit and use a
// PL/MI comparison.
NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
ReplaceNode(And.getNode(), NewN);
SwitchEQNEToPLMI = true;
} else if (!Subtarget->hasV6T2Ops()) {
// 4. Do a double shift to clear bottom and top bits, but only in
// thumb-1 mode as in thumb-2 we can use UBFX.
NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
NewN = EmitShift(ARM::tLSRri, SDValue(NewN, 0),
Range->second + (31 - Range->first));
ReplaceNode(And.getNode(), NewN);
}
}
void ARMDAGToDAGISel::Select(SDNode *N) {
SDLoc dl(N);
if (N->isMachineOpcode()) {
N->setNodeId(-1);
return; // Already selected.
}
switch (N->getOpcode()) {
default: break;
case ISD::STORE: {
// For Thumb1, match an sp-relative store in C++. This is a little
// unfortunate, but I don't think I can make the chain check work
// otherwise. (The chain of the store has to be the same as the chain
// of the CopyFromReg, or else we can't replace the CopyFromReg with
// a direct reference to "SP".)
//
// This is only necessary on Thumb1 because Thumb1 sp-relative stores use
// a different addressing mode from other four-byte stores.
//
// This pattern usually comes up with call arguments.
StoreSDNode *ST = cast<StoreSDNode>(N);
SDValue Ptr = ST->getBasePtr();
if (Subtarget->isThumb1Only() && ST->isUnindexed()) {
int RHSC = 0;
if (Ptr.getOpcode() == ISD::ADD &&
isScaledConstantInRange(Ptr.getOperand(1), /*Scale=*/4, 0, 256, RHSC))
Ptr = Ptr.getOperand(0);
if (Ptr.getOpcode() == ISD::CopyFromReg &&
cast<RegisterSDNode>(Ptr.getOperand(1))->getReg() == ARM::SP &&
Ptr.getOperand(0) == ST->getChain()) {
SDValue Ops[] = {ST->getValue(),
CurDAG->getRegister(ARM::SP, MVT::i32),
CurDAG->getTargetConstant(RHSC, dl, MVT::i32),
getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32),
ST->getChain()};
MachineSDNode *ResNode =
CurDAG->getMachineNode(ARM::tSTRspi, dl, MVT::Other, Ops);
MachineMemOperand *MemOp = ST->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(ResNode), {MemOp});
ReplaceNode(N, ResNode);
return;
}
}
break;
}
case ISD::WRITE_REGISTER:
if (tryWriteRegister(N))
return;
break;
case ISD::READ_REGISTER:
if (tryReadRegister(N))
return;
break;
case ISD::INLINEASM:
case ISD::INLINEASM_BR:
if (tryInlineAsm(N))
return;
break;
case ISD::XOR:
// Select special operations if XOR node forms integer ABS pattern
if (tryABSOp(N))
return;
// Other cases are autogenerated.
break;
case ISD::Constant: {
unsigned Val = cast<ConstantSDNode>(N)->getZExtValue();
// If we can't materialize the constant we need to use a literal pool
if (ConstantMaterializationCost(Val) > 2) {
SDValue CPIdx = CurDAG->getTargetConstantPool(
ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val),
TLI->getPointerTy(CurDAG->getDataLayout()));
SDNode *ResNode;
if (Subtarget->isThumb()) {
SDValue Ops[] = {
CPIdx,
getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32),
CurDAG->getEntryNode()
};
ResNode = CurDAG->getMachineNode(ARM::tLDRpci, dl, MVT::i32, MVT::Other,
Ops);
} else {
SDValue Ops[] = {
CPIdx,
CurDAG->getTargetConstant(0, dl, MVT::i32),
getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32),
CurDAG->getEntryNode()
};
ResNode = CurDAG->getMachineNode(ARM::LDRcp, dl, MVT::i32, MVT::Other,
Ops);
}
// Annotate the Node with memory operand information so that MachineInstr
// queries work properly. This e.g. gives the register allocation the
// required information for rematerialization.
MachineFunction& MF = CurDAG->getMachineFunction();
MachineMemOperand *MemOp =
MF.getMachineMemOperand(MachinePointerInfo::getConstantPool(MF),
MachineMemOperand::MOLoad, 4, 4);
CurDAG->setNodeMemRefs(cast<MachineSDNode>(ResNode), {MemOp});
ReplaceNode(N, ResNode);
return;
}
// Other cases are autogenerated.
break;
}
case ISD::FrameIndex: {
// Selects to ADDri FI, 0 which in turn will become ADDri SP, imm.
int FI = cast<FrameIndexSDNode>(N)->getIndex();
SDValue TFI = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
if (Subtarget->isThumb1Only()) {
// Set the alignment of the frame object to 4, to avoid having to generate
// more than one ADD
MachineFrameInfo &MFI = MF->getFrameInfo();
if (MFI.getObjectAlignment(FI) < 4)
MFI.setObjectAlignment(FI, 4);
CurDAG->SelectNodeTo(N, ARM::tADDframe, MVT::i32, TFI,
CurDAG->getTargetConstant(0, dl, MVT::i32));
return;
} else {
unsigned Opc = ((Subtarget->isThumb() && Subtarget->hasThumb2()) ?
ARM::t2ADDri : ARM::ADDri);
SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, dl, MVT::i32),
getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
CurDAG->getRegister(0, MVT::i32) };
CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
return;
}
}
case ISD::SRL:
if (tryV6T2BitfieldExtractOp(N, false))
return;
break;
case ISD::SIGN_EXTEND_INREG:
case ISD::SRA:
if (tryV6T2BitfieldExtractOp(N, true))
return;
break;
case ISD::MUL:
if (Subtarget->isThumb1Only())
break;
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
unsigned RHSV = C->getZExtValue();
if (!RHSV) break;
if (isPowerOf2_32(RHSV-1)) { // 2^n+1?
unsigned ShImm = Log2_32(RHSV-1);
if (ShImm >= 32)
break;
SDValue V = N->getOperand(0);
ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
if (Subtarget->isThumb()) {
SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
CurDAG->SelectNodeTo(N, ARM::t2ADDrs, MVT::i32, Ops);
return;
} else {
SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
Reg0 };
CurDAG->SelectNodeTo(N, ARM::ADDrsi, MVT::i32, Ops);
return;
}
}
if (isPowerOf2_32(RHSV+1)) { // 2^n-1?
unsigned ShImm = Log2_32(RHSV+1);
if (ShImm >= 32)
break;
SDValue V = N->getOperand(0);
ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
if (Subtarget->isThumb()) {
SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
CurDAG->SelectNodeTo(N, ARM::t2RSBrs, MVT::i32, Ops);
return;
} else {
SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
Reg0 };
CurDAG->SelectNodeTo(N, ARM::RSBrsi, MVT::i32, Ops);
return;
}
}
}
break;
case ISD::AND: {
// Check for unsigned bitfield extract
if (tryV6T2BitfieldExtractOp(N, false))
return;
// If an immediate is used in an AND node, it is possible that the immediate
// can be more optimally materialized when negated. If this is the case we
// can negate the immediate and use a BIC instead.
auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
if (N1C && N1C->hasOneUse() && Subtarget->isThumb()) {
uint32_t Imm = (uint32_t) N1C->getZExtValue();
// In Thumb2 mode, an AND can take a 12-bit immediate. If this
// immediate can be negated and fit in the immediate operand of
// a t2BIC, don't do any manual transform here as this can be
// handled by the generic ISel machinery.
bool PreferImmediateEncoding =
Subtarget->hasThumb2() && (is_t2_so_imm(Imm) || is_t2_so_imm_not(Imm));
if (!PreferImmediateEncoding &&
ConstantMaterializationCost(Imm) >
ConstantMaterializationCost(~Imm)) {
// The current immediate costs more to materialize than a negated
// immediate, so negate the immediate and use a BIC.
SDValue NewImm =
CurDAG->getConstant(~N1C->getZExtValue(), dl, MVT::i32);
// If the new constant didn't exist before, reposition it in the topological
// ordering so it is just before N. Otherwise, don't touch its location.
if (NewImm->getNodeId() == -1)
CurDAG->RepositionNode(N->getIterator(), NewImm.getNode());
if (!Subtarget->hasThumb2()) {
SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32),
N->getOperand(0), NewImm, getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32)};
ReplaceNode(N, CurDAG->getMachineNode(ARM::tBIC, dl, MVT::i32, Ops));
return;
} else {
SDValue Ops[] = {N->getOperand(0), NewImm, getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32),
CurDAG->getRegister(0, MVT::i32)};
ReplaceNode(N,
CurDAG->getMachineNode(ARM::t2BICrr, dl, MVT::i32, Ops));
return;
}
}
}
// (and (or x, c2), c1) and top 16-bits of c1 and c2 match, lower 16-bits
// of c1 are 0xffff, and lower 16-bit of c2 are 0. That is, the top 16-bits
// are entirely contributed by c2 and lower 16-bits are entirely contributed
// by x. That's equal to (or (and x, 0xffff), (and c1, 0xffff0000)).
// Select it to: "movt x, ((c1 & 0xffff) >> 16)
EVT VT = N->getValueType(0);
if (VT != MVT::i32)
break;
unsigned Opc = (Subtarget->isThumb() && Subtarget->hasThumb2())
? ARM::t2MOVTi16
: (Subtarget->hasV6T2Ops() ? ARM::MOVTi16 : 0);
if (!Opc)
break;
SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
N1C = dyn_cast<ConstantSDNode>(N1);
if (!N1C)
break;
if (N0.getOpcode() == ISD::OR && N0.getNode()->hasOneUse()) {
SDValue N2 = N0.getOperand(1);
ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
if (!N2C)
break;
unsigned N1CVal = N1C->getZExtValue();
unsigned N2CVal = N2C->getZExtValue();
if ((N1CVal & 0xffff0000U) == (N2CVal & 0xffff0000U) &&
(N1CVal & 0xffffU) == 0xffffU &&
(N2CVal & 0xffffU) == 0x0U) {
SDValue Imm16 = CurDAG->getTargetConstant((N2CVal & 0xFFFF0000U) >> 16,
dl, MVT::i32);
SDValue Ops[] = { N0.getOperand(0), Imm16,
getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32) };
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, Ops));
return;
}
}
break;
}
case ARMISD::UMAAL: {
unsigned Opc = Subtarget->isThumb() ? ARM::t2UMAAL : ARM::UMAAL;
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3),
getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32) };
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::i32, Ops));
return;
}
case ARMISD::UMLAL:{
if (Subtarget->isThumb()) {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
N->getOperand(3), getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32)};
ReplaceNode(
N, CurDAG->getMachineNode(ARM::t2UMLAL, dl, MVT::i32, MVT::i32, Ops));
return;
}else{
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
N->getOperand(3), getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32),
CurDAG->getRegister(0, MVT::i32) };
ReplaceNode(N, CurDAG->getMachineNode(
Subtarget->hasV6Ops() ? ARM::UMLAL : ARM::UMLALv5, dl,
MVT::i32, MVT::i32, Ops));
return;
}
}
case ARMISD::SMLAL:{
if (Subtarget->isThumb()) {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
N->getOperand(3), getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32)};
ReplaceNode(
N, CurDAG->getMachineNode(ARM::t2SMLAL, dl, MVT::i32, MVT::i32, Ops));
return;
}else{
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
N->getOperand(3), getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32),
CurDAG->getRegister(0, MVT::i32) };
ReplaceNode(N, CurDAG->getMachineNode(
Subtarget->hasV6Ops() ? ARM::SMLAL : ARM::SMLALv5, dl,
MVT::i32, MVT::i32, Ops));
return;
}
}
case ARMISD::SUBE: {
if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
break;
// Look for a pattern to match SMMLS
// (sube a, (smul_loHi a, b), (subc 0, (smul_LOhi(a, b))))
if (N->getOperand(1).getOpcode() != ISD::SMUL_LOHI ||
N->getOperand(2).getOpcode() != ARMISD::SUBC ||
!SDValue(N, 1).use_empty())
break;
if (Subtarget->isThumb())
assert(Subtarget->hasThumb2() &&
"This pattern should not be generated for Thumb");
SDValue SmulLoHi = N->getOperand(1);
SDValue Subc = N->getOperand(2);
auto *Zero = dyn_cast<ConstantSDNode>(Subc.getOperand(0));
if (!Zero || Zero->getZExtValue() != 0 ||
Subc.getOperand(1) != SmulLoHi.getValue(0) ||
N->getOperand(1) != SmulLoHi.getValue(1) ||
N->getOperand(2) != Subc.getValue(1))
break;
unsigned Opc = Subtarget->isThumb2() ? ARM::t2SMMLS : ARM::SMMLS;
SDValue Ops[] = { SmulLoHi.getOperand(0), SmulLoHi.getOperand(1),
N->getOperand(0), getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32) };
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops));
return;
}
case ISD::LOAD: {
if (Subtarget->isThumb() && Subtarget->hasThumb2()) {
if (tryT2IndexedLoad(N))
return;
} else if (Subtarget->isThumb()) {
if (tryT1IndexedLoad(N))
return;
} else if (tryARMIndexedLoad(N))
return;
// Other cases are autogenerated.
break;
}
case ARMISD::BRCOND: {
// Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
// Emits: (Bcc:void (bb:Other):$dst, (imm:i32):$cc)
// Pattern complexity = 6 cost = 1 size = 0
// Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
// Emits: (tBcc:void (bb:Other):$dst, (imm:i32):$cc)
// Pattern complexity = 6 cost = 1 size = 0
// Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
// Emits: (t2Bcc:void (bb:Other):$dst, (imm:i32):$cc)
// Pattern complexity = 6 cost = 1 size = 0
unsigned Opc = Subtarget->isThumb() ?
((Subtarget->hasThumb2()) ? ARM::t2Bcc : ARM::tBcc) : ARM::Bcc;
SDValue Chain = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
SDValue N3 = N->getOperand(3);
SDValue InFlag = N->getOperand(4);
assert(N1.getOpcode() == ISD::BasicBlock);
assert(N2.getOpcode() == ISD::Constant);
assert(N3.getOpcode() == ISD::Register);
unsigned CC = (unsigned) cast<ConstantSDNode>(N2)->getZExtValue();
if (InFlag.getOpcode() == ARMISD::CMPZ) {
bool SwitchEQNEToPLMI;
SelectCMPZ(InFlag.getNode(), SwitchEQNEToPLMI);
InFlag = N->getOperand(4);
if (SwitchEQNEToPLMI) {
switch ((ARMCC::CondCodes)CC) {
default: llvm_unreachable("CMPZ must be either NE or EQ!");
case ARMCC::NE:
CC = (unsigned)ARMCC::MI;
break;
case ARMCC::EQ:
CC = (unsigned)ARMCC::PL;
break;
}
}
}
SDValue Tmp2 = CurDAG->getTargetConstant(CC, dl, MVT::i32);
SDValue Ops[] = { N1, Tmp2, N3, Chain, InFlag };
SDNode *ResNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
MVT::Glue, Ops);
Chain = SDValue(ResNode, 0);
if (N->getNumValues() == 2) {
InFlag = SDValue(ResNode, 1);
ReplaceUses(SDValue(N, 1), InFlag);
}
ReplaceUses(SDValue(N, 0),
SDValue(Chain.getNode(), Chain.getResNo()));
CurDAG->RemoveDeadNode(N);
return;
}
case ARMISD::CMPZ: {
// select (CMPZ X, #-C) -> (CMPZ (ADDS X, #C), #0)
// This allows us to avoid materializing the expensive negative constant.
// The CMPZ #0 is useless and will be peepholed away but we need to keep it
// for its glue output.
SDValue X = N->getOperand(0);
auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1).getNode());
if (C && C->getSExtValue() < 0 && Subtarget->isThumb()) {
int64_t Addend = -C->getSExtValue();
SDNode *Add = nullptr;
// ADDS can be better than CMN if the immediate fits in a
// 16-bit ADDS, which means either [0,256) for tADDi8 or [0,8) for tADDi3.
// Outside that range we can just use a CMN which is 32-bit but has a
// 12-bit immediate range.
if (Addend < 1<<8) {
if (Subtarget->isThumb2()) {
SDValue Ops[] = { X, CurDAG->getTargetConstant(Addend, dl, MVT::i32),
getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
CurDAG->getRegister(0, MVT::i32) };
Add = CurDAG->getMachineNode(ARM::t2ADDri, dl, MVT::i32, Ops);
} else {
unsigned Opc = (Addend < 1<<3) ? ARM::tADDi3 : ARM::tADDi8;
SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), X,
CurDAG->getTargetConstant(Addend, dl, MVT::i32),
getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
Add = CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
}
}
if (Add) {
SDValue Ops2[] = {SDValue(Add, 0), CurDAG->getConstant(0, dl, MVT::i32)};
CurDAG->MorphNodeTo(N, ARMISD::CMPZ, CurDAG->getVTList(MVT::Glue), Ops2);
}
}
// Other cases are autogenerated.
break;
}
case ARMISD::CMOV: {
SDValue InFlag = N->getOperand(4);
if (InFlag.getOpcode() == ARMISD::CMPZ) {
bool SwitchEQNEToPLMI;
SelectCMPZ(InFlag.getNode(), SwitchEQNEToPLMI);
if (SwitchEQNEToPLMI) {
SDValue ARMcc = N->getOperand(2);
ARMCC::CondCodes CC =
(ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
switch (CC) {
default: llvm_unreachable("CMPZ must be either NE or EQ!");
case ARMCC::NE:
CC = ARMCC::MI;
break;
case ARMCC::EQ:
CC = ARMCC::PL;
break;
}
SDValue NewARMcc = CurDAG->getConstant((unsigned)CC, dl, MVT::i32);
SDValue Ops[] = {N->getOperand(0), N->getOperand(1), NewARMcc,
N->getOperand(3), N->getOperand(4)};
CurDAG->MorphNodeTo(N, ARMISD::CMOV, N->getVTList(), Ops);
}
}
// Other cases are autogenerated.
break;
}
case ARMISD::VZIP: {
unsigned Opc = 0;
EVT VT = N->getValueType(0);
switch (VT.getSimpleVT().SimpleTy) {
default: return;
case MVT::v8i8: Opc = ARM::VZIPd8; break;
case MVT::v4f16:
case MVT::v4i16: Opc = ARM::VZIPd16; break;
case MVT::v2f32:
// vzip.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
case MVT::v2i32: Opc = ARM::VTRNd32; break;
case MVT::v16i8: Opc = ARM::VZIPq8; break;
case MVT::v8f16:
case MVT::v8i16: Opc = ARM::VZIPq16; break;
case MVT::v4f32:
case MVT::v4i32: Opc = ARM::VZIPq32; break;
}
SDValue Pred = getAL(CurDAG, dl);
SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
return;
}
case ARMISD::VUZP: {
unsigned Opc = 0;
EVT VT = N->getValueType(0);
switch (VT.getSimpleVT().SimpleTy) {
default: return;
case MVT::v8i8: Opc = ARM::VUZPd8; break;
case MVT::v4f16:
case MVT::v4i16: Opc = ARM::VUZPd16; break;
case MVT::v2f32:
// vuzp.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
case MVT::v2i32: Opc = ARM::VTRNd32; break;
case MVT::v16i8: Opc = ARM::VUZPq8; break;
case MVT::v8f16:
case MVT::v8i16: Opc = ARM::VUZPq16; break;
case MVT::v4f32:
case MVT::v4i32: Opc = ARM::VUZPq32; break;
}
SDValue Pred = getAL(CurDAG, dl);
SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
return;
}
case ARMISD::VTRN: {
unsigned Opc = 0;
EVT VT = N->getValueType(0);
switch (VT.getSimpleVT().SimpleTy) {
default: return;
case MVT::v8i8: Opc = ARM::VTRNd8; break;
case MVT::v4f16:
case MVT::v4i16: Opc = ARM::VTRNd16; break;
case MVT::v2f32:
case MVT::v2i32: Opc = ARM::VTRNd32; break;
case MVT::v16i8: Opc = ARM::VTRNq8; break;
case MVT::v8f16:
case MVT::v8i16: Opc = ARM::VTRNq16; break;
case MVT::v4f32:
case MVT::v4i32: Opc = ARM::VTRNq32; break;
}
SDValue Pred = getAL(CurDAG, dl);
SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
return;
}
case ARMISD::BUILD_VECTOR: {
EVT VecVT = N->getValueType(0);
EVT EltVT = VecVT.getVectorElementType();
unsigned NumElts = VecVT.getVectorNumElements();
if (EltVT == MVT::f64) {
assert(NumElts == 2 && "unexpected type for BUILD_VECTOR");
ReplaceNode(
N, createDRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
return;
}
assert(EltVT == MVT::f32 && "unexpected type for BUILD_VECTOR");
if (NumElts == 2) {
ReplaceNode(
N, createSRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
return;
}
assert(NumElts == 4 && "unexpected type for BUILD_VECTOR");
ReplaceNode(N,
createQuadSRegsNode(VecVT, N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3)));
return;
}
case ARMISD::VLD1DUP: {
static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8, ARM::VLD1DUPd16,
ARM::VLD1DUPd32 };
static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8, ARM::VLD1DUPq16,
ARM::VLD1DUPq32 };
SelectVLDDup(N, /* IsIntrinsic= */ false, false, 1, DOpcodes, QOpcodes);
return;
}
case ARMISD::VLD2DUP: {
static const uint16_t Opcodes[] = { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
ARM::VLD2DUPd32 };
SelectVLDDup(N, /* IsIntrinsic= */ false, false, 2, Opcodes);
return;
}
case ARMISD::VLD3DUP: {
static const uint16_t Opcodes[] = { ARM::VLD3DUPd8Pseudo,
ARM::VLD3DUPd16Pseudo,
ARM::VLD3DUPd32Pseudo };
SelectVLDDup(N, /* IsIntrinsic= */ false, false, 3, Opcodes);
return;
}
case ARMISD::VLD4DUP: {
static const uint16_t Opcodes[] = { ARM::VLD4DUPd8Pseudo,
ARM::VLD4DUPd16Pseudo,
ARM::VLD4DUPd32Pseudo };
SelectVLDDup(N, /* IsIntrinsic= */ false, false, 4, Opcodes);
return;
}
case ARMISD::VLD1DUP_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8wb_fixed,
ARM::VLD1DUPd16wb_fixed,
ARM::VLD1DUPd32wb_fixed };
static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8wb_fixed,
ARM::VLD1DUPq16wb_fixed,
ARM::VLD1DUPq32wb_fixed };
SelectVLDDup(N, /* IsIntrinsic= */ false, true, 1, DOpcodes, QOpcodes);
return;
}
case ARMISD::VLD2DUP_UPD: {
static const uint16_t Opcodes[] = { ARM::VLD2DUPd8wb_fixed,
ARM::VLD2DUPd16wb_fixed,
ARM::VLD2DUPd32wb_fixed };
SelectVLDDup(N, /* IsIntrinsic= */ false, true, 2, Opcodes);
return;
}
case ARMISD::VLD3DUP_UPD: {
static const uint16_t Opcodes[] = { ARM::VLD3DUPd8Pseudo_UPD,
ARM::VLD3DUPd16Pseudo_UPD,
ARM::VLD3DUPd32Pseudo_UPD };
SelectVLDDup(N, /* IsIntrinsic= */ false, true, 3, Opcodes);
return;
}
case ARMISD::VLD4DUP_UPD: {
static const uint16_t Opcodes[] = { ARM::VLD4DUPd8Pseudo_UPD,
ARM::VLD4DUPd16Pseudo_UPD,
ARM::VLD4DUPd32Pseudo_UPD };
SelectVLDDup(N, /* IsIntrinsic= */ false, true, 4, Opcodes);
return;
}
case ARMISD::VLD1_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD1d8wb_fixed,
ARM::VLD1d16wb_fixed,
ARM::VLD1d32wb_fixed,
ARM::VLD1d64wb_fixed };
static const uint16_t QOpcodes[] = { ARM::VLD1q8wb_fixed,
ARM::VLD1q16wb_fixed,
ARM::VLD1q32wb_fixed,
ARM::VLD1q64wb_fixed };
SelectVLD(N, true, 1, DOpcodes, QOpcodes, nullptr);
return;
}
case ARMISD::VLD2_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD2d8wb_fixed,
ARM::VLD2d16wb_fixed,
ARM::VLD2d32wb_fixed,
ARM::VLD1q64wb_fixed};
static const uint16_t QOpcodes[] = { ARM::VLD2q8PseudoWB_fixed,
ARM::VLD2q16PseudoWB_fixed,
ARM::VLD2q32PseudoWB_fixed };
SelectVLD(N, true, 2, DOpcodes, QOpcodes, nullptr);
return;
}
case ARMISD::VLD3_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo_UPD,
ARM::VLD3d16Pseudo_UPD,
ARM::VLD3d32Pseudo_UPD,
ARM::VLD1d64TPseudoWB_fixed};
static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
ARM::VLD3q16Pseudo_UPD,
ARM::VLD3q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo_UPD,
ARM::VLD3q16oddPseudo_UPD,
ARM::VLD3q32oddPseudo_UPD };
SelectVLD(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case ARMISD::VLD4_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD4d8Pseudo_UPD,
ARM::VLD4d16Pseudo_UPD,
ARM::VLD4d32Pseudo_UPD,
ARM::VLD1d64QPseudoWB_fixed};
static const uint16_t QOpcodes0[] = { ARM::VLD4q8Pseudo_UPD,
ARM::VLD4q16Pseudo_UPD,
ARM::VLD4q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VLD4q8oddPseudo_UPD,
ARM::VLD4q16oddPseudo_UPD,
ARM::VLD4q32oddPseudo_UPD };
SelectVLD(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case ARMISD::VLD2LN_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo_UPD,
ARM::VLD2LNd16Pseudo_UPD,
ARM::VLD2LNd32Pseudo_UPD };
static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo_UPD,
ARM::VLD2LNq32Pseudo_UPD };
SelectVLDSTLane(N, true, true, 2, DOpcodes, QOpcodes);
return;
}
case ARMISD::VLD3LN_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo_UPD,
ARM::VLD3LNd16Pseudo_UPD,
ARM::VLD3LNd32Pseudo_UPD };
static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo_UPD,
ARM::VLD3LNq32Pseudo_UPD };
SelectVLDSTLane(N, true, true, 3, DOpcodes, QOpcodes);
return;
}
case ARMISD::VLD4LN_UPD: {
static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo_UPD,
ARM::VLD4LNd16Pseudo_UPD,
ARM::VLD4LNd32Pseudo_UPD };
static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo_UPD,
ARM::VLD4LNq32Pseudo_UPD };
SelectVLDSTLane(N, true, true, 4, DOpcodes, QOpcodes);
return;
}
case ARMISD::VST1_UPD: {
static const uint16_t DOpcodes[] = { ARM::VST1d8wb_fixed,
ARM::VST1d16wb_fixed,
ARM::VST1d32wb_fixed,
ARM::VST1d64wb_fixed };
static const uint16_t QOpcodes[] = { ARM::VST1q8wb_fixed,
ARM::VST1q16wb_fixed,
ARM::VST1q32wb_fixed,
ARM::VST1q64wb_fixed };
SelectVST(N, true, 1, DOpcodes, QOpcodes, nullptr);
return;
}
case ARMISD::VST2_UPD: {
static const uint16_t DOpcodes[] = { ARM::VST2d8wb_fixed,
ARM::VST2d16wb_fixed,
ARM::VST2d32wb_fixed,
ARM::VST1q64wb_fixed};
static const uint16_t QOpcodes[] = { ARM::VST2q8PseudoWB_fixed,
ARM::VST2q16PseudoWB_fixed,
ARM::VST2q32PseudoWB_fixed };
SelectVST(N, true, 2, DOpcodes, QOpcodes, nullptr);
return;
}
case ARMISD::VST3_UPD: {
static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo_UPD,
ARM::VST3d16Pseudo_UPD,
ARM::VST3d32Pseudo_UPD,
ARM::VST1d64TPseudoWB_fixed};
static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
ARM::VST3q16Pseudo_UPD,
ARM::VST3q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo_UPD,
ARM::VST3q16oddPseudo_UPD,
ARM::VST3q32oddPseudo_UPD };
SelectVST(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case ARMISD::VST4_UPD: {
static const uint16_t DOpcodes[] = { ARM::VST4d8Pseudo_UPD,
ARM::VST4d16Pseudo_UPD,
ARM::VST4d32Pseudo_UPD,
ARM::VST1d64QPseudoWB_fixed};
static const uint16_t QOpcodes0[] = { ARM::VST4q8Pseudo_UPD,
ARM::VST4q16Pseudo_UPD,
ARM::VST4q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VST4q8oddPseudo_UPD,
ARM::VST4q16oddPseudo_UPD,
ARM::VST4q32oddPseudo_UPD };
SelectVST(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case ARMISD::VST2LN_UPD: {
static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo_UPD,
ARM::VST2LNd16Pseudo_UPD,
ARM::VST2LNd32Pseudo_UPD };
static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo_UPD,
ARM::VST2LNq32Pseudo_UPD };
SelectVLDSTLane(N, false, true, 2, DOpcodes, QOpcodes);
return;
}
case ARMISD::VST3LN_UPD: {
static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo_UPD,
ARM::VST3LNd16Pseudo_UPD,
ARM::VST3LNd32Pseudo_UPD };
static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo_UPD,
ARM::VST3LNq32Pseudo_UPD };
SelectVLDSTLane(N, false, true, 3, DOpcodes, QOpcodes);
return;
}
case ARMISD::VST4LN_UPD: {
static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo_UPD,
ARM::VST4LNd16Pseudo_UPD,
ARM::VST4LNd32Pseudo_UPD };
static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo_UPD,
ARM::VST4LNq32Pseudo_UPD };
SelectVLDSTLane(N, false, true, 4, DOpcodes, QOpcodes);
return;
}
case ISD::INTRINSIC_VOID:
case ISD::INTRINSIC_W_CHAIN: {
unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
switch (IntNo) {
default:
break;
case Intrinsic::arm_mrrc:
case Intrinsic::arm_mrrc2: {
SDLoc dl(N);
SDValue Chain = N->getOperand(0);
unsigned Opc;
if (Subtarget->isThumb())
Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::t2MRRC : ARM::t2MRRC2);
else
Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::MRRC : ARM::MRRC2);
SmallVector<SDValue, 5> Ops;
Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(), dl)); /* coproc */
Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(3))->getZExtValue(), dl)); /* opc */
Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(4))->getZExtValue(), dl)); /* CRm */
// The mrrc2 instruction in ARM doesn't allow predicates, the top 4 bits of the encoded
// instruction will always be '1111' but it is possible in assembly language to specify
// AL as a predicate to mrrc2 but it doesn't make any difference to the encoded instruction.
if (Opc != ARM::MRRC2) {
Ops.push_back(getAL(CurDAG, dl));
Ops.push_back(CurDAG->getRegister(0, MVT::i32));
}
Ops.push_back(Chain);
// Writes to two registers.
const EVT RetType[] = {MVT::i32, MVT::i32, MVT::Other};
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, RetType, Ops));
return;
}
case Intrinsic::arm_ldaexd:
case Intrinsic::arm_ldrexd: {
SDLoc dl(N);
SDValue Chain = N->getOperand(0);
SDValue MemAddr = N->getOperand(2);
bool isThumb = Subtarget->isThumb() && Subtarget->hasV8MBaselineOps();
bool IsAcquire = IntNo == Intrinsic::arm_ldaexd;
unsigned NewOpc = isThumb ? (IsAcquire ? ARM::t2LDAEXD : ARM::t2LDREXD)
: (IsAcquire ? ARM::LDAEXD : ARM::LDREXD);
// arm_ldrexd returns a i64 value in {i32, i32}
std::vector<EVT> ResTys;
if (isThumb) {
ResTys.push_back(MVT::i32);
ResTys.push_back(MVT::i32);
} else
ResTys.push_back(MVT::Untyped);
ResTys.push_back(MVT::Other);
// Place arguments in the right order.
SDValue Ops[] = {MemAddr, getAL(CurDAG, dl),
CurDAG->getRegister(0, MVT::i32), Chain};
SDNode *Ld = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(Ld), {MemOp});
// Remap uses.
SDValue OutChain = isThumb ? SDValue(Ld, 2) : SDValue(Ld, 1);
if (!SDValue(N, 0).use_empty()) {
SDValue Result;
if (isThumb)
Result = SDValue(Ld, 0);
else {
SDValue SubRegIdx =
CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
Result = SDValue(ResNode,0);
}
ReplaceUses(SDValue(N, 0), Result);
}
if (!SDValue(N, 1).use_empty()) {
SDValue Result;
if (isThumb)
Result = SDValue(Ld, 1);
else {
SDValue SubRegIdx =
CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
Result = SDValue(ResNode,0);
}
ReplaceUses(SDValue(N, 1), Result);
}
ReplaceUses(SDValue(N, 2), OutChain);
CurDAG->RemoveDeadNode(N);
return;
}
case Intrinsic::arm_stlexd:
case Intrinsic::arm_strexd: {
SDLoc dl(N);
SDValue Chain = N->getOperand(0);
SDValue Val0 = N->getOperand(2);
SDValue Val1 = N->getOperand(3);
SDValue MemAddr = N->getOperand(4);
// Store exclusive double return a i32 value which is the return status
// of the issued store.
const EVT ResTys[] = {MVT::i32, MVT::Other};
bool isThumb = Subtarget->isThumb() && Subtarget->hasThumb2();
// Place arguments in the right order.
SmallVector<SDValue, 7> Ops;
if (isThumb) {
Ops.push_back(Val0);
Ops.push_back(Val1);
} else
// arm_strexd uses GPRPair.
Ops.push_back(SDValue(createGPRPairNode(MVT::Untyped, Val0, Val1), 0));
Ops.push_back(MemAddr);
Ops.push_back(getAL(CurDAG, dl));
Ops.push_back(CurDAG->getRegister(0, MVT::i32));
Ops.push_back(Chain);
bool IsRelease = IntNo == Intrinsic::arm_stlexd;
unsigned NewOpc = isThumb ? (IsRelease ? ARM::t2STLEXD : ARM::t2STREXD)
: (IsRelease ? ARM::STLEXD : ARM::STREXD);
SDNode *St = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
ReplaceNode(N, St);
return;
}
case Intrinsic::arm_neon_vld1: {
static const uint16_t DOpcodes[] = { ARM::VLD1d8, ARM::VLD1d16,
ARM::VLD1d32, ARM::VLD1d64 };
static const uint16_t QOpcodes[] = { ARM::VLD1q8, ARM::VLD1q16,
ARM::VLD1q32, ARM::VLD1q64};
SelectVLD(N, false, 1, DOpcodes, QOpcodes, nullptr);
return;
}
case Intrinsic::arm_neon_vld1x2: {
static const uint16_t DOpcodes[] = { ARM::VLD1q8, ARM::VLD1q16,
ARM::VLD1q32, ARM::VLD1q64 };
static const uint16_t QOpcodes[] = { ARM::VLD1d8QPseudo,
ARM::VLD1d16QPseudo,
ARM::VLD1d32QPseudo,
ARM::VLD1d64QPseudo };
SelectVLD(N, false, 2, DOpcodes, QOpcodes, nullptr);
return;
}
case Intrinsic::arm_neon_vld1x3: {
static const uint16_t DOpcodes[] = { ARM::VLD1d8TPseudo,
ARM::VLD1d16TPseudo,
ARM::VLD1d32TPseudo,
ARM::VLD1d64TPseudo };
static const uint16_t QOpcodes0[] = { ARM::VLD1q8LowTPseudo_UPD,
ARM::VLD1q16LowTPseudo_UPD,
ARM::VLD1q32LowTPseudo_UPD,
ARM::VLD1q64LowTPseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VLD1q8HighTPseudo,
ARM::VLD1q16HighTPseudo,
ARM::VLD1q32HighTPseudo,
ARM::VLD1q64HighTPseudo };
SelectVLD(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vld1x4: {
static const uint16_t DOpcodes[] = { ARM::VLD1d8QPseudo,
ARM::VLD1d16QPseudo,
ARM::VLD1d32QPseudo,
ARM::VLD1d64QPseudo };
static const uint16_t QOpcodes0[] = { ARM::VLD1q8LowQPseudo_UPD,
ARM::VLD1q16LowQPseudo_UPD,
ARM::VLD1q32LowQPseudo_UPD,
ARM::VLD1q64LowQPseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VLD1q8HighQPseudo,
ARM::VLD1q16HighQPseudo,
ARM::VLD1q32HighQPseudo,
ARM::VLD1q64HighQPseudo };
SelectVLD(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vld2: {
static const uint16_t DOpcodes[] = { ARM::VLD2d8, ARM::VLD2d16,
ARM::VLD2d32, ARM::VLD1q64 };
static const uint16_t QOpcodes[] = { ARM::VLD2q8Pseudo, ARM::VLD2q16Pseudo,
ARM::VLD2q32Pseudo };
SelectVLD(N, false, 2, DOpcodes, QOpcodes, nullptr);
return;
}
case Intrinsic::arm_neon_vld3: {
static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo,
ARM::VLD3d16Pseudo,
ARM::VLD3d32Pseudo,
ARM::VLD1d64TPseudo };
static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
ARM::VLD3q16Pseudo_UPD,
ARM::VLD3q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo,
ARM::VLD3q16oddPseudo,
ARM::VLD3q32oddPseudo };
SelectVLD(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vld4: {
static const uint16_t DOpcodes[] = { ARM::VLD4d8Pseudo,
ARM::VLD4d16Pseudo,
ARM::VLD4d32Pseudo,
ARM::VLD1d64QPseudo };
static const uint16_t QOpcodes0[] = { ARM::VLD4q8Pseudo_UPD,
ARM::VLD4q16Pseudo_UPD,
ARM::VLD4q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VLD4q8oddPseudo,
ARM::VLD4q16oddPseudo,
ARM::VLD4q32oddPseudo };
SelectVLD(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vld2dup: {
static const uint16_t DOpcodes[] = { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
ARM::VLD2DUPd32, ARM::VLD1q64 };
static const uint16_t QOpcodes0[] = { ARM::VLD2DUPq8EvenPseudo,
ARM::VLD2DUPq16EvenPseudo,
ARM::VLD2DUPq32EvenPseudo };
static const uint16_t QOpcodes1[] = { ARM::VLD2DUPq8OddPseudo,
ARM::VLD2DUPq16OddPseudo,
ARM::VLD2DUPq32OddPseudo };
SelectVLDDup(N, /* IsIntrinsic= */ true, false, 2,
DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vld3dup: {
static const uint16_t DOpcodes[] = { ARM::VLD3DUPd8Pseudo,
ARM::VLD3DUPd16Pseudo,
ARM::VLD3DUPd32Pseudo,
ARM::VLD1d64TPseudo };
static const uint16_t QOpcodes0[] = { ARM::VLD3DUPq8EvenPseudo,
ARM::VLD3DUPq16EvenPseudo,
ARM::VLD3DUPq32EvenPseudo };
static const uint16_t QOpcodes1[] = { ARM::VLD3DUPq8OddPseudo,
ARM::VLD3DUPq16OddPseudo,
ARM::VLD3DUPq32OddPseudo };
SelectVLDDup(N, /* IsIntrinsic= */ true, false, 3,
DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vld4dup: {
static const uint16_t DOpcodes[] = { ARM::VLD4DUPd8Pseudo,
ARM::VLD4DUPd16Pseudo,
ARM::VLD4DUPd32Pseudo,
ARM::VLD1d64QPseudo };
static const uint16_t QOpcodes0[] = { ARM::VLD4DUPq8EvenPseudo,
ARM::VLD4DUPq16EvenPseudo,
ARM::VLD4DUPq32EvenPseudo };
static const uint16_t QOpcodes1[] = { ARM::VLD4DUPq8OddPseudo,
ARM::VLD4DUPq16OddPseudo,
ARM::VLD4DUPq32OddPseudo };
SelectVLDDup(N, /* IsIntrinsic= */ true, false, 4,
DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vld2lane: {
static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo,
ARM::VLD2LNd16Pseudo,
ARM::VLD2LNd32Pseudo };
static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo,
ARM::VLD2LNq32Pseudo };
SelectVLDSTLane(N, true, false, 2, DOpcodes, QOpcodes);
return;
}
case Intrinsic::arm_neon_vld3lane: {
static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo,
ARM::VLD3LNd16Pseudo,
ARM::VLD3LNd32Pseudo };
static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo,
ARM::VLD3LNq32Pseudo };
SelectVLDSTLane(N, true, false, 3, DOpcodes, QOpcodes);
return;
}
case Intrinsic::arm_neon_vld4lane: {
static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo,
ARM::VLD4LNd16Pseudo,
ARM::VLD4LNd32Pseudo };
static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo,
ARM::VLD4LNq32Pseudo };
SelectVLDSTLane(N, true, false, 4, DOpcodes, QOpcodes);
return;
}
case Intrinsic::arm_neon_vst1: {
static const uint16_t DOpcodes[] = { ARM::VST1d8, ARM::VST1d16,
ARM::VST1d32, ARM::VST1d64 };
static const uint16_t QOpcodes[] = { ARM::VST1q8, ARM::VST1q16,
ARM::VST1q32, ARM::VST1q64 };
SelectVST(N, false, 1, DOpcodes, QOpcodes, nullptr);
return;
}
case Intrinsic::arm_neon_vst1x2: {
static const uint16_t DOpcodes[] = { ARM::VST1q8, ARM::VST1q16,
ARM::VST1q32, ARM::VST1q64 };
static const uint16_t QOpcodes[] = { ARM::VST1d8QPseudo,
ARM::VST1d16QPseudo,
ARM::VST1d32QPseudo,
ARM::VST1d64QPseudo };
SelectVST(N, false, 2, DOpcodes, QOpcodes, nullptr);
return;
}
case Intrinsic::arm_neon_vst1x3: {
static const uint16_t DOpcodes[] = { ARM::VST1d8TPseudo,
ARM::VST1d16TPseudo,
ARM::VST1d32TPseudo,
ARM::VST1d64TPseudo };
static const uint16_t QOpcodes0[] = { ARM::VST1q8LowTPseudo_UPD,
ARM::VST1q16LowTPseudo_UPD,
ARM::VST1q32LowTPseudo_UPD,
ARM::VST1q64LowTPseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VST1q8HighTPseudo,
ARM::VST1q16HighTPseudo,
ARM::VST1q32HighTPseudo,
ARM::VST1q64HighTPseudo };
SelectVST(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vst1x4: {
static const uint16_t DOpcodes[] = { ARM::VST1d8QPseudo,
ARM::VST1d16QPseudo,
ARM::VST1d32QPseudo,
ARM::VST1d64QPseudo };
static const uint16_t QOpcodes0[] = { ARM::VST1q8LowQPseudo_UPD,
ARM::VST1q16LowQPseudo_UPD,
ARM::VST1q32LowQPseudo_UPD,
ARM::VST1q64LowQPseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VST1q8HighQPseudo,
ARM::VST1q16HighQPseudo,
ARM::VST1q32HighQPseudo,
ARM::VST1q64HighQPseudo };
SelectVST(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vst2: {
static const uint16_t DOpcodes[] = { ARM::VST2d8, ARM::VST2d16,
ARM::VST2d32, ARM::VST1q64 };
static const uint16_t QOpcodes[] = { ARM::VST2q8Pseudo, ARM::VST2q16Pseudo,
ARM::VST2q32Pseudo };
SelectVST(N, false, 2, DOpcodes, QOpcodes, nullptr);
return;
}
case Intrinsic::arm_neon_vst3: {
static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo,
ARM::VST3d16Pseudo,
ARM::VST3d32Pseudo,
ARM::VST1d64TPseudo };
static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
ARM::VST3q16Pseudo_UPD,
ARM::VST3q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo,
ARM::VST3q16oddPseudo,
ARM::VST3q32oddPseudo };
SelectVST(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vst4: {
static const uint16_t DOpcodes[] = { ARM::VST4d8Pseudo,
ARM::VST4d16Pseudo,
ARM::VST4d32Pseudo,
ARM::VST1d64QPseudo };
static const uint16_t QOpcodes0[] = { ARM::VST4q8Pseudo_UPD,
ARM::VST4q16Pseudo_UPD,
ARM::VST4q32Pseudo_UPD };
static const uint16_t QOpcodes1[] = { ARM::VST4q8oddPseudo,
ARM::VST4q16oddPseudo,
ARM::VST4q32oddPseudo };
SelectVST(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
return;
}
case Intrinsic::arm_neon_vst2lane: {
static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo,
ARM::VST2LNd16Pseudo,
ARM::VST2LNd32Pseudo };
static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo,
ARM::VST2LNq32Pseudo };
SelectVLDSTLane(N, false, false, 2, DOpcodes, QOpcodes);
return;
}
case Intrinsic::arm_neon_vst3lane: {
static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo,
ARM::VST3LNd16Pseudo,
ARM::VST3LNd32Pseudo };
static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo,
ARM::VST3LNq32Pseudo };
SelectVLDSTLane(N, false, false, 3, DOpcodes, QOpcodes);
return;
}
case Intrinsic::arm_neon_vst4lane: {
static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo,
ARM::VST4LNd16Pseudo,
ARM::VST4LNd32Pseudo };
static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo,
ARM::VST4LNq32Pseudo };
SelectVLDSTLane(N, false, false, 4, DOpcodes, QOpcodes);
return;
}
}
break;
}
case ISD::ATOMIC_CMP_SWAP:
SelectCMP_SWAP(N);
return;
}
SelectCode(N);
}
// Inspect a register string of the form
// cp<coprocessor>:<opc1>:c<CRn>:c<CRm>:<opc2> (32bit) or
// cp<coprocessor>:<opc1>:c<CRm> (64bit) inspect the fields of the string
// and obtain the integer operands from them, adding these operands to the
// provided vector.
static void getIntOperandsFromRegisterString(StringRef RegString,
SelectionDAG *CurDAG,
const SDLoc &DL,
std::vector<SDValue> &Ops) {
SmallVector<StringRef, 5> Fields;
RegString.split(Fields, ':');
if (Fields.size() > 1) {
bool AllIntFields = true;
for (StringRef Field : Fields) {
// Need to trim out leading 'cp' characters and get the integer field.
unsigned IntField;
AllIntFields &= !Field.trim("CPcp").getAsInteger(10, IntField);
Ops.push_back(CurDAG->getTargetConstant(IntField, DL, MVT::i32));
}
assert(AllIntFields &&
"Unexpected non-integer value in special register string.");
}
}
// Maps a Banked Register string to its mask value. The mask value returned is
// for use in the MRSbanked / MSRbanked instruction nodes as the Banked Register
// mask operand, which expresses which register is to be used, e.g. r8, and in
// which mode it is to be used, e.g. usr. Returns -1 to signify that the string
// was invalid.
static inline int getBankedRegisterMask(StringRef RegString) {
auto TheReg = ARMBankedReg::lookupBankedRegByName(RegString.lower());
if (!TheReg)
return -1;
return TheReg->Encoding;
}
// The flags here are common to those allowed for apsr in the A class cores and
// those allowed for the special registers in the M class cores. Returns a
// value representing which flags were present, -1 if invalid.
static inline int getMClassFlagsMask(StringRef Flags) {
return StringSwitch<int>(Flags)
.Case("", 0x2) // no flags means nzcvq for psr registers, and 0x2 is
// correct when flags are not permitted
.Case("g", 0x1)
.Case("nzcvq", 0x2)
.Case("nzcvqg", 0x3)
.Default(-1);
}
// Maps MClass special registers string to its value for use in the
// t2MRS_M/t2MSR_M instruction nodes as the SYSm value operand.
// Returns -1 to signify that the string was invalid.
static int getMClassRegisterMask(StringRef Reg, const ARMSubtarget *Subtarget) {
auto TheReg = ARMSysReg::lookupMClassSysRegByName(Reg);
const FeatureBitset &FeatureBits = Subtarget->getFeatureBits();
if (!TheReg || !TheReg->hasRequiredFeatures(FeatureBits))
return -1;
return (int)(TheReg->Encoding & 0xFFF); // SYSm value
}
static int getARClassRegisterMask(StringRef Reg, StringRef Flags) {
// The mask operand contains the special register (R Bit) in bit 4, whether
// the register is spsr (R bit is 1) or one of cpsr/apsr (R bit is 0), and
// bits 3-0 contains the fields to be accessed in the special register, set by
// the flags provided with the register.
int Mask = 0;
if (Reg == "apsr") {
// The flags permitted for apsr are the same flags that are allowed in
// M class registers. We get the flag value and then shift the flags into
// the correct place to combine with the mask.
Mask = getMClassFlagsMask(Flags);
if (Mask == -1)
return -1;
return Mask << 2;
}
if (Reg != "cpsr" && Reg != "spsr") {
return -1;
}
// This is the same as if the flags were "fc"
if (Flags.empty() || Flags == "all")
return Mask | 0x9;
// Inspect the supplied flags string and set the bits in the mask for
// the relevant and valid flags allowed for cpsr and spsr.
for (char Flag : Flags) {
int FlagVal;
switch (Flag) {
case 'c':
FlagVal = 0x1;
break;
case 'x':
FlagVal = 0x2;
break;
case 's':
FlagVal = 0x4;
break;
case 'f':
FlagVal = 0x8;
break;
default:
FlagVal = 0;
}
// This avoids allowing strings where the same flag bit appears twice.
if (!FlagVal || (Mask & FlagVal))
return -1;
Mask |= FlagVal;
}
// If the register is spsr then we need to set the R bit.
if (Reg == "spsr")
Mask |= 0x10;
return Mask;
}
// Lower the read_register intrinsic to ARM specific DAG nodes
// using the supplied metadata string to select the instruction node to use
// and the registers/masks to construct as operands for the node.
bool ARMDAGToDAGISel::tryReadRegister(SDNode *N){
const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
bool IsThumb2 = Subtarget->isThumb2();
SDLoc DL(N);
std::vector<SDValue> Ops;
getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
if (!Ops.empty()) {
// If the special register string was constructed of fields (as defined
// in the ACLE) then need to lower to MRC node (32 bit) or
// MRRC node(64 bit), we can make the distinction based on the number of
// operands we have.
unsigned Opcode;
SmallVector<EVT, 3> ResTypes;
if (Ops.size() == 5){
Opcode = IsThumb2 ? ARM::t2MRC : ARM::MRC;
ResTypes.append({ MVT::i32, MVT::Other });
} else {
assert(Ops.size() == 3 &&
"Invalid number of fields in special register string.");
Opcode = IsThumb2 ? ARM::t2MRRC : ARM::MRRC;
ResTypes.append({ MVT::i32, MVT::i32, MVT::Other });
}
Ops.push_back(getAL(CurDAG, DL));
Ops.push_back(CurDAG->getRegister(0, MVT::i32));
Ops.push_back(N->getOperand(0));
ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, ResTypes, Ops));
return true;
}
std::string SpecialReg = RegString->getString().lower();
int BankedReg = getBankedRegisterMask(SpecialReg);
if (BankedReg != -1) {
Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32),
getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
N->getOperand(0) };
ReplaceNode(
N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSbanked : ARM::MRSbanked,
DL, MVT::i32, MVT::Other, Ops));
return true;
}
// The VFP registers are read by creating SelectionDAG nodes with opcodes
// corresponding to the register that is being read from. So we switch on the
// string to find which opcode we need to use.
unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
.Case("fpscr", ARM::VMRS)
.Case("fpexc", ARM::VMRS_FPEXC)
.Case("fpsid", ARM::VMRS_FPSID)
.Case("mvfr0", ARM::VMRS_MVFR0)
.Case("mvfr1", ARM::VMRS_MVFR1)
.Case("mvfr2", ARM::VMRS_MVFR2)
.Case("fpinst", ARM::VMRS_FPINST)
.Case("fpinst2", ARM::VMRS_FPINST2)
.Default(0);
// If an opcode was found then we can lower the read to a VFP instruction.
if (Opcode) {
if (!Subtarget->hasVFP2Base())
return false;
if (Opcode == ARM::VMRS_MVFR2 && !Subtarget->hasFPARMv8Base())
return false;
Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
N->getOperand(0) };
ReplaceNode(N,
CurDAG->getMachineNode(Opcode, DL, MVT::i32, MVT::Other, Ops));
return true;
}
// If the target is M Class then need to validate that the register string
// is an acceptable value, so check that a mask can be constructed from the
// string.
if (Subtarget->isMClass()) {
int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
if (SYSmValue == -1)
return false;
SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
N->getOperand(0) };
ReplaceNode(
N, CurDAG->getMachineNode(ARM::t2MRS_M, DL, MVT::i32, MVT::Other, Ops));
return true;
}
// Here we know the target is not M Class so we need to check if it is one
// of the remaining possible values which are apsr, cpsr or spsr.
if (SpecialReg == "apsr" || SpecialReg == "cpsr") {
Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
N->getOperand(0) };
ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRS_AR : ARM::MRS,
DL, MVT::i32, MVT::Other, Ops));
return true;
}
if (SpecialReg == "spsr") {
Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
N->getOperand(0) };
ReplaceNode(
N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSsys_AR : ARM::MRSsys, DL,
MVT::i32, MVT::Other, Ops));
return true;
}
return false;
}
// Lower the write_register intrinsic to ARM specific DAG nodes
// using the supplied metadata string to select the instruction node to use
// and the registers/masks to use in the nodes
bool ARMDAGToDAGISel::tryWriteRegister(SDNode *N){
const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
bool IsThumb2 = Subtarget->isThumb2();
SDLoc DL(N);
std::vector<SDValue> Ops;
getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
if (!Ops.empty()) {
// If the special register string was constructed of fields (as defined
// in the ACLE) then need to lower to MCR node (32 bit) or
// MCRR node(64 bit), we can make the distinction based on the number of
// operands we have.
unsigned Opcode;
if (Ops.size() == 5) {
Opcode = IsThumb2 ? ARM::t2MCR : ARM::MCR;
Ops.insert(Ops.begin()+2, N->getOperand(2));
} else {
assert(Ops.size() == 3 &&
"Invalid number of fields in special register string.");
Opcode = IsThumb2 ? ARM::t2MCRR : ARM::MCRR;
SDValue WriteValue[] = { N->getOperand(2), N->getOperand(3) };
Ops.insert(Ops.begin()+2, WriteValue, WriteValue+2);
}
Ops.push_back(getAL(CurDAG, DL));
Ops.push_back(CurDAG->getRegister(0, MVT::i32));
Ops.push_back(N->getOperand(0));
ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
return true;
}
std::string SpecialReg = RegString->getString().lower();
int BankedReg = getBankedRegisterMask(SpecialReg);
if (BankedReg != -1) {
Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32), N->getOperand(2),
getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
N->getOperand(0) };
ReplaceNode(
N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSRbanked : ARM::MSRbanked,
DL, MVT::Other, Ops));
return true;
}
// The VFP registers are written to by creating SelectionDAG nodes with
// opcodes corresponding to the register that is being written. So we switch
// on the string to find which opcode we need to use.
unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
.Case("fpscr", ARM::VMSR)
.Case("fpexc", ARM::VMSR_FPEXC)
.Case("fpsid", ARM::VMSR_FPSID)
.Case("fpinst", ARM::VMSR_FPINST)
.Case("fpinst2", ARM::VMSR_FPINST2)
.Default(0);
if (Opcode) {
if (!Subtarget->hasVFP2Base())
return false;
Ops = { N->getOperand(2), getAL(CurDAG, DL),
CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
return true;
}
std::pair<StringRef, StringRef> Fields;
Fields = StringRef(SpecialReg).rsplit('_');
std::string Reg = Fields.first.str();
StringRef Flags = Fields.second;
// If the target was M Class then need to validate the special register value
// and retrieve the mask for use in the instruction node.
if (Subtarget->isMClass()) {
int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
if (SYSmValue == -1)
return false;
SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
N->getOperand(2), getAL(CurDAG, DL),
CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
ReplaceNode(N, CurDAG->getMachineNode(ARM::t2MSR_M, DL, MVT::Other, Ops));
return true;
}
// We then check to see if a valid mask can be constructed for one of the
// register string values permitted for the A and R class cores. These values
// are apsr, spsr and cpsr; these are also valid on older cores.
int Mask = getARClassRegisterMask(Reg, Flags);
if (Mask != -1) {
Ops = { CurDAG->getTargetConstant(Mask, DL, MVT::i32), N->getOperand(2),
getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
N->getOperand(0) };
ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSR_AR : ARM::MSR,
DL, MVT::Other, Ops));
return true;
}
return false;
}
bool ARMDAGToDAGISel::tryInlineAsm(SDNode *N){
std::vector<SDValue> AsmNodeOperands;
unsigned Flag, Kind;
bool Changed = false;
unsigned NumOps = N->getNumOperands();
// Normally, i64 data is bounded to two arbitrary GRPs for "%r" constraint.
// However, some instrstions (e.g. ldrexd/strexd in ARM mode) require
// (even/even+1) GPRs and use %n and %Hn to refer to the individual regs
// respectively. Since there is no constraint to explicitly specify a
// reg pair, we use GPRPair reg class for "%r" for 64-bit data. For Thumb,
// the 64-bit data may be referred by H, Q, R modifiers, so we still pack
// them into a GPRPair.
SDLoc dl(N);
SDValue Glue = N->getGluedNode() ? N->getOperand(NumOps-1)
: SDValue(nullptr,0);
SmallVector<bool, 8> OpChanged;
// Glue node will be appended late.
for(unsigned i = 0, e = N->getGluedNode() ? NumOps - 1 : NumOps; i < e; ++i) {
SDValue op = N->getOperand(i);
AsmNodeOperands.push_back(op);
if (i < InlineAsm::Op_FirstOperand)
continue;
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(i))) {
Flag = C->getZExtValue();
Kind = InlineAsm::getKind(Flag);
}
else
continue;
// Immediate operands to inline asm in the SelectionDAG are modeled with
// two operands. The first is a constant of value InlineAsm::Kind_Imm, and
// the second is a constant with the value of the immediate. If we get here
// and we have a Kind_Imm, skip the next operand, and continue.
if (Kind == InlineAsm::Kind_Imm) {
SDValue op = N->getOperand(++i);
AsmNodeOperands.push_back(op);
continue;
}
unsigned NumRegs = InlineAsm::getNumOperandRegisters(Flag);
if (NumRegs)
OpChanged.push_back(false);
unsigned DefIdx = 0;
bool IsTiedToChangedOp = false;
// If it's a use that is tied with a previous def, it has no
// reg class constraint.
if (Changed && InlineAsm::isUseOperandTiedToDef(Flag, DefIdx))
IsTiedToChangedOp = OpChanged[DefIdx];
// Memory operands to inline asm in the SelectionDAG are modeled with two
// operands: a constant of value InlineAsm::Kind_Mem followed by the input
// operand. If we get here and we have a Kind_Mem, skip the next operand (so
// it doesn't get misinterpreted), and continue. We do this here because
// it's important to update the OpChanged array correctly before moving on.
if (Kind == InlineAsm::Kind_Mem) {
SDValue op = N->getOperand(++i);
AsmNodeOperands.push_back(op);
continue;
}
if (Kind != InlineAsm::Kind_RegUse && Kind != InlineAsm::Kind_RegDef
&& Kind != InlineAsm::Kind_RegDefEarlyClobber)
continue;
unsigned RC;
bool HasRC = InlineAsm::hasRegClassConstraint(Flag, RC);
if ((!IsTiedToChangedOp && (!HasRC || RC != ARM::GPRRegClassID))
|| NumRegs != 2)
continue;
assert((i+2 < NumOps) && "Invalid number of operands in inline asm");
SDValue V0 = N->getOperand(i+1);
SDValue V1 = N->getOperand(i+2);
unsigned Reg0 = cast<RegisterSDNode>(V0)->getReg();
unsigned Reg1 = cast<RegisterSDNode>(V1)->getReg();
SDValue PairedReg;
MachineRegisterInfo &MRI = MF->getRegInfo();
if (Kind == InlineAsm::Kind_RegDef ||
Kind == InlineAsm::Kind_RegDefEarlyClobber) {
// Replace the two GPRs with 1 GPRPair and copy values from GPRPair to
// the original GPRs.
unsigned GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
SDValue Chain = SDValue(N,0);
SDNode *GU = N->getGluedUser();
SDValue RegCopy = CurDAG->getCopyFromReg(Chain, dl, GPVR, MVT::Untyped,
Chain.getValue(1));
// Extract values from a GPRPair reg and copy to the original GPR reg.
SDValue Sub0 = CurDAG->getTargetExtractSubreg(ARM::gsub_0, dl, MVT::i32,
RegCopy);
SDValue Sub1 = CurDAG->getTargetExtractSubreg(ARM::gsub_1, dl, MVT::i32,
RegCopy);
SDValue T0 = CurDAG->getCopyToReg(Sub0, dl, Reg0, Sub0,
RegCopy.getValue(1));
SDValue T1 = CurDAG->getCopyToReg(Sub1, dl, Reg1, Sub1, T0.getValue(1));
// Update the original glue user.
std::vector<SDValue> Ops(GU->op_begin(), GU->op_end()-1);
Ops.push_back(T1.getValue(1));
CurDAG->UpdateNodeOperands(GU, Ops);
}
else {
// For Kind == InlineAsm::Kind_RegUse, we first copy two GPRs into a
// GPRPair and then pass the GPRPair to the inline asm.
SDValue Chain = AsmNodeOperands[InlineAsm::Op_InputChain];
// As REG_SEQ doesn't take RegisterSDNode, we copy them first.
SDValue T0 = CurDAG->getCopyFromReg(Chain, dl, Reg0, MVT::i32,
Chain.getValue(1));
SDValue T1 = CurDAG->getCopyFromReg(Chain, dl, Reg1, MVT::i32,
T0.getValue(1));
SDValue Pair = SDValue(createGPRPairNode(MVT::Untyped, T0, T1), 0);
// Copy REG_SEQ into a GPRPair-typed VR and replace the original two
// i32 VRs of inline asm with it.
unsigned GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
Chain = CurDAG->getCopyToReg(T1, dl, GPVR, Pair, T1.getValue(1));
AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Glue = Chain.getValue(1);
}
Changed = true;
if(PairedReg.getNode()) {
OpChanged[OpChanged.size() -1 ] = true;
Flag = InlineAsm::getFlagWord(Kind, 1 /* RegNum*/);
if (IsTiedToChangedOp)
Flag = InlineAsm::getFlagWordForMatchingOp(Flag, DefIdx);
else
Flag = InlineAsm::getFlagWordForRegClass(Flag, ARM::GPRPairRegClassID);
// Replace the current flag.
AsmNodeOperands[AsmNodeOperands.size() -1] = CurDAG->getTargetConstant(
Flag, dl, MVT::i32);
// Add the new register node and skip the original two GPRs.
AsmNodeOperands.push_back(PairedReg);
// Skip the next two GPRs.
i += 2;
}
}
if (Glue.getNode())
AsmNodeOperands.push_back(Glue);
if (!Changed)
return false;
SDValue New = CurDAG->getNode(N->getOpcode(), SDLoc(N),
CurDAG->getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
New->setNodeId(-1);
ReplaceNode(N, New.getNode());
return true;
}
bool ARMDAGToDAGISel::
SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
std::vector<SDValue> &OutOps) {
switch(ConstraintID) {
default:
llvm_unreachable("Unexpected asm memory constraint");
case InlineAsm::Constraint_i:
// FIXME: It seems strange that 'i' is needed here since it's supposed to
// be an immediate and not a memory constraint.
LLVM_FALLTHROUGH;
case InlineAsm::Constraint_m:
case InlineAsm::Constraint_o:
case InlineAsm::Constraint_Q:
case InlineAsm::Constraint_Um:
case InlineAsm::Constraint_Un:
case InlineAsm::Constraint_Uq:
case InlineAsm::Constraint_Us:
case InlineAsm::Constraint_Ut:
case InlineAsm::Constraint_Uv:
case InlineAsm::Constraint_Uy:
// Require the address to be in a register. That is safe for all ARM
// variants and it is hard to do anything much smarter without knowing
// how the operand is used.
OutOps.push_back(Op);
return false;
}
return true;
}
/// createARMISelDag - This pass converts a legalized DAG into a
/// ARM-specific DAG, ready for instruction scheduling.
///
FunctionPass *llvm::createARMISelDag(ARMBaseTargetMachine &TM,
CodeGenOpt::Level OptLevel) {
return new ARMDAGToDAGISel(TM, OptLevel);
}
| apple/swift-llvm | lib/Target/ARM/ARMISelDAGToDAG.cpp | C++ | apache-2.0 | 172,333 |
package com.huawei.esdk.sms.north.http.common;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.huawei.esdk.platform.common.utils.ESDKIOUtils;
import com.huawei.esdk.platform.common.utils.help.DocumentBuilderFactories;
import com.huawei.esdk.sms.north.http.bean.PlaceHolderBean;
public abstract class AbstractXMLProcessor implements IXMLProcessor
{
private static Logger LOGGER = Logger.getLogger(AbstractXMLProcessor.class);
@Override
public List<PlaceHolderBean> processClasspathXMLFile(String fileName)
throws ParserConfigurationException, SAXException, IOException
{
String xmlContent = ESDKIOUtils.getClasspathFileContent(fileName);
return parseXML(xmlContent);
}
@Override
public List<PlaceHolderBean> processXML(String xmlContent)
throws ParserConfigurationException, SAXException, IOException
{
return parseXML(xmlContent);
}
protected List<PlaceHolderBean> parseXML(String xmlAsString)
throws ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactories.newSecurityInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(xmlAsString.getBytes("utf-8"))));
doc.getDocumentElement().normalize();
Element rootElement = doc.getDocumentElement();
List<PlaceHolderBean> result = new ArrayList<PlaceHolderBean>();
return parseNode(rootElement, result);
}
protected List<PlaceHolderBean> parseNode(Node nNode, List<PlaceHolderBean> placerHolders)
{
StringBuilder sb = new StringBuilder();
if (LOGGER.isDebugEnabled())
{
sb.append("Current Node :").append(nNode.getNodeName());
sb.append("|Node Type:").append(nNode.getNodeType());
sb.append("|Node Value:").append(nNode.getNodeValue());
sb.append("|Text Value:" + nNode.getTextContent());
LOGGER.debug(sb.toString());
}
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element)nNode;
if (hasSubElement(nNode))
{
NodeList nList = nNode.getChildNodes();
Node nodeItem;
for (int temp = 0; temp < nList.getLength(); temp++)
{
nodeItem = nList.item(temp);
parseNode(nodeItem, placerHolders);
}
}
else
{
if (LOGGER.isDebugEnabled())
{
sb.delete(0, sb.length());
sb.append("Tag Name:").append(eElement.getTagName());
sb.append("|Node Name:").append(eElement.getNodeName());
sb.append("|Node Value:").append(eElement.getNodeValue());
sb.append("|Text Content:").append(eElement.getTextContent());
LOGGER.debug(sb.toString());
}
//It's the element which hasn't child element and should be processed
PlaceHolderBean placeHolder = processElement(eElement);
if (null != placeHolder)
{
placerHolders.add(placeHolder);
}
}
}
return placerHolders;
}
private boolean hasSubElement(Node node)
{
if (null == node || Node.ELEMENT_NODE != node.getNodeType())
{
return false;
}
NodeList nList = node.getChildNodes();
Node nodeItem;
for (int temp = 0; temp < nList.getLength(); temp++)
{
nodeItem = nList.item(temp);
if (Node.ELEMENT_NODE == nodeItem.getNodeType())
{
return true;
}
}
return false;
}
protected abstract PlaceHolderBean processElement(Element element);
}
| eSDK/esdk_sms | source/esdk_sms_neadp_http/src/main/java/com/huawei/esdk/sms/north/http/common/AbstractXMLProcessor.java | Java | apache-2.0 | 4,493 |
package com.example;
/**
* Created by Nish on 2/21/15.
*/
public interface Movable {
public void moveLeft();
public void moveRight();
}
| nishtahir/Mektory-BeginnersAndroid | Week2/mygame/src/main/java/com/example/Movable.java | Java | apache-2.0 | 147 |
# 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.
# =============================================================================
"""Python front-end supports for functions.
NOTE: functions are currently experimental and subject to change!
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import hashlib
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import function_pb2
from tensorflow.python import pywrap_tensorflow as c_api
from tensorflow.python.eager import context
from tensorflow.python.framework import c_api_util
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import graph_to_function_def
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import compat
from tensorflow.python.util import function_utils
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util import tf_inspect
class Defun(object):
"""Decorator used to define TensorFlow functions.
Use this decorator to make a Python function usable directly as a TensorFlow
function.
The decorated function must add ops to the default graph and return zero or
more `Tensor` objects. Call the decorator with named arguments, one for each
argument of the function to decorate, with the expected type of the argument
as value.
For example if the function to decorate accepts two `tf.float32` arguments
named `x` and `y`, call the decorator with:
@Defun(tf.float32, tf.float32)
def foo(x, y):
...
When you call the decorated function it will add `call` ops to the
default graph and adds the definition of the function into the
default graph. Because the addition of the function into the graph
is deferred, the decorator can be used anywhere in the program.
Any variables created inside of the function are hoisted into the outer graph.
Note that the variables are created in the variable scope that was active
during the first call to the function. Subsequent function calls will refer to
the same set of variables.
Definitions of functions in a graph are frozen as soon as the graph is used to
create a session. However, new functions and new calls to existing functions
may be added to the graph, with the new functions themselves becoming
immediately frozen.
Example, but also see the [How To on functions](link_needed).
```python
# Defining the function.
@tf.Defun(tf.float32, tf.float32)
def MyFunc(x, y):
return x + y, x - y
# Building the graph.
a = tf.constant([1.0])
b = tf.constant([2.0])
c, d = MyFunc(a, b, name='mycall')
```
"""
def __init__(self, *input_types, **kwargs):
"""Create a `Defun` decorator.
Args:
*input_types: A list of `tf.DType`
**kwargs: Optional keyword arguments, including
func_name - (optional). A python string, the name to use to
declare this `Function` in the graph.
grad_func - (optional). A function implementing the gradient
of the function-to-register. This is must be a
`_DefinedFunction` object. The gradient
function must satisfy the criterion defined in
function.proto:GradientDef.
python_grad_func - (optional). A function implementing the
gradient of the function python-side. This function must
take the current op and the gradients w.r.t. its outputs,
and return the gradients w.r.t. the inputs. That is it must
implement the interface expected by `tf.RegisterGradient`).
This will be called by tf.gradients to add the gradient ops
to the graph. At most one of grad_func and python_grad_func
can be specified.
out_names = (optional). A list of strings, one per output
tensor.
shape_func - (optional). A function taking the op and returning a list
of static shapes to set for the function's outputs.
"""
self._input_types = input_types
self._func_name = kwargs.pop("func_name", None)
self._grad_func = kwargs.pop("grad_func", None)
self._python_grad_func = kwargs.pop("python_grad_func", None)
self._out_names = kwargs.pop("out_names", None)
self._extra_kwargs = kwargs
def __call__(self, func):
# Various sanity checks on the callable func.
if not callable(func):
raise ValueError("func %s must be callable" % func)
# Func should not use kwargs and defaults.
argspec = tf_inspect.getargspec(func)
if argspec.keywords or argspec.defaults:
raise ValueError("Functions with argument defaults or keyword "
"arguments are not supported.")
# Computes how many arguments 'func' has.
min_args = len(argspec.args)
max_args = min_args
if argspec.varargs:
max_args = 1000000
argnames = argspec.args
if tf_inspect.ismethod(func):
# 1st argument is the "class" type.
min_args -= 1
argnames = argnames[1:]
if self._input_types:
# If Defun is given a list of types for the inputs, the number
# of input types should be compatible with 'func'.
num = len(self._input_types)
if num < min_args or num > max_args:
raise ValueError(
"The function has fewer arguments than the number of specified "
"input types.")
return _DefinedFunction(
func,
argnames,
self._input_types,
self._func_name,
self._grad_func,
self._python_grad_func,
out_names=self._out_names,
**self._extra_kwargs)
# 'func' expects no arguments and input types is an empty list.
if min_args == 0 and max_args == 0:
return _DefinedFunction(
func, [], [],
self._func_name,
self._grad_func,
self._python_grad_func,
out_names=self._out_names,
**self._extra_kwargs)
# Input types are unknown. It's an overloaded function and hence
# its definition needs to be deferred until it's called.
return _OverloadedFunction(
func,
argnames,
self._func_name,
self._grad_func,
self._python_grad_func,
out_names=self._out_names,
**self._extra_kwargs)
class _DefinedFunction(object):
"""_DefinedFunction encapsulates a function definition and its properties.
Attributes:
name: The function name.
definition: The definition of this function. A FunctionDef proto.
grad_func_name: If not None, the name of this function's gradient function.
python_grad_func: A python callable implementing the gradient of
the function python-side.
"""
def __init__(self,
func,
argnames,
input_types,
func_name=None,
grad_func=None,
python_grad_func=None,
out_names=None,
shape_func=None,
capture_by_value=False,
**kwargs):
"""Creates _DefinedFunction.
Args:
func: A python callable which constructs a tf function body.
argnames: A list of strings for function argument names.
input_types: The function's argument types. Can be a tuple, list of
tf data types.
func_name: The function name. Defaults to None, in which derives from
'func'.
grad_func: This function's gradient function, if not None. Defaults
to None.
python_grad_func: A python callable implementing the gradient of
the function python-side.
out_names: An optional list of strings for the function return value
names.
shape_func: An optional function mapping an op to a list of static
output shapes.
capture_by_value: Boolean (defaults to False). If True, captured values
will be copied into the function body.
**kwargs: The keyword arguments. **kwargs is passed to every call
site of this function.
Raises:
ValueError: The function definition is invalid.
"""
self._func = func
self._input_types = input_types
self._func_name = func_name
self._grad_func = grad_func
self._python_grad_func = python_grad_func
self._out_names = out_names
self._shape_func = shape_func
self._capture_by_value = capture_by_value
self._extra_kwargs = kwargs
# Constructed only when C API is disabled, lazily
self._definition = None
# Constructed only when C API is enabled, lazily
self._c_func = None
self._sub_functions = dict() # Constructed with _definition or _c_func
# pylint: disable=protected-access
device_funcs = ops.get_default_graph()._device_functions_outer_to_inner
# pylint: enable=protected-access
# Get the innermost device if possbile.
self._caller_device = device_funcs[-1] if device_funcs else None
# Cached OpDef for this function. When C API is enabled, this is
# the only part of FunctionDef that we cache in Python. When C API
# is disabled the whole _definition is available and this is simply
# another reference to _definition.signature
self._op_def = None
assert isinstance(input_types, (list, tuple))
self._arg_types = input_types
self._arg_names = [argnames[i] if i < len(argnames) else ("arg%d" % i)
for i in range(len(input_types))]
@property
def name(self):
"""Function name."""
self._create_definition_if_needed()
return self._func_name
@property
def definition(self):
"""Function definition proto."""
self._create_definition_if_needed()
if self._c_func:
with c_api_util.tf_buffer() as buf:
c_api.TF_FunctionToFunctionDef(self._c_func.func, buf)
fdef = function_pb2.FunctionDef()
proto_data = c_api.TF_GetBuffer(buf)
fdef.ParseFromString(compat.as_bytes(proto_data))
return fdef
return self._definition
@property
def _signature(self):
self._create_definition_if_needed()
return self._op_def
def set_grad_func(self, grad_func):
"""Specifies the gradient function of this function."""
assert not self._grad_func
assert isinstance(grad_func, _DefinedFunction)
self._grad_func = grad_func
@property
def grad_func_name(self):
"""Its gradient function's name."""
return self._grad_func.name if self._grad_func else None
@property
def python_grad_func(self):
"""Python gradient function callable."""
return self._python_grad_func
@property
def declared_input_types(self):
"""Returns the list of data types of explicit declared inputs."""
return self._input_types
@property
def captured_inputs(self):
"""Returns the list of implicitly captured inputs."""
self._create_definition_if_needed()
return self._extra_inputs
@property
def stateful_ops(self):
"""Returns the list of stateful ops in function definition.
Returns:
A list of (op.name, op.type) pairs.
"""
self._create_definition_if_needed()
return self._stateful_ops
def _create_definition_if_needed(self):
"""Creates the function definition if it's not created yet."""
with context.graph_mode():
self._create_definition_if_needed_impl()
def _create_definition_if_needed_impl(self):
"""This is not what you want, see _create_definition_if_needed."""
if self._definition is not None or self._c_func is not None:
return
temp_graph = func_graph_from_py_func(
self._func, self._arg_names, self._arg_types, self._func_name,
self._capture_by_value, self._caller_device)
self._extra_inputs = temp_graph.extra_inputs
# pylint: disable=protected-access
self._sub_functions = temp_graph._functions
# pylint: enable=protected-access
# Extra kwargs are treated as attrs on the function def.
if self._func_name:
base_func_name = self._func_name
else:
base_func_name = function_utils.get_func_name(self._func)
if self._grad_func:
base_func_name += ("_%s" % self._grad_func.name)
kwargs_attr = _parse_kwargs_as_attrs(base_func_name, **self._extra_kwargs)
if not temp_graph._c_graph: # pylint: disable=protected-access
# Build the FunctionDef
self._definition = graph_to_function_def.graph_to_function_def(
temp_graph,
temp_graph.get_operations(),
temp_graph.inputs,
temp_graph.outputs,
out_names=self._out_names)
for k in kwargs_attr:
self._definition.attr[k].CopyFrom(kwargs_attr[k])
# Hash the definition and its dependencies.
self._hash_str = self._create_hash_str(
self._definition.signature.input_arg,
self._definition.signature.output_arg, self._definition.node_def)
# Finally, we decide the function name to use. If not specified,
# make up something which is almost certainly unique (but deterministic).
if not self._func_name:
self._func_name = "_".join([base_func_name, self._hash_str])
self._definition.signature.name = self._func_name
if self._func.__doc__:
self._definition.signature.description = self._func.__doc__
self._op_def = self._definition.signature
else: # C API is enabled
output_names = ([compat.as_bytes(x) for x in self._out_names]
if self._out_names else [])
description = self._func.__doc__ or None
# pylint: disable=protected-access
c_func = c_api.TF_GraphToFunction_wrapper(
temp_graph._c_graph,
base_func_name,
self._func_name is None, # append_hash_to_fn_name
None, # opers
[t._as_tf_output() for t in temp_graph.inputs],
[t._as_tf_output() for t in temp_graph.outputs],
output_names,
None, # opts
description)
self._c_func = c_api_util.ScopedTFFunction(c_func)
# pylint: enable=protected-access
self._set_c_attrs(kwargs_attr)
# Set cached fields: _op_def and _func_name (if not already set)
self._op_def = self.definition.signature
if self._func_name:
assert self._func_name == self._op_def.name
else:
self._func_name = compat.as_str(self._op_def.name)
self._stateful_ops = [(op.name, op.type)
for op in temp_graph.get_operations()
if op.op_def.is_stateful]
def _set_c_attrs(self, attrs):
"""Sets `attrs` as attributes of self._c_func.
Requires that self._c_func is not None.
Args:
attrs: a dictionary from attribute name to attribute proto value
"""
for name, attr_value in attrs.items():
serialized = attr_value.SerializeToString()
# TODO(skyewm): this creates and deletes a new TF_Status for every attr.
# It might be worth creating a convenient way to re-use the same status.
c_api.TF_FunctionSetAttrValueProto(self._c_func.func, compat.as_str(name),
serialized)
def _create_hash_str(self, input_arg, output_arg, node_def):
"""Creates an 8-character string unique to this input.
Args:
input_arg: the input_arg field of an OpDef
(e.g. self._definition.signature.input_arg)
output_arg: the output_arg field of an OpDef
(e.g. self._definition.signature.output_arg)
node_def: the node_def field of a FunctionDef
(e.g. self._definition.node_def)
Returns:
The unique string for this input
"""
hasher = hashlib.sha1()
def update_num(n):
hasher.update(compat.as_bytes("%x" % n))
def update_str(s):
update_num(len(s))
hasher.update(compat.as_bytes(s))
def update_strs(slist):
update_num(len(slist))
for s in slist:
update_str(s)
for adef in input_arg:
update_str(adef.SerializeToString())
for adef in output_arg:
update_str(adef.SerializeToString())
for n in sorted(node_def, key=lambda n: n.name):
update_str(n.name)
update_str(n.op)
update_strs(n.input)
update_num(len(n.attr))
# NOTE: protobuf map serialization does not guarantee ordering.
for k in sorted(n.attr):
update_str(k)
update_str(n.attr[k].SerializeToString())
return hasher.hexdigest()[:8]
def add_to_graph(self, g):
"""Adds this function into the graph g."""
self._create_definition_if_needed()
# Adds this function into 'g'.
# pylint: disable=protected-access
if context.executing_eagerly():
context.context().add_function_def(self.definition)
else:
g._add_function(self)
# pylint: enable=protected-access
# Ensures related sub-routines are defined in 'g', too.
for f in self._sub_functions.values():
f.add_to_graph(g)
# Adds its gradient function, too.
if self._grad_func:
self._grad_func.add_to_graph(g)
def __call__(self, *args, **kwargs):
self.add_to_graph(ops.get_default_graph())
args = [ops.convert_to_tensor(_) for _ in args] + self._extra_inputs
ret, op = _call(self._signature, *args, **kwargs)
# Set a hidden attr in 'op' so that gradients_impl can refer back
# to this _DefinedFunction instance to access python_grad_func.
assert isinstance(op, ops.Operation)
setattr(op, "__defun", self)
if self._shape_func is not None:
shapes = self._shape_func(op)
if len(shapes) != len(op.outputs):
raise ValueError("shape_func produced %d shapes for %d outputs" %
(len(shapes), len(op.outputs)))
for (t, shape) in zip(op.outputs, shapes):
t.set_shape(shape)
return ret
class _OverloadedFunction(object):
"""_OverloadedFunction encapsulates an overloaded function.
_OverloadedFunction maintains a mapping from input types to
instantiated _DefinedFunction in self._overload.
"""
def __init__(self,
func,
argnames,
func_name=None,
grad_func=None,
python_grad_func=None,
out_names=None,
**kwargs):
"""Creates _DefinedFunction.
Args:
func: A python callable which constructs a tf function body.
argnames: A list of strings for function argument names.
func_name: The function name. Defaults to None, in which derives from
'func'.
grad_func: This function's gradient function, if not None. Defaults
to None.
python_grad_func: A python callable implementing the gradient of
the function python-side.
out_names: A list of strings for the function return value names.
**kwargs: The keyword arguments. **kwargs is passed to every call
site of this function.
Raises:
ValueError: The function definition is invalid.
"""
self._func = func
self._argnames = argnames
self._func_name = func_name
assert grad_func is None or isinstance(grad_func, _OverloadedFunction)
self._grad_func = grad_func
self._python_grad_func = python_grad_func
self._out_names = out_names
self._extra_kwargs = kwargs
self._overload = {}
def instantiate(self, input_types):
"""Instantiate this function given input argument types.
Args:
input_types: A list of data types for the inputs.
Returns:
_DefinedFunction for the given input types.
"""
# Stringify the type list.
key = _type_list_to_str(input_types)
defined = self._overload.get(key)
if not defined:
# If not defined yet, define the function given the input types.
name = self._func_name
if name is not None:
name = "_".join([name, key])
defined = _DefinedFunction(
self._func,
self._argnames,
input_types,
name,
None,
self._python_grad_func,
out_names=self._out_names,
**self._extra_kwargs)
_ = defined.name # Fully instantiate the function definition.
if self._grad_func:
# If _grad_func is given, it is another
# _OverloadedFunction. We need to instantiate it with the
# right input types.
output_types = [
dtypes.DType(_.type) for _ in defined._signature.output_arg # pylint: disable=protected-access
]
# pylint: disable=protected-access
defined._grad_func = self._grad_func.instantiate(input_types +
output_types)
# pylint: enable=protected-access
self._overload[key] = defined
return defined
def __call__(self, *args, **kwargs):
input_types = []
args = list(args)
for (i, x) in enumerate(args):
x = ops.convert_to_tensor(x)
if not isinstance(x, ops.Tensor):
raise ValueError("Expect a Tensor but get ", x)
input_types.append(x.dtype)
args[i] = x
return self.instantiate(input_types)(*args, **kwargs)
class _FuncGraph(ops.Graph):
"""A helper for constructing a function.
_FuncGraph overrides ops.Graph's create_op() so that we can keep
track of all inputs into every op created inside the function. If
any input is from other graphs, we keep track of it in self.capture
and substitute the input with a place holder.
Each captured input's corresponding place holder is converted into a
function argument and the caller passes in the captured tensor.
"""
def __init__(self, name, capture_by_value, *args, **kwargs):
super(_FuncGraph, self).__init__(*args, **kwargs)
self._capture_by_value = capture_by_value
self._building_function = True
self._outer_graph = ops.get_default_graph()
self._vscope = vs.get_variable_scope()
self._old_custom_getter = self._vscope.custom_getter
# The name of the function.
self.name = name
# Placeholder tensors representing the inputs to this function. The tensors
# are in this _FuncGraph.
self.inputs = []
# Tensors that will be returned this function. The tensors are in this
# _FuncGraph.
self.outputs = []
# Maps external tensor -> internal tensor (e.g. input placeholder).
self._captured = {}
# The external tensors that have been captured as inputs and must be passed
# to this function (empty if capturing by value, otherwise these are the
# keys of _captured).
self.extra_inputs = []
# Input placeholders that been added for captured values (empty if capturing
# by value).
self.extra_args = []
# Captured variables.
# TODO(skyewm): is this needed?
self.extra_vars = []
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def container(self, container_name):
"""Returns a context manager that specifies the resource container to use.
Overridden from `tf.Graph` to update both the init_scope container
and the present inner container. This is necessary to make sure setting
containers applies correctly both to created variables and to stateful
ops.
Args:
container_name: container name string.
Returns:
A context manager for defining resource containers for stateful ops,
yields the container name.
"""
original_container = self._container
# pylint: disable=protected-access
with ops.init_scope():
original_init_container = ops.get_default_graph()._container
try:
self._container = container_name
with ops.init_scope():
ops.get_default_graph()._container = container_name
yield self._container
finally:
self._container = original_container
with ops.init_scope():
ops.get_default_graph()._container = original_init_container
# pylint: enable=protected-access
# pylint: enable=g-doc-return-or-yield
def getvar(
self,
getter,
name,
shape=None,
dtype=None,
initializer=None,
reuse=None,
trainable=True,
collections=None, # pylint: disable=redefined-outer-name
use_resource=None,
**kwargs):
"""A custom variable getter."""
# Here, we switch the default graph to the outer graph and ask the
# variable scope in which the function is defined to give us the
# variable. The variable is stashed in extra_vars and returned to
# the caller.
#
# We capture these variables so that the variable definition is
# hoisted upward to the outer most graph.
with self._outer_graph.as_default():
# pylint: disable=protected-access
var = self._vscope.get_variable(
vs._get_default_variable_store(),
name,
shape=shape,
dtype=dtype,
initializer=initializer,
reuse=reuse,
trainable=trainable,
collections=collections,
use_resource=use_resource)
self.extra_vars.append(var)
if isinstance(var, resource_variable_ops.ResourceVariable):
# For resource-based variables read the variable outside the function
# and pass in the value. This ensures that the function is pure and
# differentiable. TODO(apassos) this may have performance problems if
# the function will only do embedding lookups on the variable.
return var.value()
return var
def create_op(self, op_type, inputs, data_types, **kwargs):
for i, x in enumerate(inputs):
if isinstance(x, ops.EagerTensor) or x.graph is not self:
inputs[i] = self.capture(x)
return super(_FuncGraph, self).create_op(op_type, inputs, data_types,
**kwargs)
def capture(self, tensor, name=None):
"""Adds the given tensor to this graph and returns the captured tensor."""
if tensor in self._captured:
# Captured already.
return self._captured[tensor]
elif self._capture_by_value:
return self._add_tensor_and_parents(tensor)
else:
return self._capture_tensor_as_extra_input(tensor, name)
def _capture_tensor_as_extra_input(self, tensor, name=None):
# Substitute with a placeholder.
self.extra_inputs.append(tensor)
# Hoist the new input placeholder out of any control flow context
# we're currently in.
with ops.control_dependencies(None):
ph = array_ops.placeholder(
tensor.dtype, shape=tensor.get_shape(), name=name)
# pylint: disable=protected-access
if ops._USE_C_SHAPES:
if isinstance(tensor, ops.EagerTensor):
handle_data = tensor._handle_data
if handle_data:
handle_data = handle_data.SerializeToString()
else:
handle_data = c_api.GetHandleShapeAndType(tensor.graph._c_graph,
tensor._as_tf_output())
if handle_data:
c_api.SetHandleShapeAndType(ph.graph._c_graph, ph._as_tf_output(),
compat.as_bytes(handle_data))
else:
ph._handle_data = tensor._handle_data
# pylint: enable=protected-access
self.inputs.append(ph)
self._captured[tensor] = ph
self.extra_args.append(ph)
if _is_guaranteed_const(tensor):
with ops.control_dependencies(None):
return array_ops.guarantee_const(ph)
else:
return ph
def _add_tensor_and_parents(self, tensor):
op = self._add_op_and_parents(tensor.op)
return op.outputs[tensor.value_index]
def _add_op_and_parents(self, op):
# pylint: disable=protected-access
op_def = graph_to_function_def._get_op_def(op)
# pylint: enable=protected-access
if op_def.is_stateful:
raise ValueError("Cannot capture a stateful node (name:%s, type:%s) "
"by value." % (op.name, op.type))
elif op.type in ("Placeholder", "PlaceholderV2"):
raise ValueError("Cannot capture a placeholder (name:%s, type:%s) "
"by value." % (op.name, op.type))
captured_inputs = [self._add_tensor_and_parents(x) for x in op.inputs]
captured_op = self.create_op(
op.type,
captured_inputs, [o.dtype for o in op.outputs],
name=op.name,
attrs=op.node_def.attr,
op_def=op_def)
for t, captured_t in zip(op.outputs, captured_op.outputs):
self._captured[t] = captured_t
return captured_op
def func_graph_from_py_func(func, arg_names, arg_types, name=None,
capture_by_value=False, device=None,
colocation_stack=None, container=None,
collections_ref=None, arg_shapes=None):
"""Returns a _FuncGraph generated from `func`.
Args:
func: A Python callable which constructs a TF function body. The arguments
must correspond to `arg_types`. Returns a value or list/tuple of values.
No returned value can be None.
arg_names: A sequence of strings for the function argument names.
arg_types: A sequence of the function's argument types.
name: The function name. If None, the name is derived from `func`.
capture_by_value: boolean. If True, captured values will be copied into the
function body.
device: device name or function.
colocation_stack: A colocation stack (list) the _FuncGraph should use.
container: A container name the _FuncGraph should start with.
collections_ref: A reference to a collections dict the _FuncGraph should
use internally.
arg_shapes: A sequence of the function's argument shapes.
Returns:
A _FuncGraph.
Raises:
ValueError: if func returns None.
"""
if not name:
name = function_utils.get_func_name(func)
func_graph = _FuncGraph(name, capture_by_value)
with func_graph.as_default(), ops.device(device):
# pylint: disable=protected-access
if collections_ref is not None:
func_graph._collections = collections_ref
if container is not None:
func_graph._container = container
if colocation_stack is not None:
func_graph._colocation_stack = colocation_stack
# pylint: enable=protected-access
if arg_shapes is None:
arg_shapes = [None] * len(arg_types)
# Create placeholders for the function arguments.
for (argname, argtype, argshape) in zip(arg_names, arg_types, arg_shapes):
argholder = array_ops.placeholder(argtype, shape=argshape, name=argname)
func_graph.inputs.append(argholder)
# Call func and gather the output tensors.
with vs.variable_scope("", custom_getter=func_graph.getvar):
outputs = func(*func_graph.inputs)
# There is no way of distinguishing between a function not returning
# anything and a function returning None in Python.
# We need to allow the former and ideally want to forbid the latter as
# it is most likely user error.
# TODO(iga): Consider adding a @NoOutput decorator on top of @Defun to
# allow users to explicitly mark the function as not returning anything.
# For now, we allow a single None return and interpret it as a function
# with no output.
if outputs is None:
outputs = []
else:
# If func only returned one value, make it a tuple.
if not isinstance(outputs, (list, tuple)):
outputs = (outputs,)
if any([_ is None for _ in outputs]):
raise ValueError("Function can not return None.")
# Ensures each output is a Tensor in the function graph.
outputs = [ops.convert_to_tensor(t) for t in outputs]
outputs = [func_graph.capture(t) if t.graph is not func_graph else t
for t in outputs]
func_graph.outputs = outputs
return func_graph
def _is_guaranteed_const(tensor):
"""Determines whether `tensor` is guaranteed to be a constant.
A tensor is guaranteed to be a constant if either it was produced by
a `GuaranteeConst` op or if all of its children are guaranteed to be
constants.
Args:
tensor: The tensor for which to determine const-ness.
Returns:
True if `tensor` is guaranteed to be a constant, False otherwise.
"""
if isinstance(tensor, ops.EagerTensor):
return False
class Work(object):
def __init__(self, op, leaving):
self.op = op
self.leaving = leaving
is_guaranteed_const = lambda op: op.node_def.op == "GuaranteeConst"
constants = set([])
def all_inputs_const(op):
# If all inputs of an op are guaranteed constants, then we can infer that
# the op produces a constant as well.
return op.inputs and all(inp.op in constants for inp in op.inputs)
visited = set([])
stack = [Work(tensor.op, leaving=False)]
while stack:
work = stack.pop()
if work.leaving:
if all_inputs_const(work.op):
constants.add(work.op)
continue
visited.add(work.op)
if is_guaranteed_const(work.op):
constants.add(work.op)
continue
# This op will be revisited after all its inputs are checked for const-ness.
stack.append(Work(work.op, leaving=True))
for inp in work.op.inputs:
if inp.op not in visited:
stack.append(Work(inp.op, leaving=False))
return tensor.op in constants
def _call(sig, *inputs, **kwargs):
"""Adds a node calling a function.
This adds a `call` op to the default graph that calls the function
of signature `sig`, passing the tensors in `inputs` as arguments.
It returns the outputs of the call, which are one or more tensors.
`sig` is OpDefArg.a `_DefinedFunction` object.
You can pass an optional keyword parameter `name=string` to name the
added operation.
You can pass an optional keyword parameter `noinline=True|False` to
instruct the runtime not to inline the function body into the call
site.
Args:
sig: OpDefArg. The signature of the function.
*inputs: arguments to the function.
**kwargs: Optional keyword arguments. Can only contain 'name' or
'noinline'.
Returns:
A 2-element tuple. First element: a Tensor if the function returns a single
value; a list of Tensors if the function returns multiple value; the
Operation if the function returns no values. Second element: the Operation.
Raises:
ValueError: if the arguments are invalid.
"""
if len(inputs) != len(sig.input_arg):
raise ValueError("Expected number of arguments: %d, received: %d" % (len(
sig.input_arg), len(inputs)))
name = kwargs.pop("name", None)
g = ops.get_default_graph()
func_name = sig.name
attrs = _parse_kwargs_as_attrs(func_name, **kwargs)
output_types = [dtypes.DType(x.type) for x in sig.output_arg]
with ops.name_scope(name, func_name, inputs) as name:
op = g.create_op(
func_name,
list(inputs),
output_types,
name=name,
attrs=attrs,
op_def=sig,
compute_shapes=False)
if op.outputs:
if len(op.outputs) == 1:
ret = op.outputs[0]
else:
ret = tuple(op.outputs)
else:
ret = op
return ret, op
def _from_definition(fdef, grad_func=None):
"""Creates a _DefinedFunction initialized from a FunctionDef proto.
Args:
fdef: a FunctionDef
grad_func: a _DefinedFunction or None
Returns:
A _DefinedFunction representing fdef
"""
# TODO(iga): This method does major surgery on _DefinedFunction.
# Make it a named constructor using @classmethod of _DefinedFunction.
# The Python callable is only needed to create a FunctionDef. Since we have
# the FunctionDef here, we don't need to set _DefinedFunction._func (nor do we
# have access to such a callable here).
func = None
argnames = [arg.name for arg in fdef.signature.input_arg]
input_types = tuple(
dtypes.as_dtype(arg.type) for arg in fdef.signature.input_arg)
func_name = fdef.signature.name
# Note: FunctionDefs do not include python gradient functions, so if the
# original _DefinedFunction included one it will not be reflected here.
python_grad_func = None
out_names = [arg.name for arg in fdef.signature.output_arg]
result = _DefinedFunction(func, argnames, input_types, func_name, grad_func,
python_grad_func, out_names)
# pylint: disable=protected-access
serialized = fdef.SerializeToString()
c_func = c_api.TF_FunctionImportFunctionDef(serialized)
result._c_func = c_api_util.ScopedTFFunction(c_func)
result._extra_inputs = []
# pylint: enable=protected-access
return result
def _from_library(lib):
"""Creates _DefinedFunctions initialized from a FunctionDefLibrary proto.
This method handles assigning the correct gradient functions to each
function.
Args:
lib: a FunctionDefLibrary
Returns:
A list of _DefinedFunctions
Raises:
ValueError: `lib` is invalid
"""
if not lib.function and not lib.gradient:
return []
# function name -> FunctionDef proto
funcs = {fdef.signature.name: fdef for fdef in lib.function}
# Validate that all references function names have function defs
for g in lib.gradient:
if g.function_name not in funcs:
raise ValueError("FunctionDefLibrary missing '%s' FunctionDef\n%s" %
(g.function_name, str(lib)))
if g.gradient_func not in funcs:
raise ValueError("FunctionDefLibrary missing '%s' FunctionDef\n%s" %
(g.gradient_func, str(lib)))
# function name -> gradient function name
func_to_grad = collections.defaultdict(lambda: None)
# gradient function name -> names of functions having that grad function
grad_to_funcs = collections.defaultdict(list)
for gdef in lib.gradient:
func_to_grad[gdef.function_name] = gdef.gradient_func
grad_to_funcs[gdef.gradient_func].append(gdef.function_name)
# Start with functions without gradients
ready = [
fdef for fdef in lib.function if func_to_grad[fdef.signature.name] is None
]
if not ready:
raise ValueError(
"FunctionDefLibrary contains cyclic gradient functions!\n" + str(lib))
# function name -> _DefinedFunction
initialized = {}
while ready:
fdef = ready.pop()
name = fdef.signature.name
grad = initialized.get(func_to_grad[name])
if func_to_grad[name]:
assert grad
defined_func = _from_definition(fdef, grad_func=grad)
initialized[name] = defined_func
ready.extend(funcs[f] for f in grad_to_funcs[name])
return initialized.values()
def _get_experimental_kwarg_as_attr(attr_name, value):
"""Creates an AttrValue for a python object."""
if isinstance(value, bool):
return attr_value_pb2.AttrValue(b=value)
elif isinstance(value, int):
return attr_value_pb2.AttrValue(i=value)
elif isinstance(value, float):
return attr_value_pb2.AttrValue(f=value)
elif isinstance(value, str):
return attr_value_pb2.AttrValue(s=compat.as_bytes(value))
else:
raise ValueError("Unsupported attribute type for %s with type %s" %
(attr_name, type(value)))
def _parse_kwargs_as_attrs(func_name, **kwargs):
"""Parses **kwargs into a node's attributes."""
attrs = {}
noinline = kwargs.pop("noinline", None)
if noinline is not None:
attrs["_noinline"] = attr_value_pb2.AttrValue(b=bool(noinline))
compiled = kwargs.pop("compiled", None)
separate_compiled_gradients = kwargs.pop("separate_compiled_gradients", None)
if compiled is not None:
attrs["_XlaCompile"] = attr_value_pb2.AttrValue(b=bool(compiled))
attrs["_XlaSeparateCompiledGradients"] = attr_value_pb2.AttrValue(
b=bool(separate_compiled_gradients))
# Forward _XlaScope from enclosing context (if set), otherwise create new.
# pylint: disable=protected-access
if "_XlaScope" in ops.get_default_graph()._attr_scope_map:
attrs["_XlaScope"] = ops.get_default_graph()._attr_scope_map["_XlaScope"]
else:
attrs["_XlaScope"] = attr_value_pb2.AttrValue(
s=("function_%s" % func_name).encode())
# pylint: enable=protected-access
kwargs_keys = list(kwargs.keys())
for key in kwargs_keys:
if key.startswith("experimental_"):
attrs[key] = _get_experimental_kwarg_as_attr(key, kwargs[key])
del kwargs[key]
if kwargs:
raise ValueError("Unknown keyword arguments: %s" % kwargs.keys())
return attrs
def get_extra_vars():
"""Returns the captured variables by the function.
Returns:
If the default graph is being used to define a function, the
returned list of variables are those created inside the function
body so far. Otherwise, returns an empty list.
"""
g = ops.get_default_graph()
if isinstance(g, _FuncGraph):
return g.extra_vars
else:
return []
def get_extra_inputs():
"""Returns the captured input tensors by the function.
Returns:
If the default graph is being used to define a function, the
returned list of tensors are those accessed inside the function body
but defined outside the function body so far. Otherwise, returns an
empty list.
"""
g = ops.get_default_graph()
if isinstance(g, _FuncGraph):
return g.extra_inputs
else:
return []
def get_extra_args():
"""Returns the corresponding function arguments for the captured inputs.
Returns:
If the default graph is being used to define a function, the
returned list of place holders are those used inside the function
body corresponding those returned by get_extra_inputs(). Otherwise,
returns an empty list.
"""
g = ops.get_default_graph()
if isinstance(g, _FuncGraph):
return g.extra_args
else:
return []
def _type_list_to_str(types):
if any([_ not in _DTYPE_TO_STR for _ in types]):
raise ValueError("Unsupported dtypes: %s" % types)
return "".join([_DTYPE_TO_STR[_] for _ in types])
# NOTE: The list needs to be extended when more data types are added.
_DTYPE_TO_STR = {
dtypes.float16: "f16",
dtypes.float32: "f32",
dtypes.float64: "f64",
dtypes.int32: "i32",
dtypes.uint8: "i8",
dtypes.uint16: "u16",
dtypes.uint32: "u32",
dtypes.uint64: "u64",
dtypes.int16: "i16",
dtypes.int8: "i8",
dtypes.string: "s",
dtypes.complex64: "c64",
dtypes.complex128: "c128",
dtypes.int64: "i64",
dtypes.bool: "b",
dtypes.qint8: "qi8",
dtypes.quint8: "qu8",
dtypes.qint16: "qi16",
dtypes.quint16: "qu16",
dtypes.qint32: "qi32",
dtypes.bfloat16: "b16"
}
def function_def_from_tf_function(c_func):
"""Converts a SWIG-wrapped TF_Function* to a FunctionDef proto."""
with c_api_util.tf_buffer() as buf:
c_api.TF_FunctionToFunctionDef(c_func, buf)
data = c_api.TF_GetBuffer(buf)
fdef = function_pb2.FunctionDef()
fdef.ParseFromString(compat.as_bytes(data))
return fdef
| kobejean/tensorflow | tensorflow/python/framework/function.py | Python | apache-2.0 | 43,277 |
//*************************************************************
// Filename: socket.js
//
// Author: Jake Higgins <jth7036@rit.edu>
//*************************************************************
var Socket;
function addSocketListeners() {
Socket = new io();
Socket.on('sync objects', function(objects, room, caller) {
console.log(objects);
if(CallerID == caller) {
console.log(objects);
$.each(objects, function(key, object) {
createStroke(object);
});
CanvasManager.render();
}
});
Socket.on('add object', function(object, room, caller) {
if(CallerID != caller && RoomID == room) {
createStroke(object);
CanvasManager.clearCanvas();
}
});
Socket.on('move object', function(object, room, caller) {
console.log('move object');
if(CallerID != caller && RoomID == room) {
var targetObj = ObjectManager.findObject(object.objectID);
console.log(targetObj);
if(targetObj != null) {
targetObj.max = object.max;
targetObj.min = object.min;
$(targetObj.container).css({
top: targetObj.min.y,
left: targetObj.min.x
});
}
}
});
Socket.on('delete object', function(object, room, caller) {
if(CallerID != caller && RoomID == room)
{
ObjectManager.deleteObject(object.objectID);
}
});
Socket.on('clear objects', function(room, caller) {
console.log('clear');
if(CallerID != caller && RoomID == room) {
CanvasManager.clear(true);
}
});
Socket.on('draw', function(drawData, room, caller) {
if(CallerID != caller && RoomID == room) {
Drawing.draw(drawData, true);
}
});
// ======== Chat =============/
// Comes in the format message/roomID/caller
// if(roomID == this.roomID) // pseudocode for now
// add chat to chat thingy
Socket.on('receiveMessage', function(message, room, caller)
{
if ( RoomID == room )
{
// Proceed
Chat.write(message, caller);
}
});
}
function createStroke(stroke) {
console.log(stroke);
var obj = new object("stroke");
obj.initialize();
obj.imageData = stroke.imageData;
obj.layer = stroke.layer;
obj.max = stroke.max;
obj.min = stroke.min;
obj.objectID = stroke.objectID;
obj.type = "stroke";
obj.objectData = {
imageData: obj.imageData,
layer: obj.layer,
max: obj.max,
min: obj.min,
objectID: obj.objectID,
objectType: obj.type,
};
obj.createImage();
ObjectManager.addObject(obj);
} | IGME-Production-Studio/driftwoodrp | update/public/static/scripts/socket.js | JavaScript | apache-2.0 | 2,530 |
package ch.unibe.scg.regex;
import static java.util.Collections.singleton;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import ch.unibe.scg.regex.ParserProvider.Node;
import ch.unibe.scg.regex.ParserProvider.Node.Basic;
import ch.unibe.scg.regex.ParserProvider.Node.Group;
import ch.unibe.scg.regex.ParserProvider.Node.NonGreedyStar;
import ch.unibe.scg.regex.ParserProvider.Node.Optional;
import ch.unibe.scg.regex.ParserProvider.Node.Plus;
import ch.unibe.scg.regex.ParserProvider.Node.PositiveSet;
import ch.unibe.scg.regex.ParserProvider.Node.SetItem;
import ch.unibe.scg.regex.ParserProvider.Node.Simple;
import ch.unibe.scg.regex.ParserProvider.Node.Star;
import ch.unibe.scg.regex.ParserProvider.Node.Union;
import ch.unibe.scg.regex.TNFA.Builder;
import ch.unibe.scg.regex.Transition.Priority;
/**
* Not thread-safe! Use only from one thread at a time!
*
* @author nes
*/
class RegexToNFA {
final InputRangeCleanup inputRangeCleanup = new InputRangeCleanup();
TNFA convert(final Node node) {
Collection<InputRange> allInputRanges = new ArrayList<>();
allInputRanges.add(InputRange.ANY); // All regexes contain this implicitly.
findRanges(node, allInputRanges);
final Builder builder = Builder.make(allInputRanges);
builder.registerCaptureGroup(builder.captureGroupMaker.entireMatch);
final MiniAutomaton m =
makeInitialMiniAutomaton(builder, builder.captureGroupMaker.entireMatch);
final MiniAutomaton a = make(m, builder, node, builder.captureGroupMaker.entireMatch);
final State endTagger = builder.makeState();
builder.addEndTagTransition(a.finishing, endTagger, builder.captureGroupMaker.entireMatch,
Priority.NORMAL);
builder.setAsAccepting(endTagger);
return builder.build();
}
private void findRanges(Node n, Collection<InputRange> out) {
if (n instanceof Node.SetItem) {
out.add(((SetItem) n).inputRange);
}
for (Node c : n.getChildren()) {
findRanges(c, out);
}
}
static class MiniAutomaton {
final Collection<State> finishing;
final Collection<State> initial;
MiniAutomaton(final Collection<State> initial, final Collection<State> finishing) {
if (initial.iterator().next() == null) {
assert false;
}
this.initial = initial;
this.finishing = finishing;
}
MiniAutomaton(final Collection<State> initial, final State finishing) {
this(initial, singleton(finishing));
}
@Override
public String toString() {
return "" + initial + " -> " + finishing;
}
}
MiniAutomaton make(final MiniAutomaton last, final Builder builder, final Node node,
CaptureGroup captureGroup) {
MiniAutomaton ret;
if (node instanceof Node.Any) {
ret = makeAny(last, builder);
} else if (node instanceof Node.Char) {
ret = makeChar(last, builder, (Node.Char) node);
} else if (node instanceof Node.Simple) {
ret = makeSimple(last, builder, (Node.Simple) node, captureGroup);
} else if (node instanceof Node.Optional) {
ret = makeOptional(last, builder, (Node.Optional) node, captureGroup);
} else if (node instanceof Node.NonGreedyStar) {
ret = makeNonGreedyStar(last, builder, (Node.NonGreedyStar) node, captureGroup);
} else if (node instanceof Node.Star) {
ret = makeStar(last, builder, (Star) node, captureGroup);
} else if (node instanceof Node.Plus) {
ret = makePlus(last, builder, (Node.Plus) node, captureGroup);
} else if (node instanceof Node.Group) {
ret = makeGroup(last, builder, (Node.Group) node, captureGroup);
} else if (node instanceof Node.Eos) {
ret = makeEos(last, builder);
} else if (node instanceof Node.Char) {
ret = makeChar(last, builder, (Node.Char) node);
} else if (node instanceof Node.PositiveSet) {
ret = makePositiveSet(last, builder, (Node.PositiveSet) node);
} else if (node instanceof Node.Union) {
ret = makeUnion(last, builder, (Node.Union) node, captureGroup);
} else {
throw new AssertionError("Unknown node type: " + node);
}
assert !ret.initial.contains(null);
assert !ret.finishing.contains(null);
return ret;
}
MiniAutomaton makeAny(final MiniAutomaton last, final Builder builder) {
final State a = builder.makeState();
builder.addUntaggedTransition(InputRange.ANY, last.finishing, a);
return new MiniAutomaton(last.finishing, a);
}
MiniAutomaton makeChar(final MiniAutomaton last, final Builder b, final Node.Char character) {
final State a = b.makeState();
final MiniAutomaton ret = new MiniAutomaton(last.finishing, a);
b.addUntaggedTransition(character.inputRange, ret.initial, a);
return ret;
}
MiniAutomaton makeEos(final MiniAutomaton last, final Builder builder) {
final State a = builder.makeState();
builder.addUntaggedTransition(InputRange.EOS, last.finishing, a);
return new MiniAutomaton(last.finishing, a);
}
MiniAutomaton makeGroup(final MiniAutomaton last, final Builder builder, final Group group,
CaptureGroup parentCaptureGroup) {
final CaptureGroup cg = builder.makeCaptureGroup(parentCaptureGroup);
builder.registerCaptureGroup(cg);
final State startGroup = builder.makeState();
builder.addStartTagTransition(last.finishing, startGroup, cg, Priority.NORMAL);
final MiniAutomaton startGroupAutomaton = new MiniAutomaton(singleton(startGroup), singleton(startGroup));
final MiniAutomaton body = make(startGroupAutomaton, builder, group.body, cg);
final State endTag = builder.makeState();
builder.addEndTagTransition(body.finishing, endTag, cg, Priority.NORMAL);
return new MiniAutomaton(last.finishing, endTag);
}
MiniAutomaton makeInitialMiniAutomaton(final Builder builder, CaptureGroup entireMatch) {
final State init = builder.makeInitialState();
final State startTagger = builder.makeState();
builder.addStartTagTransition(singleton(init), startTagger, entireMatch, Priority.NORMAL);
return new MiniAutomaton(singleton(init), singleton(startTagger));
}
MiniAutomaton makeOptional(final MiniAutomaton last, final Builder builder,
final Optional optional, CaptureGroup captureGroup) {
final MiniAutomaton ma = make(last, builder, optional.elementary, captureGroup);
final List<State> f = new ArrayList<>(last.finishing);
f.addAll(ma.finishing);
return new MiniAutomaton(last.finishing, f);
}
MiniAutomaton makePlus(final MiniAutomaton last, final Builder builder, final Plus plus,
CaptureGroup captureGroup) {
final MiniAutomaton inner = make(last, builder, plus.elementary, captureGroup);
Collection<State> out = singleton(builder.makeState());
builder.makeUntaggedEpsilonTransitionFromTo(inner.finishing, out, Priority.LOW);
final MiniAutomaton ret = new MiniAutomaton(last.finishing, out);
builder.makeUntaggedEpsilonTransitionFromTo(inner.finishing,
inner.initial, Priority.NORMAL);
return ret;
}
MiniAutomaton makeUnion(MiniAutomaton last, Builder builder, Union union,
CaptureGroup captureGroup) {
MiniAutomaton left = make(last, builder, union.left, captureGroup);
MiniAutomaton right = make(last, builder, union.right, captureGroup);
Collection<State> out = singleton(builder.makeState());
builder.makeUntaggedEpsilonTransitionFromTo(left.finishing, out, Priority.NORMAL);
builder.makeUntaggedEpsilonTransitionFromTo(right.finishing, out, Priority.LOW);
return new MiniAutomaton(last.finishing, out);
}
MiniAutomaton makePositiveSet(final MiniAutomaton last, final Builder builder,
final PositiveSet set) {
final List<SetItem> is = set.items;
final SortedSet<InputRange> ranges = new TreeSet<>();
for (final SetItem i : is) {
ranges.add(i.inputRange);
}
final List<InputRange> rangesList = new ArrayList<>(ranges);
final List<InputRange> cleanedRanges = inputRangeCleanup.cleanUp(rangesList);
final State a = builder.makeState();
for (InputRange range : cleanedRanges) {
builder.addUntaggedTransition(range, last.finishing, a);
}
return new MiniAutomaton(last.finishing, a);
}
MiniAutomaton makeSimple(final MiniAutomaton last, final Builder b, final Simple simple,
CaptureGroup captureGroup) {
final List<? extends Basic> bs = simple.basics;
MiniAutomaton lm = last;
for (final Basic e : bs) {
lm = make(lm, b, e, captureGroup);
}
return new MiniAutomaton(last.finishing, lm.finishing);
}
MiniAutomaton makeNonGreedyStar(MiniAutomaton last, Builder builder, NonGreedyStar nonGreedyStar,
CaptureGroup captureGroup) {
// Make start state and connect.
State start = builder.makeState();
builder.makeUntaggedEpsilonTransitionFromTo(last.finishing, singleton(start), Priority.NORMAL);
// Make inner machine.
MiniAutomaton innerLast = new MiniAutomaton(last.finishing, start);
final MiniAutomaton inner = make(innerLast, builder, nonGreedyStar.elementary, captureGroup);
// Connect inner machine back to start.
builder.makeUntaggedEpsilonTransitionFromTo(inner.finishing, singleton(start), Priority.LOW);
// Make and connect `out` state.
State out = builder.makeState();
builder.makeUntaggedEpsilonTransitionFromTo(singleton(start), singleton(out), Priority.NORMAL);
return new MiniAutomaton(last.finishing, out);
}
MiniAutomaton makeStar(final MiniAutomaton last, final Builder builder, final Star star,
CaptureGroup captureGroup) {
// Make start state and connect.
State start = builder.makeState();
builder.makeUntaggedEpsilonTransitionFromTo(last.finishing, singleton(start), Priority.NORMAL);
// Make inner machine.
MiniAutomaton innerLast = new MiniAutomaton(singleton(start), start);
final MiniAutomaton inner = make(innerLast, builder, star.elementary, captureGroup);
// Connect inner machine back to start.
builder.makeUntaggedEpsilonTransitionFromTo(inner.finishing, singleton(start), Priority.NORMAL);
// Make and connect `out` state.
State out = builder.makeState();
builder.makeUntaggedEpsilonTransitionFromTo(singleton(start), singleton(out), Priority.LOW);
return new MiniAutomaton(last.finishing, out);
}
}
| nes1983/tree-regex | src/ch/unibe/scg/regex/RegexToNFA.java | Java | apache-2.0 | 10,402 |
/*
* Copyright (c) 2015 TextGlass
*
* 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.
*
*/
public class TransformerIsNumber implements Transformer {
@Override
public String transform(String input) throws Exception {
try {
Double.parseDouble(input);
} catch(NumberFormatException nfe) {
throw new Exception(nfe.toString());
}
return input;
}
@Override
public String toString() {
return "TransformerIsNumber";
}
}
| TextGlass/reference | client/src/TransformerIsNumber.java | Java | apache-2.0 | 972 |
/*
* Copyright (c) 2017 Martin Pfeffer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pepperonas.materialdialog.adapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.pepperonas.materialdialog.R;
import com.pepperonas.materialdialog.utils.Utils;
import java.util.List;
/**
* @author Martin Pfeffer (pepperonas)
*/
public class ShareAdapter extends BaseAdapter {
private Object[] items;
private LayoutInflater mInflater;
private Context mCtx;
private Typeface mTypeface;
public ShareAdapter(@NonNull Context context) {
this.mInflater = LayoutInflater.from(context);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("text/plain");
List activities = context.getPackageManager().queryIntentActivities(sendIntent, 0);
items = activities.toArray();
mCtx = context;
}
public ShareAdapter(@NonNull Context context, Typeface typeface) {
this.mInflater = LayoutInflater.from(context);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("text/plain");
List activities = context.getPackageManager().queryIntentActivities(sendIntent, 0);
items = activities.toArray();
mCtx = context;
mTypeface = typeface;
}
public int getCount() {
return items.length;
}
public Object getItem(int position) {
return items[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_list_item_share_app, null);
holder = new ViewHolder();
holder.logo = (ImageView) convertView.findViewById(R.id.iv_simple_list_item_share_app);
holder.name = (TextView) convertView.findViewById(R.id.tv_simple_list_item_share_app);
if (mTypeface != null) {
holder.name.setTypeface(mTypeface);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(((ResolveInfo) items[position]).activityInfo
.applicationInfo.loadLabel(mCtx.getPackageManager()).toString());
holder.logo.setImageDrawable(((ResolveInfo) items[position]).activityInfo
.applicationInfo.loadIcon(mCtx.getPackageManager()));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(
Utils.dp2px(mCtx, 16),
Utils.dp2px(mCtx, 4),
Utils.dp2px(mCtx, 4),
Utils.dp2px(mCtx, 4));
holder.logo.setLayoutParams(layoutParams);
return convertView;
}
static class ViewHolder {
TextView name;
ImageView logo;
}
} | pepperonas/MaterialDialog | library/src/main/java/com/pepperonas/materialdialog/adapter/ShareAdapter.java | Java | apache-2.0 | 3,990 |
// Copyright Istio 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 forwarder
import (
"bytes"
"fmt"
"net/http"
"istio.io/pkg/log"
)
const (
hostHeader = "Host"
)
var fwLog = log.RegisterScope("forwarder", "echo clientside", 0)
func writeHeaders(requestID int, header http.Header, outBuffer bytes.Buffer, addFn func(string, string)) {
for key, values := range header {
for _, v := range values {
addFn(key, v)
if key == hostHeader {
outBuffer.WriteString(fmt.Sprintf("[%d] Host=%s\n", requestID, v))
} else {
outBuffer.WriteString(fmt.Sprintf("[%d] Header=%s:%s\n", requestID, key, v))
}
}
}
}
| istio/istio | pkg/test/echo/server/forwarder/util.go | GO | apache-2.0 | 1,156 |
package com.siqisoft.stone.admin.dict.controller;
import java.util.List;
import org.siqisource.stone.dict.model.Dict;
import org.siqisource.stone.dict.service.DictService;
import org.siqisource.stone.orm.condition.Condition;
import org.siqisource.stone.ui.AjaxResponse;
import org.siqisource.stone.ui.Notify;
import org.siqisource.stone.ui.easyui.PagedRows;
import org.siqisource.stone.ui.easyui.Paging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.siqisoft.stone.admin.dict.service.DictConditionBuilder;
@Controller
public class DictController {
@Autowired
DictService service;
@RequestMapping("/dict/DictList.do")
public String list(Model model) {
return "dict/DictList";
}
@RequestMapping("/dict/dictListData.do")
@ResponseBody
public PagedRows<Dict> listData(DictQueryForm dictQueryForm, Paging paging) {
Condition condition = DictConditionBuilder.listCondition(dictQueryForm);
int count = service.count(condition);
List<Dict> dictList = service.list(condition, paging.getRowBounds());
return new PagedRows<Dict>(count, dictList);
}
@RequestMapping("/dict/DictRead.do")
public String read(String code, Model model) {
Dict dict = service.read(code);
model.addAttribute("dict", dict);
return "dict/DictRead";
}
@RequestMapping("/dict/DictAddInit.do")
public String addInit(Dict dict, Model model) {
return "dict/DictAdd";
}
@RequestMapping("/dict/DictAdd.do")
public String add(Dict dict, Model model) {
service.insert(dict);
return this.read(dict.getCode(), model);
}
@RequestMapping("/dict/dictDelete.do")
@ResponseBody
public AjaxResponse delete(String[] codeList, Model model) {
// 判断是否被关联
if (codeList != null) {
service.deleteBatch(codeList);
}
return new Notify("成功删除"+codeList.length+"条记录");
}
@RequestMapping("/dict/DictEditInit.do")
public String editInit(String code, Model model) {
Dict dict = service.read(code);
model.addAttribute("dict", dict);
return "dict/DictEdit";
}
@RequestMapping("/dict/DictEdit.do")
public String edit(Dict dict, Model model) {
service.update(dict);
return this.read(dict.getCode(), model);
}
}
| ylyxf/stone-sdk | src/main/java/com/siqisoft/stone/admin/dict/controller/DictController.java | Java | apache-2.0 | 2,471 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.listeners;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.psi.PsiElement;
/**
* Refactorings invoke {@link #getListener(com.intellij.psi.PsiElement)} of registered
* {@linkplain RefactoringElementListenerProvider} before particular element is subjected to refactoring.
* @author dsl
*/
public interface RefactoringElementListenerProvider {
ExtensionPointName<RefactoringElementListenerProvider> EP_NAME = ExtensionPointName.create("com.intellij.refactoring.elementListenerProvider");
/**
*
* Should return a listener for particular element. Invoked in read action.
*/
@javax.annotation.Nullable
RefactoringElementListener getListener(PsiElement element);
}
| consulo/consulo | modules/base/lang-api/src/main/java/com/intellij/refactoring/listeners/RefactoringElementListenerProvider.java | Java | apache-2.0 | 1,347 |
/*
* Copyright 2016 Shredder121.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.shredder121.gh_event_api.handler.pull_request;
/**
* The handler interface for receiving {@code pull_request} events.
*
* @author Shredder121
*/
@FunctionalInterface
public interface PullRequestHandler {
void handle(PullRequestPayload payload);
}
| johnktims/gh-event-api | src/main/java/com/github/shredder121/gh_event_api/handler/pull_request/PullRequestHandler.java | Java | apache-2.0 | 873 |
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Model extends CI_Model {
// Variável que define o nome da tabela
var $table = "";
/**
* Método Construtor
*/
function __construct() {
parent::__construct();
}
/**
* Insere um registro na tabela
*
* @param array $data Dados a serem inseridos
*
* @return boolean
*/
function Inserir($data) {
if(!isset($data))
return false;
return $this->db->insert($this->table, $data);
}
/**
* Recupera um registro a partir de um ID
*
* @param integer $id ID do registro a ser recuperado
*
* @return array
*/
function GetById($id) {
if(is_null($id))
return false;
$this->db->where('id', $id);
$query = $this->db->get($this->table);
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return null;
}
}
/**
* Lista todos os registros da tabela
*
* @param string $sort Campo para ordenação dos registros
*
* @param string $order Tipo de ordenação: ASC ou DESC
*
* @return array
*/
function GetAll($sort = 'id', $order = 'asc') {
// $this->db->where('servico', 'Website');
$this->db->order_by($sort, $order);
$query = $this->db->get($this->table);
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return null;
}
}
function GetAllFace($sort = 'id', $order = 'asc') {
$this->db->where("servico like '%Facebook%'");
$this->db->order_by($sort, $order);
$query = $this->db->get($this->table);
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return null;
}
}
function GetAllSite($sort = 'id', $order = 'asc') {
$this->db->where("servico like '%Website%'");
$this->db->order_by($sort, $order);
$query = $this->db->get($this->table);
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return null;
}
}
function GetAllMail($sort = 'id', $order = 'asc') {
$this->db->where("servico like '%Mail%'");
$this->db->order_by($sort, $order);
$query = $this->db->get($this->table);
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return null;
}
}
/**
* Atualiza um registro na tabela
*
* @param integer $int ID do registro a ser atualizado
*
* @param array $data Dados a serem inseridos
*
* @return boolean
*/
function Atualizar($id, $data) {
if(is_null($id) || !isset($data))
return false;
$this->db->where('id', $id);
return $this->db->update($this->table, $data);
}
/**
* Remove um registro na tabela
*
* @param integer $int ID do registro a ser removido
*
*
* @return boolean
*/
function Excluir($id) {
if(is_null($id))
return false;
$this->db->where('id', $id);
return $this->db->delete($this->table);
}
}
/* End of file */
| ChristianHerber/UebiControl | application/core/MY_Model.php | PHP | apache-2.0 | 2,979 |
package com.vertabelo.mobileorm.myplaces.orm.gen;
public class AddressViewDAOImpl
extends com.vertabelo.mobileorm.myplaces.orm.runtime.dao.BaseDAO<AddressView>
implements AddressViewDAO {
public AddressViewDAOImpl(com.vertabelo.mobileorm.myplaces.orm.runtime.util.SQLiteDataSource dataSource) {
super(dataSource);
}
public AddressViewDAOImpl(com.vertabelo.mobileorm.myplaces.orm.runtime.util.SQLiteDataSource dataSource,
com.vertabelo.mobileorm.myplaces.orm.runtime.util.DAOMonitor daoMonitor) {
super(dataSource, daoMonitor);
}
@Override
public Class<AddressView> getPojoClass() {
return POJO_CLASS;
}
@Override
public com.vertabelo.mobileorm.myplaces.orm.runtime.query.TableExpression getTableExpression() {
return TABLE_EXPRESSION;
}
@Override
public com.vertabelo.mobileorm.myplaces.orm.runtime.util.ResultSetHandler getResultSetHandler() {
return RESULT_SET_HANDLER;
}
@Override
public java.util.List<AddressView> getAddressViewList() {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION);
com.vertabelo.mobileorm.myplaces.orm.runtime.dao.SelectObjectListResult<AddressView>
selectObjectListResult = select(query, RESULT_SET_HANDLER);
return selectObjectListResult.getObjectList();
}
@Override
public java.util.List<AddressView> getAddressViewList(com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp orderBy) {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION);
query.orderBy(orderBy);
com.vertabelo.mobileorm.myplaces.orm.runtime.dao.SelectObjectListResult<AddressView>
selectObjectListResult = select(query, RESULT_SET_HANDLER);
return selectObjectListResult.getObjectList();
}
@Override
public java.util.List<AddressView> getAddressViewList(com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp orderBy, com.vertabelo.mobileorm.myplaces.orm.runtime.query.OrderByDirection asc) {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION);
query.orderBy(orderBy, asc);
com.vertabelo.mobileorm.myplaces.orm.runtime.dao.SelectObjectListResult<AddressView>
selectObjectListResult = select(query, RESULT_SET_HANDLER);
return selectObjectListResult.getObjectList();
}
@Override
public java.util.List<AddressView> getAddressViewList(com.vertabelo.mobileorm.myplaces.orm.runtime.query.LExp where) {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION);
query.setWhere(where);
com.vertabelo.mobileorm.myplaces.orm.runtime.dao.SelectObjectListResult<AddressView>
selectObjectListResult = select(query, RESULT_SET_HANDLER);
return selectObjectListResult.getObjectList();
}
@Override
public java.util.List<AddressView> getAddressViewList(com.vertabelo.mobileorm.myplaces.orm.runtime.query.LExp where,
com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp orderBy) {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION);
query.setWhere(where);
query.orderBy(orderBy);
com.vertabelo.mobileorm.myplaces.orm.runtime.dao.SelectObjectListResult<AddressView>
selectObjectListResult = select(query, RESULT_SET_HANDLER);
return selectObjectListResult.getObjectList();
}
@Override
public java.util.List<AddressView> getAddressViewList(com.vertabelo.mobileorm.myplaces.orm.runtime.query.LExp where,
com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp orderBy, com.vertabelo.mobileorm.myplaces.orm.runtime.query.OrderByDirection asc) {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION);
query.setWhere(where);
query.orderBy(orderBy, asc);
com.vertabelo.mobileorm.myplaces.orm.runtime.dao.SelectObjectListResult<AddressView>
selectObjectListResult = select(query, RESULT_SET_HANDLER);
return selectObjectListResult.getObjectList();
}
@Override
public Long getCount() {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION,
com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp.fun("COUNT",
com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp.ASTERISK));
java.util.List<Long> list = select(query, new com.vertabelo.mobileorm.myplaces.orm.runtime.util.handlers.LongResultSetHandler()).getObjectList();
if (list.size() > 1) {
throw new RuntimeException("More than one object returned");
} else if (list.size() == 1) {
return list.get(0);
} else {
throw new RuntimeException("Cannot retrieve count() method result");
}
}
@Override
public Long getCount(com.vertabelo.mobileorm.myplaces.orm.runtime.query.LExp where) {
com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery query =
new com.vertabelo.mobileorm.myplaces.orm.runtime.query.SelectQuery(TABLE_EXPRESSION,
com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp.fun("COUNT",
com.vertabelo.mobileorm.myplaces.orm.runtime.query.AExp.ASTERISK));
query.setWhere(where);
java.util.List<Long> list = select(query, new com.vertabelo.mobileorm.myplaces.orm.runtime.util.handlers.LongResultSetHandler()).getObjectList();
if (list.size() > 1) {
throw new RuntimeException("More than one object returned");
} else if (list.size() == 1) {
return list.get(0);
} else {
throw new RuntimeException("Cannot retrieve count() method result");
}
}
}
| Vertabelo/mobiorm-demo-android | app/src/main/java/com/vertabelo/mobileorm/myplaces/orm/gen/AddressViewDAOImpl.java | Java | apache-2.0 | 6,557 |
package misc
// TrackedRepo identifies a git remote repository.
type TrackedRepo string
| kubernetes-sigs/kustomize | cmd/gorepomod/internal/misc/trackedrepo.go | GO | apache-2.0 | 89 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.generation;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.intention.AddAnnotationPsiFix;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.intellij.codeInsight.AnnotationUtil.CHECK_EXTERNAL;
import static com.intellij.codeInsight.AnnotationUtil.CHECK_TYPE;
/**
* @author anna
*/
public interface OverrideImplementsAnnotationsHandler {
ExtensionPointName<OverrideImplementsAnnotationsHandler> EP_NAME = ExtensionPointName.create("com.intellij.overrideImplementsAnnotationsHandler");
/**
* Returns annotations which should be copied from a source to an implementation (by default, no annotations are copied).
*/
default String[] getAnnotations(@NotNull PsiFile file) {
//noinspection deprecation
return getAnnotations(file.getProject());
}
/**
* @deprecated Use {@link #getAnnotations(PsiFile)}
*/
@Deprecated
String[] getAnnotations(Project project);
@Deprecated
@NotNull
default String[] annotationsToRemove(Project project, @NotNull String fqName) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
/** Perform post processing on the annotations, such as deleting or renaming or otherwise updating annotations in the override */
default void cleanup(PsiModifierListOwner source, @Nullable PsiElement targetClass, PsiModifierListOwner target) {
}
static void repeatAnnotationsFromSource(PsiModifierListOwner source, @Nullable PsiElement targetClass, PsiModifierListOwner target) {
Module module = ModuleUtilCore.findModuleForPsiElement(targetClass != null ? targetClass : target);
GlobalSearchScope moduleScope = module != null ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : null;
Project project = target.getProject();
JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
for (OverrideImplementsAnnotationsHandler each : EP_NAME.getExtensionList()) {
for (String annotation : each.getAnnotations(target.getContainingFile())) {
if (moduleScope != null && facade.findClass(annotation, moduleScope) == null) continue;
int flags = CHECK_EXTERNAL | CHECK_TYPE;
if (AnnotationUtil.isAnnotated(source, annotation, flags) && !AnnotationUtil.isAnnotated(target, annotation, flags)) {
each.transferToTarget(annotation, source, target);
}
}
}
for (OverrideImplementsAnnotationsHandler each : EP_NAME.getExtensionList()) {
each.cleanup(source, targetClass, target);
}
}
default void transferToTarget(String annotation, PsiModifierListOwner source, PsiModifierListOwner target) {
PsiModifierList modifierList = target.getModifierList();
assert modifierList != null : target;
PsiAnnotation srcAnnotation = AnnotationUtil.findAnnotation(source, annotation);
PsiNameValuePair[] valuePairs = srcAnnotation != null ? srcAnnotation.getParameterList().getAttributes() : PsiNameValuePair.EMPTY_ARRAY;
AddAnnotationPsiFix.addPhysicalAnnotation(annotation, valuePairs, modifierList);
}
} | paplorinc/intellij-community | java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementsAnnotationsHandler.java | Java | apache-2.0 | 3,542 |
package io.omengye.common.utils.constants;
public class Constants {
private Constants(){}
public static final String RESULT_FLAG = "flag";
}
| omengye/ws | common/src/main/java/io/omengye/common/utils/constants/Constants.java | Java | apache-2.0 | 153 |
/**
* Copyright 2017 dialog LLC <info@dlg.im>
* @flow
*/
import type { PeerInfo } from '@dlghq/dialog-types';
import type { AvatarSize } from '../Avatar/getAvatarSize';
import type { Gradient } from '../Avatar/getAvatarColor';
import React, { PureComponent } from 'react';
import classNames from 'classnames';
import getAvatarSize from '../Avatar/getAvatarSize';
import getAvatarText from '../Avatar/getAvatarText';
import getAvatarColor from '../Avatar/getAvatarColor';
import createSequence from '../../utils/createSequence';
import styles from '../PeerAvatar/PeerAvatar.css';
export type Props = {
className?: string,
peerBig: PeerInfo,
peerSmall: PeerInfo,
size: AvatarSize,
onClick?: (event: SyntheticMouseEvent) => any
};
type DefaultProps = {
size: AvatarSize
};
const seq = createSequence();
class DoublePeerAvatar extends PureComponent<DefaultProps, Props, void> {
id: string;
ids: {
big: string,
clip: string,
small: string
};
static defaultProps = {
size: 'medium'
};
constructor(props: Props) {
super(props);
this.id = 'double_peer_avatar_' + seq.next();
this.ids = {
big: `${this.id}_big`,
clip: `${this.id}_big_clip`,
small: `${this.id}_small`
};
}
getAvatarSize(): number {
return getAvatarSize(this.props.size);
}
renderDefsBig(): React.Element<any> {
if (this.props.peerBig.avatar) {
return (
<pattern id={this.ids.big} width="100%" height="100%" patternUnits="userSpaceOnUse">
<image
x="0"
y="0"
width="100px"
height="100px"
xlinkHref={this.props.peerBig.avatar}
/>
</pattern>
);
}
const colors: Gradient = getAvatarColor(this.props.peerBig.placeholder);
return (
<linearGradient
id={this.ids.big}
gradientUnits="userSpaceOnUse"
x1="6.79%"
y1="105.31%"
x2="93.21%"
y2="-5.31%"
>
<stop stopColor={colors.payload.from} />
<stop offset="1" stopColor={colors.payload.to} />
</linearGradient>
);
}
renderClipMaskBig(): React.Element<any> {
return (
<clipPath id={this.ids.clip}>
<path
// eslint-disable-next-line
d="M58.2070074,99.3297063 C55.5367715,99.7706374 52.795171,100 50,100 C22.3857625,100 0,77.6142375 0,50 C0,22.3857625 22.3857625,0 50,0 C77.6142375,0 100,22.3857625 100,50 C100,52.795171 99.7706374,55.5367715 99.3297063,58.2070074 C94.8434182,55.5348957 89.6009561,54 84,54 C67.4314575,54 54,67.4314575 54,84 C54,89.6009561 55.5348957,94.8434182 58.2070074,99.3297063 Z"
/>
</clipPath>
);
}
renderDefsSmall(): React.Element<any> {
if (this.props.peerSmall.avatar) {
return (
<pattern
id={this.ids.small}
width="100%"
height="100%"
x="58"
y="58"
patternUnits="userSpaceOnUse"
>
<image
x="0"
y="0"
width="100px"
height="100px"
xlinkHref={this.props.peerSmall.avatar}
transform="scale(0.507046569,0.507046569)"
/>
</pattern>
);
}
const colors: Gradient = getAvatarColor(this.props.peerSmall.placeholder);
return (
<linearGradient
id={this.ids.small}
gradientUnits="userSpaceOnUse"
x1="6.79%"
y1="105.31%"
x2="93.21%"
y2="-5.31%"
>
<stop stopColor={colors.payload.from} />
<stop offset="1" stopColor={colors.payload.to} />
</linearGradient>
);
}
renderSmallAvatar(): React.Element<any> {
return (
<circle cx="84" cy="84" r="25" fill={`url(#${this.ids.small})`} />
);
}
renderBigAvatar(): React.Element<any> {
return (
<path
// eslint-disable-next-line
d="M58.2070074,99.3297063 C55.5367715,99.7706374 52.795171,100 50,100 C22.3857625,100 0,77.6142375 0,50 C0,22.3857625 22.3857625,0 50,0 C77.6142375,0 100,22.3857625 100,50 C100,52.795171 99.7706374,55.5367715 99.3297063,58.2070074 C94.8434182,55.5348957 89.6009561,54 84,54 C67.4314575,54 54,67.4314575 54,84 C54,89.6009561 55.5348957,94.8434182 58.2070074,99.3297063 Z"
fill={`url(#${this.ids.big})`}
/>
);
}
renderPeerSmallText(): ?React.Element<any> {
if (this.props.peerSmall.avatar) {
return null;
}
const size = this.getAvatarSize();
const text = size >= 20 ? getAvatarText(this.props.peerSmall.title) : null;
const twoChars = Boolean(text && text.length !== 1);
const textStyles = {
fontSize: twoChars ? 20 : 24
};
return (
<text
className={styles.text}
x="84"
y="84"
textAnchor="middle"
alignmentBaseline="central"
dominantBaseline="central"
style={textStyles}
>
{text}
</text>
);
}
renderPeerBigText(): ?React.Element<any> {
if (this.props.peerBig.avatar) {
return null;
}
const size = this.getAvatarSize();
const text = size >= 20 ? getAvatarText(this.props.peerBig.title) : null;
const twoChars = Boolean(text && text.length !== 1);
const textStyles = {
fontSize: twoChars ? 38 : 48
};
return (
<text
className={styles.text}
x="50"
y="50"
textAnchor="middle"
alignmentBaseline="central"
dominantBaseline="central"
style={textStyles}
clipPath={`url(#${this.ids.clip})`}
>
{text}
</text>
);
}
render(): React.Element<any> {
const className = classNames(styles.container, {
[styles.clickable]: this.props.onClick
}, this.props.className);
const size = this.getAvatarSize();
return (
<svg
viewBox="0 0 109 109"
width={size}
height={size}
className={className}
onClick={this.props.onClick}
>
<defs>
{this.renderDefsBig()}
{this.renderClipMaskBig()}
{this.renderDefsSmall()}
</defs>
{this.renderBigAvatar()}
{this.renderSmallAvatar()}
{this.renderPeerBigText()}
{this.renderPeerSmallText()}
</svg>
);
}
}
export default DoublePeerAvatar;
| nolawi/champs-dialog-sg | src/components/DoublePeerAvatar/DoublePeerAvatar.js | JavaScript | apache-2.0 | 6,308 |
# ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] benjamin@bengfort.com $
"""
Helper module for ORMBad version information.
"""
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 1,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
"""
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0],
__version_info__['serial']))
return ''.join(vers)
| tipsybear/ormbad | ormbad/version.py | Python | apache-2.0 | 1,161 |
/**
* Created by raj on 19/8/14.
*/
var fs = require('fs');
var content = fs.read ('animeEpisode.json');
console.log(JSON.stringify(JSON.parse(content)[1][0].title));
videolinks=JSON.parse(content);
links=[];
function pages(k) {
var page = new WebPage();
page.open('http://www.gogoanime.com/', function (status) {
console.log('opened gogoanime :++++ ', status);
if (status==fail){
page.close();
pages(k);
}
if (status == success) {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function () {
console.log('jq included')
var data = page.evaluate(function (data) {
var tempdata=[];
for (var i = 0; i <$('.post div:eq(1) table tbody tr td:eq(0) ul').length; i = i + 1) {
data.links.push($('.post div:eq(1) table tbody tr td:eq(0) ul li a').attr('href'));
}
return JSON.stringify(data);
});
links[k][m] = JSON.parse(data);
console.log(data);
if (m < links[k].length - 1) {
page.close();
console.log('next episoide called');
pages(k, m + 1);
}
;
if (m == links[k].length - 1) {
page.close();
console.log('next anime called');
var path = 'links.json';
fs.write(path, links[k], 'w');
pages(k + 1, 1);
}
if (k == links.length - 1) {
var path = 'links.json';
fs.write(path, links, 'w');
}
});
}
});
}
pages(1,1); | msandeepraj211/phantom | recent.js | JavaScript | apache-2.0 | 1,995 |
#!/usr/bin/python
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example creates a bidder-level filter set.
A bidder-level filter set can be used to retrieve aggregated data for all
Authorized Buyers accounts under the given bidder account, including the bidder
account itself.
"""
import argparse
from datetime import date
from datetime import datetime
from datetime import timedelta
import os
import pprint
import sys
import uuid
sys.path.insert(0, os.path.abspath('..'))
from googleapiclient.errors import HttpError
import samples_util
_DATE_FORMAT = '%Y%m%d'
_FILTER_SET_NAME_TEMPLATE = ('bidders/{bidders_resource_id}/'
'filterSets/{filtersets_resource_id}')
_OWNER_NAME_TEMPLATE = 'bidders/{bidders_resource_id}'
_TODAY = date.today()
_VALID_ENVIRONMENTS = ('WEB', 'APP')
_VALID_FORMATS = ('DISPLAY', 'VIDEO')
_VALID_PLATFORMS = ('DESKTOP', 'TABLET', 'MOBILE')
_VALID_TIME_SERIES_GRANULARITIES = ('HOURLY', 'DAILY')
DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_FILTER_SET_RESOURCE_ID = f'FilterSet_{uuid.uuid4()}'
DEFAULT_END_DATE = _TODAY.strftime(_DATE_FORMAT)
DEFAULT_START_DATE = (_TODAY - timedelta(days=7)).strftime(
_DATE_FORMAT)
def main(ad_exchange_buyer, owner_name, body, is_transient):
try:
# Construct and execute the request.
filter_set = ad_exchange_buyer.bidders().filterSets().create(
ownerName=owner_name, isTransient=is_transient, body=body).execute()
print(f'FilterSet created for bidder: "{owner_name}".')
pprint.pprint(filter_set)
except HttpError as e:
print(e)
if __name__ == '__main__':
def time_series_granularity_type(s):
if s not in _VALID_TIME_SERIES_GRANULARITIES:
raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity '
f'specified: "{s}".')
return s
def environment_type(s):
if s not in _VALID_ENVIRONMENTS:
raise argparse.ArgumentTypeError(
f'Invalid Environment specified: "{s}".')
return s
def format_type(s):
if s not in _VALID_FORMATS:
raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".')
return s
def platform_type(s):
if s not in _VALID_PLATFORMS:
raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".')
return s
def valid_date(s):
try:
return datetime.strptime(s, _DATE_FORMAT).date()
except ValueError:
raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".')
parser = argparse.ArgumentParser(
description=('Creates a bidder-level filter set with the specified '
'options.'))
# Required fields.
parser.add_argument(
'-b', '--bidder_resource_id', default=DEFAULT_BIDDER_RESOURCE_ID,
help=('The resource ID of the bidders resource for which the filter set '
'is being created. This will be used to construct the ownerName '
'used as a path parameter for filter set requests. For additional '
'information on how to configure the ownerName path parameter, '
'see: https://developers.google.com/authorized-buyers/apis/'
'reference/rest/v2beta1/bidders.filterSets/create'
'#body.PATH_PARAMETERS.owner_name'))
parser.add_argument(
'-r', '--resource_id', default=DEFAULT_FILTER_SET_RESOURCE_ID,
help=('The resource ID of the filter set. Note that this must be '
'unique. This will be used to construct the filter set\'s name. '
'For additional information on how to configure a filter set\'s '
'name, see: https://developers.google.com/authorized-buyers/apis/'
'reference/rest/v2beta1/bidders.filterSets#FilterSet.FIELDS.name'))
parser.add_argument(
'--end_date', default=DEFAULT_END_DATE, type=valid_date,
help=('The end date for the filter set\'s absoluteDateRange field, which '
'will be accepted in this example in YYYYMMDD format.'))
parser.add_argument(
'--start_date', default=DEFAULT_START_DATE, type=valid_date,
help=('The start date for the filter set\'s time_range field, which '
'will be accepted in this example in YYYYMMDD format.'))
# Optional fields.
parser.add_argument(
'-e', '--environment', required=False,
type=environment_type,
help=('The environment on which to filter.'))
parser.add_argument(
'-f', '--format', required=False,
type=format_type,
help=('The format on which to filter.'))
parser.add_argument(
'-p', '--platforms', required=False, nargs='*', type=platform_type,
help=('The platforms on which to filter. The filters represented by '
'multiple platforms are ORed together. Note that you may specify '
'more than one using a space as a delimiter.'))
parser.add_argument(
'-s', '--seller_network_ids', required=False, nargs='*', type=int,
help=('The list of IDs for seller networks on which to filter. The '
'filters represented by multiple seller network IDs are ORed '
'together. Note that you may specify more than one using a space '
'as a delimiter.'))
parser.add_argument(
'-t', '--time_series_granularity', required=False,
type=time_series_granularity_type,
help=('The granularity of time intervals if a time series breakdown is '
'desired.'))
parser.add_argument(
'--is_transient', required=False, default=True, type=bool,
help=('Whether the filter set is transient, or should be persisted '
'indefinitely. In this example, this will default to True.'))
args = parser.parse_args()
# Build the time_range as an AbsoluteDateRange.
time_range = {
'startDate': {
'year': args.start_date.year,
'month': args.start_date.month,
'day': args.start_date.day
},
'endDate': {
'year': args.end_date.year,
'month': args.end_date.month,
'day': args.end_date.day
}
}
# Create a body containing the required fields.
BODY = {
'name': _FILTER_SET_NAME_TEMPLATE.format(
bidders_resource_id=args.bidder_resource_id,
filtersets_resource_id=args.resource_id),
# Note: You may alternatively specify relativeDateRange or
# realtimeTimeRange.
'absoluteDateRange': time_range
}
# Add optional fields to body if specified.
if args.environment:
BODY['environment'] = args.environment
if args.format:
BODY['format'] = args.format
if args.platforms:
BODY['platforms'] = args.platforms
if args.seller_network_ids:
BODY['sellerNetworkIds'] = args.seller_network_ids
if args.time_series_granularity:
BODY['timeSeriesGranularity'] = args.time_series_granularity
try:
service = samples_util.GetService('v2beta1')
except IOError as ex:
print(f'Unable to create adexchangebuyer service - {ex}')
print('Did you specify the key file in samples_util.py?')
sys.exit(1)
main(service, _OWNER_NAME_TEMPLATE.format(
bidders_resource_id=args.bidder_resource_id),
BODY, args.is_transient)
| googleads/googleads-adxbuyer-examples | python/samples/v2_x/create_bidder_level_filter_set.py | Python | apache-2.0 | 7,717 |
/*******************************************************************************
* Copyright 2006 - 2012 Vienna University of Technology,
* Department of Software Technology and Interactive Systems, IFS
*
* 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 work originates from the Planets project, co-funded by the European Union under the Sixth Framework Programme.
******************************************************************************/
package eu.scape_project.planning.model.transform;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.ManyToOne;
import eu.scape_project.planning.model.ChangeLog;
import eu.scape_project.planning.model.IChangesHandler;
import eu.scape_project.planning.model.ITouchable;
import eu.scape_project.planning.model.Values;
import eu.scape_project.planning.model.values.INumericValue;
import eu.scape_project.planning.model.values.IOrdinalValue;
import eu.scape_project.planning.model.values.TargetValues;
import eu.scape_project.planning.model.values.Value;
import eu.scape_project.planning.validation.ValidationError;
/**
* Implements basic transformation functionality, i.e. aggregation over {@link Values} and
* common properties of transformers.
* @author Hannes Kulovits
*/
@Entity
@Inheritance
@DiscriminatorColumn(name = "type")
public abstract class Transformer implements ITransformer, Serializable, ITouchable
{
private static final long serialVersionUID = -3708795251848706848L;
@Id
@GeneratedValue
protected int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(cascade=CascadeType.ALL)
private ChangeLog changeLog = new ChangeLog();
/**
* Transforms all the values in the list of the provided {@link Values}.
* According to the type of each {@link Value}, either
* {@link ITransformer#transform(INumericValue)} or {@link ITransformer#transform(IOrdinalValue)}
* is called.
* @param values List of values to be transformed
* @return {@link TargetValues}, which contains a list of all transformed values corresponding to the provided input
*/
public TargetValues transformValues(Values values) {
TargetValues result = new TargetValues();
for (Value v : values.getList()) {
if (v instanceof INumericValue) {
result.add(transform((INumericValue) v));
} else {
result.add(transform((IOrdinalValue) v));
}
}
return result;
}
public ChangeLog getChangeLog() {
return this.changeLog;
}
public void setChangeLog(ChangeLog value) {
changeLog = value;
}
public boolean isChanged() {
return changeLog.isAltered();
}
public void touch(String username) {
getChangeLog().touch(username);
}
public void touch() {
getChangeLog().touch();
}
/**
* @see ITouchable#handleChanges(IChangesHandler)
*/
public void handleChanges(IChangesHandler h){
h.visit(this);
}
/**
* If this Transformer is not correctly configured, this method adds
* an appropriate error-message to the given list and returns false.
*
* @return true if this transformer is correctly configured
*/
public abstract boolean isTransformable(List<ValidationError> errors);
public abstract Transformer clone();
}
| openpreserve/plato | plato-model/src/main/java/eu/scape_project/planning/model/transform/Transformer.java | Java | apache-2.0 | 4,334 |
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.hooks.rtc.network;
import java.net.URI;
import org.apache.http.client.methods.HttpPost;
public class HttpPatch extends HttpPost {
public HttpPatch() {
super();
}
public HttpPatch(String uri) {
super(uri);
}
public HttpPatch(URI uri) {
super(uri);
}
@Override
public String getMethod() {
return "PATCH";
}
}
| GerritCodeReview/plugins_hooks-rtc | src/main/java/com/googlesource/gerrit/plugins/hooks/rtc/network/HttpPatch.java | Java | apache-2.0 | 999 |
/*
* *************************************************************************
* Copyright (C) FRS Belgium NV ("FRSGlobal"). All rights reserved.
*
* This computer program is protected by copyright law and international
* treaties. Unauthorized reproduction or distribution of this program,
* or any portion of it, may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law.
* *************************************************************************
*/
package org.cluj.bus.servlet;
import com.google.gson.Gson;
import org.cluj.bus.model.BusSchedule;
import org.cluj.bus.model.BusScheduleDTO;
import org.cluj.bus.model.CategorySchedule;
import org.cluj.bus.services.JPARepository;
import org.cluj.bus.util.ScheduleUtilities;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BusScheduleServlet extends HttpServlet
{
private static final Logger LOGGER = Logger.getLogger(BusScheduleServlet.class.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
String busId = httpServletRequest.getParameter(ServletUtils.BUS_ID_PARAMETER_KEY);
ServletUtils.sendResponse(httpServletResponse, getResponseString(busId));
}
private String getResponseString(String busId)
{
List<BusSchedule> busSchedules = new JPARepository<>(BusSchedule.class).findAll("busId", busId);
Map<String, CategorySchedule> categorySchedules = new HashMap<>();
for (BusSchedule busSchedule : busSchedules)
{
String days = busSchedule.getDays();
CategorySchedule categorySchedule = categorySchedules.get(days);
if (categorySchedule == null)
{
categorySchedule = new CategorySchedule();
categorySchedules.put(days, categorySchedule);
categorySchedule.setDisplayName(busSchedule.getCategory());
categorySchedule.setApplicableDays(getApplicableDays(days));
}
Collection<Date> startTimes = categorySchedule.getStartTimes();
if (startTimes == null)
{
startTimes = new ArrayList<>();
categorySchedule.setStartTimes(startTimes);
}
try
{
startTimes.add(ScheduleUtilities.getStartTime(busSchedule.getStartTime()));
}
catch (ParseException e)
{
LOGGER.log(Level.SEVERE, "Error parsing start time", e);
}
}
BusScheduleDTO schedule = new BusScheduleDTO();
schedule.setSchedules(categorySchedules.values());
return new Gson().toJson(schedule);
}
private Collection<Integer> getApplicableDays(String days)
{
List<Integer> applicableDays = new ArrayList<>();
for (char aChar : days.toCharArray())
{
int day = Integer.parseInt(String.valueOf(aChar));
applicableDays.add(day);
}
return applicableDays;
}
}
| abotos/ClujLiveTransit | Java/appengine-code/appengine-web-ui/src/java/org/cluj/bus/servlet/BusScheduleServlet.java | Java | apache-2.0 | 3,589 |
/*
* 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.catalina.valves.rewrite;
import java.nio.charset.Charset;
/**
* Resolver abstract class.
*/
public abstract class Resolver {
public abstract String resolve(String key);
public String resolveEnv(String key) {
return System.getProperty(key);
}
public abstract String resolveSsl(String key);
public abstract String resolveHttp(String key);
public abstract boolean resolveResource(int type, String name);
/**
* @return The name of the encoding to use to %nn encode URIs
*
* @deprecated This will be removed in Tomcat 9.0.x
*/
@Deprecated
public abstract String getUriEncoding();
public abstract Charset getUriCharset();
}
| IAMTJW/Tomcat-8.5.20 | tomcat-8.5.20/java/org/apache/catalina/valves/rewrite/Resolver.java | Java | apache-2.0 | 1,568 |
/*
* 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.droids.impl;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import org.apache.droids.api.DelayTimer;
import org.apache.droids.api.Droid;
import org.apache.droids.api.Task;
import org.apache.droids.api.TaskExceptionHandler;
import org.apache.droids.api.TaskExceptionResult;
import org.apache.droids.api.TaskMaster;
import org.apache.droids.api.Worker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SequentialTaskMaster<T extends Task> implements TaskMaster<T>
{
private static final Logger LOG = LoggerFactory.getLogger(SequentialTaskMaster.class);
private final Object mutex;
private volatile boolean completed;
private volatile Date startedWorking = null;
private volatile Date finishedWorking = null;
private volatile int completedTask = 0;
private volatile T lastCompletedTask = null;
private volatile ExecutionState state = ExecutionState.INITIALIZED;
private DelayTimer delayTimer = null;
private TaskExceptionHandler exHandler = null;
public SequentialTaskMaster() {
super();
this.mutex = new Object();
}
/**
* The queue has been initialized
*/
@Override
public synchronized void start(final Queue<T> queue, final Droid<T> droid) {
this.completed = false;
this.startedWorking = new Date();
this.finishedWorking = null;
this.completedTask = 0;
this.state = ExecutionState.RUNNING;
boolean terminated = false;
while (!terminated) {
T task = queue.poll();
if (task == null) {
break;
}
if (delayTimer != null) {
long delay = delayTimer.getDelayMillis();
if (delay > 0) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
}
}
Worker<T> worker = droid.getNewWorker();
try {
if (!task.isAborted()) {
worker.execute(task);
}
completedTask++;
lastCompletedTask = task;
} catch (Exception ex) {
TaskExceptionResult result = TaskExceptionResult.WARN;
if (exHandler != null) {
result = exHandler.handleException(ex);
}
switch (result) {
case WARN:
LOG.warn(ex.toString() + " " + task.getId());
if (LOG.isDebugEnabled()) {
LOG.debug(ex.toString(), ex);
}
break;
case FATAL:
LOG.error(ex.getMessage(), ex);
terminated = true;
break;
}
}
}
finishedWorking = new Date();
this.state = ExecutionState.STOPPED;
droid.finished();
synchronized (mutex) {
completed = true;
mutex.notifyAll();
}
}
@Override
public final void setExceptionHandler(TaskExceptionHandler exHandler) {
this.exHandler = exHandler;
}
@Override
public final void setDelayTimer(DelayTimer delayTimer) {
this.delayTimer = delayTimer;
}
public boolean isWorking() {
return startedWorking != null && finishedWorking == null;
}
@Override
public Date getStartTime() {
return startedWorking;
}
@Override
public Date getFinishedWorking() {
return finishedWorking;
}
@Override
public long getCompletedTasks() {
return completedTask;
}
@Override
public T getLastCompletedTask() {
return lastCompletedTask;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
if (timeout < 0) {
timeout = 0;
}
synchronized (this.mutex) {
long deadline = System.currentTimeMillis() + unit.toMillis(timeout);
long remaining = timeout;
while (!completed) {
this.mutex.wait(remaining);
if (timeout >= 0) {
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
return false; // Reach if timeout is over and no finish.
}
}
}
}
return true;
}
@Override
public ExecutionState getExecutionState() {
return state;
}
}
| fogbeam/Heceta_droids | droids-core/src/main/java/org/apache/droids/impl/SequentialTaskMaster.java | Java | apache-2.0 | 4,864 |
// 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.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
[ExportCompletionProvider(nameof(KeywordCompletionProvider), LanguageNames.CSharp)]
[ExtensionOrder(After = nameof(NamedParameterCompletionProvider))]
[Shared]
internal class KeywordCompletionProvider : AbstractKeywordCompletionProvider<CSharpSyntaxContext>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public KeywordCompletionProvider()
: base(GetKeywordRecommenders())
{
}
private static ImmutableArray<IKeywordRecommender<CSharpSyntaxContext>> GetKeywordRecommenders()
{
return new IKeywordRecommender<CSharpSyntaxContext>[]
{
new AbstractKeywordRecommender(),
new AddKeywordRecommender(),
new AliasKeywordRecommender(),
new AnnotationsKeywordRecommender(),
new AscendingKeywordRecommender(),
new AsKeywordRecommender(),
new AssemblyKeywordRecommender(),
new AsyncKeywordRecommender(),
new AwaitKeywordRecommender(),
new BaseKeywordRecommender(),
new BoolKeywordRecommender(),
new BreakKeywordRecommender(),
new ByKeywordRecommender(),
new ByteKeywordRecommender(),
new CaseKeywordRecommender(),
new CatchKeywordRecommender(),
new CharKeywordRecommender(),
new CheckedKeywordRecommender(),
new ChecksumKeywordRecommender(),
new ClassKeywordRecommender(),
new ConstKeywordRecommender(),
new ContinueKeywordRecommender(),
new DecimalKeywordRecommender(),
new DefaultKeywordRecommender(),
new DefineKeywordRecommender(),
new DelegateKeywordRecommender(),
new DescendingKeywordRecommender(),
new DisableKeywordRecommender(),
new DoKeywordRecommender(),
new DoubleKeywordRecommender(),
new DynamicKeywordRecommender(),
new ElifKeywordRecommender(),
new ElseKeywordRecommender(),
new EnableKeywordRecommender(),
new EndIfKeywordRecommender(),
new EndRegionKeywordRecommender(),
new EnumKeywordRecommender(),
new EqualsKeywordRecommender(),
new ErrorKeywordRecommender(),
new EventKeywordRecommender(),
new ExplicitKeywordRecommender(),
new ExternKeywordRecommender(),
new FalseKeywordRecommender(),
new FieldKeywordRecommender(),
new FinallyKeywordRecommender(),
new FixedKeywordRecommender(),
new FloatKeywordRecommender(),
new ForEachKeywordRecommender(),
new ForKeywordRecommender(),
new FromKeywordRecommender(),
new GetKeywordRecommender(),
new GlobalKeywordRecommender(),
new GotoKeywordRecommender(),
new GroupKeywordRecommender(),
new HiddenKeywordRecommender(),
new IfKeywordRecommender(),
new ImplicitKeywordRecommender(),
new InKeywordRecommender(),
new InterfaceKeywordRecommender(),
new InternalKeywordRecommender(),
new IntKeywordRecommender(),
new IntoKeywordRecommender(),
new IsKeywordRecommender(),
new JoinKeywordRecommender(),
new LetKeywordRecommender(),
new LineKeywordRecommender(),
new LoadKeywordRecommender(),
new LockKeywordRecommender(),
new LongKeywordRecommender(),
new MethodKeywordRecommender(),
new ModuleKeywordRecommender(),
new NameOfKeywordRecommender(),
new NamespaceKeywordRecommender(),
new NewKeywordRecommender(),
new NintKeywordRecommender(),
new NotNullKeywordRecommender(),
new NuintKeywordRecommender(),
new NullableKeywordRecommender(),
new NullKeywordRecommender(),
new ObjectKeywordRecommender(),
new OnKeywordRecommender(),
new OperatorKeywordRecommender(),
new OrderByKeywordRecommender(),
new OutKeywordRecommender(),
new OverrideKeywordRecommender(),
new ParamKeywordRecommender(),
new ParamsKeywordRecommender(),
new PartialKeywordRecommender(),
new PragmaKeywordRecommender(),
new PrivateKeywordRecommender(),
new PropertyKeywordRecommender(),
new ProtectedKeywordRecommender(),
new PublicKeywordRecommender(),
new ReadOnlyKeywordRecommender(),
new ReferenceKeywordRecommender(),
new RefKeywordRecommender(),
new RegionKeywordRecommender(),
new RemoveKeywordRecommender(),
new RestoreKeywordRecommender(),
new ReturnKeywordRecommender(),
new SByteKeywordRecommender(),
new SealedKeywordRecommender(),
new SelectKeywordRecommender(),
new SetKeywordRecommender(),
new ShortKeywordRecommender(),
new SizeOfKeywordRecommender(),
new StackAllocKeywordRecommender(),
new StaticKeywordRecommender(),
new StringKeywordRecommender(),
new StructKeywordRecommender(),
new SwitchKeywordRecommender(),
new ThisKeywordRecommender(),
new ThrowKeywordRecommender(),
new TrueKeywordRecommender(),
new TryKeywordRecommender(),
new TypeKeywordRecommender(),
new TypeOfKeywordRecommender(),
new TypeVarKeywordRecommender(),
new UIntKeywordRecommender(),
new ULongKeywordRecommender(),
new UncheckedKeywordRecommender(),
new UndefKeywordRecommender(),
new UnmanagedKeywordRecommender(),
new UnsafeKeywordRecommender(),
new UShortKeywordRecommender(),
new UsingKeywordRecommender(),
new VarKeywordRecommender(),
new VirtualKeywordRecommender(),
new VoidKeywordRecommender(),
new VolatileKeywordRecommender(),
new WarningKeywordRecommender(),
new WarningsKeywordRecommender(),
new WhenKeywordRecommender(),
new WhereKeywordRecommender(),
new WhileKeywordRecommender(),
new YieldKeywordRecommender(),
}.ToImmutableArray();
}
internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
=> CompletionUtilities.IsTriggerCharacter(text, characterPosition, options);
internal override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters;
protected override async Task<CSharpSyntaxContext> CreateContextAsync(Document document, int position, CancellationToken cancellationToken)
{
var span = new TextSpan(position, length: 0);
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
return CSharpSyntaxContext.CreateContext(document.Project.Solution.Workspace, semanticModel, position, cancellationToken);
}
private static readonly CompletionItemRules s_tupleRules = CompletionItemRules.Default.
WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ':'));
protected override CompletionItem CreateItem(RecommendedKeyword keyword, CSharpSyntaxContext context)
{
var rules = context.IsPossibleTupleContext ? s_tupleRules : CompletionItemRules.Default;
return CommonCompletionItem.Create(
displayText: keyword.Keyword,
displayTextSuffix: "",
description: keyword.DescriptionFactory(CancellationToken.None),
glyph: Glyph.Keyword,
rules: rules.WithMatchPriority(keyword.MatchPriority)
.WithFormatOnCommit(keyword.ShouldFormatOnCommit));
}
internal override TextSpan GetCurrentSpan(TextSpan span, SourceText text)
=> CompletionUtilities.GetCompletionItemSpan(text, span.End);
}
}
| reaction1989/roslyn | src/Features/CSharp/Portable/Completion/CompletionProviders/KeywordCompletionProvider.cs | C# | apache-2.0 | 9,814 |
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Python header conversion
# Copyright (c) 2013,2014 Dave Hughes <dave@waveform.org.uk>
#
# Original headers
# Copyright (c) 2012, Broadcom Europe Ltd
# 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 holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import (
unicode_literals,
print_function,
division,
absolute_import,
)
# Make Py2's str equivalent to Py3's
str = type('')
import ctypes as ct
import warnings
_lib = ct.CDLL('libbcm_host.so')
# bcm_host.h #################################################################
bcm_host_init = _lib.bcm_host_init
bcm_host_init.argtypes = []
bcm_host_init.restype = None
bcm_host_deinit = _lib.bcm_host_deinit
bcm_host_deinit.argtypes = []
bcm_host_deinit.restype = None
graphics_get_display_size = _lib.graphics_get_display_size
graphics_get_display_size.argtypes = [ct.c_uint16, ct.POINTER(ct.c_uint32), ct.POINTER(ct.c_uint32)]
graphics_get_display_size.restype = ct.c_int32
| naziris/HomeSecPi | picamera/bcm_host.py | Python | apache-2.0 | 2,448 |
# quick demo of some python image filters
# using raspberry pi camera
import Tkinter as tk
from picamera import PiCamera
from time import sleep
from PIL import Image,ImageFilter,ImageChops,ImageTk
imagefile = "image.jpg"
w = 320
h = 240
lastfilter = "none"
camera = PiCamera()
def takephoto():
camera.capture(imagefile)
image1 = Image.open(imagefile)
return image1
def photoloop():
count = 0
while (count < 9):
sleep(0.5)
image1 = newphoto()
if lastfilter is not "none":
dofilter(lastfilter,image1)
count = count + 1
def newphoto():
global image1
image1 = takephoto()
tkimage1 = ImageTk.PhotoImage(image1)
panel1.configure(image=tkimage1)
panel1.image = tkimage1
def invert():
global image1
image1= ImageChops.invert(image1)
tkimage1 = ImageTk.PhotoImage(image1)
panel1.configure(image=tkimage1)
panel1.image = tkimage1
def grayscale():
global image1
r, g, b = image1.split()
image1 = Image.merge("RGB", (g,g,g))
tkimage1 = ImageTk.PhotoImage(image1)
panel1.configure(image=tkimage1)
panel1.image = tkimage1
def dofilter (theimage,thefilter):
lastfilter = thefilter
global image1
image1 = image1.filter(thefilter)
tkimage1 = ImageTk.PhotoImage(image1)
panel1.configure(image=tkimage1)
panel1.image = tkimage1
# Setup a window
root = tk.Tk()
root.title('Image')
image1 = takephoto()
tkimage1 = ImageTk.PhotoImage(image1)
w = tkimage1.width()
h = tkimage1.height()
root.geometry("%dx%d+%d+%d" % (w, h, 0, 0))
# root has no image argument, so use a label as a panel
panel1 = tk.Label(root, image=tkimage1)
panel1.pack(side='top', fill='both', expand='yes')
# save the panel's image from 'garbage collection'
panel1.image = tkimage1
# Add some buttons
buttonrow = tk.Frame(root)
buttonrow.place(y=0,x=0)
button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto())
button.pack(side='left',)
button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop())
button.pack(side='left',)
button = tk.Button(buttonrow, text='INVERT',command = lambda: invert())
button.pack(side='left',)
button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale())
button.pack(side='left',)
# add some filter buttons
button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR))
button.pack(side='left')
button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR))
button.pack(side='left')
button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES))
button.pack(side='left')
button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS))
button.pack(side='left')
button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE))
button.pack(side='left')
button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy())
button.pack(side='left')
root.mainloop() | emschimmel/CameraPi | camera_try.py | Python | apache-2.0 | 2,985 |
/**
* Copyright (c) 2008-2010 Andrey Somov
*
* 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.yaml.snakeyaml.tokens;
import java.util.List;
import org.yaml.snakeyaml.error.Mark;
import org.yaml.snakeyaml.error.YAMLException;
/**
* @see <a href="http://pyyaml.org/wiki/PyYAML">PyYAML</a> for more information
*/
public final class DirectiveToken<T> extends Token {
private final String name;
private final List<T> value;
public DirectiveToken(String name, List<T> value, Mark startMark, Mark endMark) {
super(startMark, endMark);
this.name = name;
if (value != null && value.size() != 2) {
throw new YAMLException("Two strings must be provided instead of "
+ String.valueOf(value.size()));
}
this.value = value;
}
public String getName() {
return this.name;
}
public List<T> getValue() {
return this.value;
}
@Override
protected String getArguments() {
if (value != null) {
return "name=" + name + ", value=[" + value.get(0) + ", " + value.get(1) + "]";
} else {
return "name=" + name;
}
}
@Override
public Token.ID getTokenId() {
return ID.Directive;
}
}
| spariev/snakeyaml | src/main/java/org/yaml/snakeyaml/tokens/DirectiveToken.java | Java | apache-2.0 | 1,789 |
var a02307 =
[
[ "GenericVector", "a02307.html#a60d42eebf02708482a8b506edd417990", null ],
[ "GenericVector", "a02307.html#a28a69767bcadb6058a2a9df4afecd5fc", null ],
[ "GenericVector", "a02307.html#a2b61cd1cd756770518f5ac30f817a9bf", null ],
[ "~GenericVector", "a02307.html#a49840c8743a063b87839baef7e19b968", null ],
[ "back", "a02307.html#a48b82547ebbaa5fedecfdebe7e2f155a", null ],
[ "binary_search", "a02307.html#ad561e19e75a0fb30f0118774d7fa5621", null ],
[ "bool_binary_search", "a02307.html#a8c261f66a24da67aac1acca7aa8f650a", null ],
[ "choose_nth_item", "a02307.html#a5c4218ef833d0fe5db9b9749abd81ea5", null ],
[ "choose_nth_item", "a02307.html#ae1e555b0cdded2c36dd6cf15345f659f", null ],
[ "clear", "a02307.html#a9cdbff49b186574b83e43afba606fdd9", null ],
[ "compact", "a02307.html#a080f7786e007523bcaa3f69913a82882", null ],
[ "compact_sorted", "a02307.html#a8cb22ff55d6dd125d93cd03fd73bf8ad", null ],
[ "contains", "a02307.html#a997e0fcaaa6b6533401dc54c0691e2e5", null ],
[ "contains_index", "a02307.html#ac1aae0b1c22248f264dad02481123398", null ],
[ "delete_data_pointers", "a02307.html#a98f62dccd75224a60437c2761bd215cd", null ],
[ "DeSerialize", "a02307.html#aa4f5b1bc0d044fbd1fc77363b798c39c", null ],
[ "DeSerialize", "a02307.html#a2e4fca9599eff590b76affc0a0aa0a2b", null ],
[ "DeSerializeClasses", "a02307.html#a698ebd328d22f1edc114053ca2eba48e", null ],
[ "DeSerializeClasses", "a02307.html#ade729c7d5429fbd5be304e3493a8a95f", null ],
[ "dot_product", "a02307.html#a6f6dfbc607499173e7809656c6c505bc", null ],
[ "double_the_size", "a02307.html#af0214c8c21da9eb57dfebc78611d0cd6", null ],
[ "empty", "a02307.html#a172c4aa23ba397e24319ae095281cbcc", null ],
[ "get", "a02307.html#abd0a875f98a1d78613ed3521d96e5300", null ],
[ "get_index", "a02307.html#a6dee574daf4a3d4f0fc7048964f8f252", null ],
[ "init", "a02307.html#a5b010723588fe15f303e4f3474d8479e", null ],
[ "init_to_size", "a02307.html#a6751521fd3eb461d81fc83ef93a0def3", null ],
[ "insert", "a02307.html#a57ca5259541548a97bcfd4d0925a27ff", null ],
[ "length", "a02307.html#a6af4e0a2a30dda267d19bf783ae22eb7", null ],
[ "move", "a02307.html#abae057ce589be25aae9b80958f84e34c", null ],
[ "operator+=", "a02307.html#af73fadcdb08f0a12a5615f2bcf6fa6a8", null ],
[ "operator+=", "a02307.html#acc7df2256174b32632e4d5b6c8d05d29", null ],
[ "operator=", "a02307.html#af6fd5b3891b276c10add96f9411bec05", null ],
[ "operator[]", "a02307.html#afd51f3f981284adb20bdf3b0bfd1c1f7", null ],
[ "pop_back", "a02307.html#a0621dd57ce58dae3cb5f3d61e76bd233", null ],
[ "push_back", "a02307.html#a0dc89fe2a365b04a61017f9d78c1a303", null ],
[ "push_back_new", "a02307.html#a393f9f8dcc55ad759a5c7fbdc4840a89", null ],
[ "push_front", "a02307.html#ae08e7cece0097ad356b5e565cbb2cf0b", null ],
[ "read", "a02307.html#a10a273cab07e56c1654b2167f8aa9408", null ],
[ "remove", "a02307.html#a3fd37a240a42f1c3052e8d28614d3702", null ],
[ "reserve", "a02307.html#aa225ea3fc9374961482bc804028317eb", null ],
[ "resize_no_init", "a02307.html#a09005e8f2b51d033d60eb5690aa5d112", null ],
[ "reverse", "a02307.html#a58f6d73009cc3c56d0efb0d96ad35b5b", null ],
[ "Serialize", "a02307.html#a206a6fe71c3780d862d97ef7c5fc9546", null ],
[ "Serialize", "a02307.html#a3e994fd938468ff4fc4b4a902e970876", null ],
[ "SerializeClasses", "a02307.html#ad0e8164e4c5c82e9e367c8a6d9b755b1", null ],
[ "SerializeClasses", "a02307.html#a7d0060c687429049a0ea5cf21d067b8e", null ],
[ "set", "a02307.html#a067b7833ee66238b7b5e230404525fcb", null ],
[ "set_clear_callback", "a02307.html#af2bbca5b3258035a333b62679835a253", null ],
[ "set_compare_callback", "a02307.html#aa3ec670c7f68a95f84641a0ded8cb61f", null ],
[ "size", "a02307.html#a20cfad5c58c50cb85a9529d8ddbd96af", null ],
[ "size_reserved", "a02307.html#a1c273622446ec7b5a6669fa9c9fdd8e5", null ],
[ "sort", "a02307.html#a999bbd8ff336c81fe1198ea714c7936d", null ],
[ "sort", "a02307.html#a461142d4ff7c61f22119552b7c0b2755", null ],
[ "swap", "a02307.html#ac10b1de04fdfd4f5e4b90ac6d03f35b9", null ],
[ "truncate", "a02307.html#a980882b5ebc3e72fdedbdbe345196f21", null ],
[ "unsigned_size", "a02307.html#a47bd2385b28d536e8b6e87b689d61ede", null ],
[ "WithinBounds", "a02307.html#a367914d03777eef59176d48155d06b72", null ],
[ "write", "a02307.html#a8745d1d8394e852d12398d0458684dee", null ],
[ "clear_cb_", "a02307.html#a57a833bdcc07a53e9a7b57d07cac2131", null ],
[ "compare_cb_", "a02307.html#acd69761952fb39cbe7d7b43a6b06a432", null ],
[ "data_", "a02307.html#ab88657a46d06c175dcfc76c0fcdaac7d", null ],
[ "size_reserved_", "a02307.html#a4a02eb2a4ed31e8454cd8ae06eb8d7c5", null ],
[ "size_used_", "a02307.html#a99185b084a6ace7536818ce2f17b11fb", null ]
]; | stweil/tesseract-ocr.github.io | 4.0.0/a02307.js | JavaScript | apache-2.0 | 4,880 |
package mx.emite.sdk.scot.request;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import lombok.Builder;
import lombok.Data;
import lombok.Singular;
import mx.emite.sdk.cfdi32.anotaciones.Rfc;
import mx.emite.sdk.scot.request.extra.SucursalInfo;
@Data
@Builder
public class SucursalesAltaRequest {
/**
* Token del <b>Integrador</b> obtenido con el servicio de Token
* -- SETTER --
*
* @param token
* Token del <b>Integrador</b> obtenido de Scot©
*
*/
@NotNull
private String token;
/**
* @param rfc del emisor, si se deja en blanco se consultan todos los emisores
*/
@Rfc
private String rfc;
/**
* @param sucursales lista de sucursales a dar de alta
*/
@Valid @NotEmpty @Singular("sucursal")
private List<SucursalInfo> sucursales;
/**
* modificar si la sucursal ya se encuentra dado de alta
*/
@NotNull
public Boolean modificar;
}
| emite-mx/ef-sdk-java | ef-sdk-java/src/main/java/mx/emite/sdk/scot/request/SucursalesAltaRequest.java | Java | apache-2.0 | 1,030 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MassTransit.Publisher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MassTransit.Publisher")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("918f334e-cfe9-4000-bd5d-8154d3f88163")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | shibukraj/Masstransit.PubSubSample | MassTransit.Publisher/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,382 |
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package attributes
import (
"bytes"
"crypto/x509"
"encoding/asn1"
"errors"
"fmt"
"strconv"
"strings"
pb "github.com/fabric_sdk_golang/core/crypto/attributes/proto"
"github.com/fabric_sdk_golang/core/crypto/primitives"
"github.com/golang/protobuf/proto"
)
var (
// TCertEncAttributesBase is the base ASN1 object identifier for attributes.
// When generating an extension to include the attribute an index will be
// appended to this Object Identifier.
TCertEncAttributesBase = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6}
// TCertAttributesHeaders is the ASN1 object identifier of attributes header.
TCertAttributesHeaders = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 9}
padding = []byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}
//headerPrefix is the prefix used in the header exteion of the certificate.
headerPrefix = "00HEAD"
//HeaderAttributeName is the name used to derivate the K used to encrypt/decrypt the header.
HeaderAttributeName = "attributeHeader"
)
//ParseAttributesHeader parses a string and returns a map with the attributes.
func ParseAttributesHeader(header string) (map[string]int, error) {
if !strings.HasPrefix(header, headerPrefix) {
return nil, errors.New("Invalid header")
}
headerBody := strings.Replace(header, headerPrefix, "", 1)
tokens := strings.Split(headerBody, "#")
result := make(map[string]int)
for _, token := range tokens {
pair := strings.Split(token, "->")
if len(pair) == 2 {
key := pair[0]
valueStr := pair[1]
value, err := strconv.Atoi(valueStr)
if err != nil {
return nil, err
}
result[key] = value
}
}
return result, nil
}
//ReadAttributeHeader read the header of the attributes.
func ReadAttributeHeader(tcert *x509.Certificate, headerKey []byte) (map[string]int, bool, error) {
var err error
var headerRaw []byte
encrypted := false
if headerRaw, err = primitives.GetCriticalExtension(tcert, TCertAttributesHeaders); err != nil {
return nil, encrypted, err
}
headerStr := string(headerRaw)
var header map[string]int
header, err = ParseAttributesHeader(headerStr)
if err != nil {
if headerKey == nil {
return nil, false, errors.New("Is not possible read an attribute encrypted without the headerKey")
}
headerRaw, err = DecryptAttributeValue(headerKey, headerRaw)
if err != nil {
return nil, encrypted, errors.New("error decrypting header value '" + err.Error() + "''")
}
headerStr = string(headerRaw)
header, err = ParseAttributesHeader(headerStr)
if err != nil {
return nil, encrypted, err
}
encrypted = true
}
return header, encrypted, nil
}
//ReadTCertAttributeByPosition read the attribute stored in the position "position" of the tcert.
func ReadTCertAttributeByPosition(tcert *x509.Certificate, position int) ([]byte, error) {
if position <= 0 {
return nil, fmt.Errorf("Invalid attribute position. Received [%v]", position)
}
oid := asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 9 + position}
value, err := primitives.GetCriticalExtension(tcert, oid)
if err != nil {
return nil, err
}
return value, nil
}
//ReadTCertAttribute read the attribute with name "attributeName" and returns the value and a boolean indicating if the returned value is encrypted or not.
func ReadTCertAttribute(tcert *x509.Certificate, attributeName string, headerKey []byte) ([]byte, bool, error) {
header, encrypted, err := ReadAttributeHeader(tcert, headerKey)
if err != nil {
return nil, false, err
}
position := header[attributeName]
if position == 0 {
return nil, encrypted, errors.New("Failed attribute '" + attributeName + "' doesn't exists in the TCert.")
}
value, err := ReadTCertAttributeByPosition(tcert, position)
if err != nil {
return nil, encrypted, err
}
return value, encrypted, nil
}
//EncryptAttributeValue encrypts "attributeValue" using "attributeKey"
func EncryptAttributeValue(attributeKey []byte, attributeValue []byte) ([]byte, error) {
value := append(attributeValue, padding...)
return primitives.CBCPKCS7Encrypt(attributeKey, value)
}
//getAttributeKey returns the attributeKey derived from the preK0 to the attributeName.
func getAttributeKey(preK0 []byte, attributeName string) []byte {
return primitives.HMACTruncated(preK0, []byte(attributeName), 32)
}
//EncryptAttributeValuePK0 encrypts "attributeValue" using a key derived from preK0.
func EncryptAttributeValuePK0(preK0 []byte, attributeName string, attributeValue []byte) ([]byte, error) {
attributeKey := getAttributeKey(preK0, attributeName)
return EncryptAttributeValue(attributeKey, attributeValue)
}
//DecryptAttributeValue decrypts "encryptedValue" using "attributeKey" and return the decrypted value.
func DecryptAttributeValue(attributeKey []byte, encryptedValue []byte) ([]byte, error) {
value, err := primitives.CBCPKCS7Decrypt(attributeKey, encryptedValue)
if err != nil {
return nil, err
}
lenPadding := len(padding)
lenValue := len(value)
if lenValue < lenPadding {
return nil, errors.New("Error invalid value. Decryption verification failed.")
}
lenWithoutPadding := lenValue - lenPadding
if bytes.Compare(padding[0:lenPadding], value[lenWithoutPadding:lenValue]) != 0 {
return nil, errors.New("Error generating decryption key for value. Decryption verification failed.")
}
value = value[0:lenWithoutPadding]
return value, nil
}
//getKAndValueForAttribute derives K for the attribute "attributeName", checks the value padding and returns both key and decrypted value
func getKAndValueForAttribute(attributeName string, preK0 []byte, cert *x509.Certificate) ([]byte, []byte, error) {
headerKey := getAttributeKey(preK0, HeaderAttributeName)
value, encrypted, err := ReadTCertAttribute(cert, attributeName, headerKey)
if err != nil {
return nil, nil, err
}
attributeKey := getAttributeKey(preK0, attributeName)
if encrypted {
value, err = DecryptAttributeValue(attributeKey, value)
if err != nil {
return nil, nil, err
}
}
return attributeKey, value, nil
}
//GetKForAttribute derives the K for the attribute "attributeName" and returns the key
func GetKForAttribute(attributeName string, preK0 []byte, cert *x509.Certificate) ([]byte, error) {
key, _, err := getKAndValueForAttribute(attributeName, preK0, cert)
return key, err
}
//GetValueForAttribute derives the K for the attribute "attributeName" and returns the value
func GetValueForAttribute(attributeName string, preK0 []byte, cert *x509.Certificate) ([]byte, error) {
_, value, err := getKAndValueForAttribute(attributeName, preK0, cert)
return value, err
}
func createAttributesHeaderEntry(preK0 []byte) *pb.AttributesMetadataEntry {
attKey := getAttributeKey(preK0, HeaderAttributeName)
return &pb.AttributesMetadataEntry{AttributeName: HeaderAttributeName, AttributeKey: attKey}
}
func createAttributesMetadataEntry(attributeName string, preK0 []byte) *pb.AttributesMetadataEntry {
attKey := getAttributeKey(preK0, attributeName)
return &pb.AttributesMetadataEntry{AttributeName: attributeName, AttributeKey: attKey}
}
//CreateAttributesMetadataObjectFromCert creates an AttributesMetadata object from certificate "cert", metadata and the attributes keys.
func CreateAttributesMetadataObjectFromCert(cert *x509.Certificate, metadata []byte, preK0 []byte, attributeKeys []string) *pb.AttributesMetadata {
var entries []*pb.AttributesMetadataEntry
for _, key := range attributeKeys {
if len(key) == 0 {
continue
}
entry := createAttributesMetadataEntry(key, preK0)
entries = append(entries, entry)
}
headerEntry := createAttributesHeaderEntry(preK0)
entries = append(entries, headerEntry)
return &pb.AttributesMetadata{Metadata: metadata, Entries: entries}
}
//CreateAttributesMetadataFromCert creates the AttributesMetadata from the original metadata and certificate "cert".
func CreateAttributesMetadataFromCert(cert *x509.Certificate, metadata []byte, preK0 []byte, attributeKeys []string) ([]byte, error) {
attributesMetadata := CreateAttributesMetadataObjectFromCert(cert, metadata, preK0, attributeKeys)
return proto.Marshal(attributesMetadata)
}
//CreateAttributesMetadata create the AttributesMetadata from the original metadata
func CreateAttributesMetadata(raw []byte, metadata []byte, preK0 []byte, attributeKeys []string) ([]byte, error) {
cert, err := primitives.DERToX509Certificate(raw)
if err != nil {
return nil, err
}
return CreateAttributesMetadataFromCert(cert, metadata, preK0, attributeKeys)
}
//GetAttributesMetadata object from the original metadata "metadata".
func GetAttributesMetadata(metadata []byte) (*pb.AttributesMetadata, error) {
attributesMetadata := &pb.AttributesMetadata{}
err := proto.Unmarshal(metadata, attributesMetadata)
return attributesMetadata, err
}
//BuildAttributesHeader builds a header attribute from a map of attribute names and positions.
func BuildAttributesHeader(attributesHeader map[string]int) ([]byte, error) {
var header []byte
var headerString string
var positions = make(map[int]bool)
for k, v := range attributesHeader {
if positions[v] {
return nil, errors.New("Duplicated position found in attributes header")
}
positions[v] = true
vStr := strconv.Itoa(v)
headerString = headerString + k + "->" + vStr + "#"
}
header = []byte(headerPrefix + headerString)
return header, nil
}
| shangsony/fabric_sdk_golang | core/crypto/attributes/attributes.go | GO | apache-2.0 | 9,892 |
var crypto = require("crypto"),
Request = require("./../request"),
Response = require("./../response");
module.exports = sessionCookie;
/**
* A middleware for storing and retrieving session data using HTTP cookies.
* The `options` may be any of the following:
*
* - secret A secret string to use to verify the cookie's contents,
* defaults to `null`. If this is set the session's contents
* will be cleared if the cookie has been tampered with
* - name The name of the cookie, defaults to "strata.session"
* - path The path of the cookie, defaults to "/"
* - domain The cookie's domain, defaults to `null`
* - expireAfter A number of seconds after which this cookie will expire,
* defaults to `null`
* - secure True to only send this cookie over HTTPS, defaults to `false`
* - httpOnly True to only send this cookie over HTTP, defaults to `true`
*/
function sessionCookie(app, options) {
var readSession = sessionCookieReader(options);
var writeSession = sessionCookieWriter(options);
return function (env, callback) {
if (env.session) {
app(env, callback);
return;
}
readSession(env, function (err, session) {
if (err) {
env.session = {};
} else {
env.session = session;
}
app(env, function (status, headers, body) {
var res = new Response(body, headers, status);
writeSession(env, res);
res.send(callback);
});
});
}
}
function sessionCookieReader(options) {
options = sessionCookieOptions(options);
return function readSessionCookie(env, callback) {
var req = new Request(env);
req.cookies(function (err, cookies) {
if (err) {
callback(err, cookies);
return;
}
var cookie = cookies[options.name];
if (cookie) {
cookie = new Buffer(cookie, "base64").toString("utf8");
var parts = cookie.split("--"),
data = parts[0],
digest = parts[1];
if (digest === sessionDigest(data, options.secret)) {
try {
callback(null, JSON.parse(data));
return;
} catch (e) {
// The cookie does not contain valid JSON.
callback(e, {});
return;
}
}
}
callback(null, {});
});
}
}
function sessionCookieWriter(options) {
options = sessionCookieOptions(options);
return function writeSessionCookie(env, res) {
var session = env.session;
if (session) {
var data = JSON.stringify(session);
var digest = sessionDigest(data, options.secret);
var cookie = new Buffer(data + "--" + digest, "utf8").toString("base64");
if (cookie.length > 4096) {
env.error.write("Session cookie data size exceeds 4k; content dropped\n");
return;
}
var cookieOptions = {
value: cookie,
path: options.path,
domain: options.domain,
secure: options.secure,
httpOnly: options.httpOnly
};
if (options.expireAfter) {
// expireAfter is given in seconds.
var expires = new Date().getTime() + (options.expireAfter * 1000);
cookieOptions.expires = new Date(expires);
}
res.setCookie(options.name, cookieOptions);
}
}
}
function sessionDigest(data, secret) {
var shasum = crypto.createHash("sha1");
shasum.update(data);
if (secret) {
shasum.update(secret);
}
return shasum.digest("hex");
}
/**
* Creates a new options object from the given session cookie `options` with
* sane defaults.
*/
function sessionCookieOptions(options) {
options = options || {};
var opts = {
secret: options.secret || null,
name: options.name || "strata.session",
path: options.path || "/",
domain: options.domain || null,
expireAfter: options.expireAfter || null,
secure: options.secure || false
};
if ("httpOnly" in options) {
opts.httpOnly = options.httpOnly || false;
} else {
opts.httpOnly = true;
}
return opts;
}
| mbutler/nfn | node_modules/hem/node_modules/strata/lib/session/cookie.js | JavaScript | apache-2.0 | 4,665 |
package org.efix.util.buffer;
import org.efix.util.ByteSequenceWrapper;
import org.efix.util.StringUtil;
public class BufferUtil {
public static UnsafeBuffer fromString(String string) {
return new UnsafeBuffer(StringUtil.asciiBytes(string));
}
public static String toString(Buffer buffer) {
return toString(buffer, 0, buffer.capacity());
}
public static String toString(Buffer buffer, int offset, int length) {
return new ByteSequenceWrapper(buffer, offset, length).toString();
}
}
| artyomkorzun/efix | src/main/java/org/efix/util/buffer/BufferUtil.java | Java | apache-2.0 | 536 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.example.db.discovery.spring.namespace.jdbc.repository;
import org.apache.shardingsphere.example.db.discovery.spring.namespace.jdbc.entity.Address;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public final class AddressRepository {
private final DataSource dataSource;
public AddressRepository(final DataSource dataSource) {
this.dataSource = dataSource;
}
public void createTableIfNotExists() throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS t_address "
+ "(address_id BIGINT NOT NULL, address_name VARCHAR(100) NOT NULL, PRIMARY KEY (address_id))";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
}
}
public void dropTable() throws SQLException {
String sql = "DROP TABLE t_address";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
}
}
public void truncateTable() throws SQLException {
String sql = "TRUNCATE TABLE t_address";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
}
}
public Long insert(final Address entity) throws SQLException {
String sql = "INSERT INTO t_address (address_id, address_name) VALUES (?, ?)";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setLong(1, entity.getAddressId());
preparedStatement.setString(2, entity.getAddressName());
preparedStatement.executeUpdate();
}
return entity.getAddressId();
}
public void delete(final Long primaryKey) throws SQLException {
String sql = "DELETE FROM t_address WHERE address_id=?";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setLong(1, primaryKey);
preparedStatement.executeUpdate();
}
}
public List<Address> selectAll() throws SQLException {
String sql = "SELECT * FROM t_address";
return getAddress(sql);
}
private List<Address> getAddress(final String sql) throws SQLException {
List<Address> result = new LinkedList<>();
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
Address address = new Address();
address.setAddressId(resultSet.getLong(1));
address.setAddressName(resultSet.getString(2));
result.add(address);
}
}
return result;
}
}
| apache/incubator-shardingsphere | examples/shardingsphere-sample/shardingsphere-example-generated/shardingsphere-jdbc-sample/shardingsphere-jdbc-memory-local-db-discovery-spring-namespace-jdbc-example/src/main/java/org/apache/shardingsphere/example/db/discovery/spring/namespace/jdbc/repository/AddressRepository.java | Java | apache-2.0 | 4,185 |
package dao
import (
"go-common/app/admin/ep/merlin/model"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
var (
username = "fengyifenguitest@bilibili.com"
)
func Test_Mail_Log(t *testing.T) {
Convey("test add mail log", t, func() {
ml := &model.MailLog{
ReceiverName: username,
MailType: 1,
SendContext: "test add mail log",
}
err := d.InsertMailLog(ml)
So(err, ShouldBeNil)
})
Convey("test find mail log", t, func() {
mailLogs, err := d.FindMailLog(username)
So(len(mailLogs), ShouldBeGreaterThan, 0)
So(err, ShouldBeNil)
})
Convey("test delete mail log", t, func() {
err := d.DelMailLog(username)
So(err, ShouldBeNil)
})
Convey("test find mail log", t, func() {
mailLogs, err := d.FindMailLog(username)
So(len(mailLogs), ShouldEqual, 0)
So(err, ShouldBeNil)
})
}
| LQJJ/demo | 126-go-common-master/app/admin/ep/merlin/dao/mysql_mail_log_test.go | GO | apache-2.0 | 832 |
import styled, { css as styledCss, keyframes } from 'styled-components'
import type { TTestable } from '@/spec'
import Img from '@/Img'
import { theme } from '@/utils/themes'
import css from '@/utils/css'
const DURATION = '2.5s'
const load = keyframes`
0% {
top: 24px;
}
70% {
top: 10px;
}
90% {
top: 0;
}
95% {
top: 0;
}
100% {
top: 24px;
}
`
const liquid1 = keyframes`
0% {
height: 0;
opacity: 0;
top: -5px;
}
22% {
height: 2.8125px;
top: 3.75px;
opacity: 1;
}
25% {
top: -2.5px;
}
35% {
height: 11.25px;
top: -5px;
}
55% {
height: 3px;
top: -1.25px;
}
60% {
height: 6px;
opacity: 1;
top: -3px;
}
96% {
height: 8.4375px;
opacity: 0;
top: 5px;
}
100% {
height: 0;
opacity: 0;
}
`
const liquid2 = keyframes`
0% {
height: 0;
opacity: 0;
top: -0.5rem;
}
17.5% {
height: 3px;
top: 2px;
opacity: 1;
}
20% {
top: -2.5px;
}
25% {
height: 15px;
top: -6px;
}
45% {
height: 3px;
top: -1px;
}
60% {
opacity: 1;
height: 15px;
top: -5px;
}
96% {
opacity: 0;
height: 8px;
top: 5px;
}
100% {
height: 0;
opacity: 0;
}
`
const loadRule = styledCss`
${load} ${DURATION} infinite;
`
const liquid1Rule = styledCss`
${liquid1} ${DURATION} infinite;
`
const liquid2Rule = styledCss`
${liquid2} ${DURATION} infinite;
`
export const Wrapper = styled.div.attrs(({ testid }: TTestable) => ({
'data-test-id': testid,
}))<TTestable>`
text-align: center;
position: relative;
height: 28px;
margin-bottom: 6px;
cursor: pointer;
`
export const Battery = styled.div`
display: inline-block;
position: relative;
width: 16px;
height: 26px;
box-shadow: 0 0 0 2px #155e76;
border-radius: 2px;
&:before {
content: '';
position: absolute;
left: 5px;
top: -4px;
height: 3px;
width: 6px;
background: #155e76;
border-radius: 2px;
}
${Wrapper}:hover & {
&:after {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
border-right: 16px solid transparent;
border-bottom: 22px solid rgba(255, 255, 255, 0.25);
}
}
`
export const Liquid = styled.div`
position: absolute;
top: 23px;
bottom: 0;
left: 0;
right: 0;
width: 16px;
background: ${theme('baseColor.green')};
${Wrapper}:hover & {
top: 0;
animation: ${loadRule};
&:before {
left: 0;
animation: ${liquid2Rule};
content: '';
position: absolute;
top: -5px;
height: 11.25px;
width: 14.625px;
background: ${theme('baseColor.green')};
border-radius: 50%;
opacity: 0;
}
&:after {
right: 0;
animation: ${liquid1Rule};
content: '';
position: absolute;
top: -5px;
height: 11.25px;
width: 14.625px;
background: ${theme('baseColor.green')};
border-radius: 50%;
opacity: 0;
}
}
`
export const MoneySign = styled(Img)`
position: absolute;
top: 6px;
left: 3px;
${css.size(10)};
fill: #327faf;
transition: opacity 0.25s;
${Wrapper}:hover & {
fill: #ecbcb3;
top: 8px;
left: 2px;
${css.size(12)};
}
transition: all 0.2s;
`
| mydearxym/mastani | src/widgets/Charger/styles/index.ts | TypeScript | apache-2.0 | 3,323 |
/*
* Copyright (c) 2017 Antony Esik
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ae.camunda.dispatcher.mapper.xml;
import com.ae.camunda.dispatcher.api.mapper.TaskMapper;
import com.ae.camunda.dispatcher.exception.CamundaMappingException;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.springframework.stereotype.Component;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collections;
/**
* @author AEsik
* Date 09.10.2017
*/
@Component
public class XmlTaskMapper implements TaskMapper {
@Override
public String map(Object task) {
try {
JAXBContext context = JAXBContextFactory.createContext(new Class[]{task.getClass()}, Collections.emptyMap());
StringWriter sw = new StringWriter();
context.createMarshaller().marshal(task, sw);
return sw.toString();
} catch (JAXBException e) {
throw new CamundaMappingException(e);
}
}
@Override
public Object map(String body, Class<?> clazz) {
try {
JAXBContext context = JAXBContextFactory.createContext(new Class[]{clazz}, Collections.emptyMap());
StringReader sr = new StringReader(body);
return context.createUnmarshaller().unmarshal(sr);
} catch (JAXBException e) {
throw new CamundaMappingException(e);
}
}
}
| EsikAntony/camunda-task-dispatcher | camunda-task-dispatcher-mapper-xml/src/main/java/com/ae/camunda/dispatcher/mapper/xml/XmlTaskMapper.java | Java | apache-2.0 | 1,991 |
/*
Copyright 2022 The Vitess 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 physical
import (
"strings"
"vitess.io/vitess/go/mysql/collations"
"vitess.io/vitess/go/sqltypes"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/evalengine"
)
func (rp *Route) findSysInfoRoutingPredicatesGen4(predicates []sqlparser.Expr, reservedVars *sqlparser.ReservedVars) error {
for _, pred := range predicates {
isTableSchema, bvName, out, err := extractInfoSchemaRoutingPredicate(pred, reservedVars)
if err != nil {
return err
}
if out == nil {
// we didn't find a predicate to use for routing, continue to look for next predicate
continue
}
if isTableSchema {
rp.SysTableTableSchema = append(rp.SysTableTableSchema, out)
} else {
if rp.SysTableTableName == nil {
rp.SysTableTableName = map[string]evalengine.Expr{}
}
rp.SysTableTableName[bvName] = out
}
}
return nil
}
func extractInfoSchemaRoutingPredicate(in sqlparser.Expr, reservedVars *sqlparser.ReservedVars) (bool, string, evalengine.Expr, error) {
switch cmp := in.(type) {
case *sqlparser.ComparisonExpr:
if cmp.Operator == sqlparser.EqualOp {
isSchemaName, col, other, replaceOther := findOtherComparator(cmp)
if col != nil && shouldRewrite(other) {
evalExpr, err := evalengine.Translate(other, ¬ImplementedSchemaInfoConverter{})
if err != nil {
if strings.Contains(err.Error(), evalengine.ErrTranslateExprNotSupported) {
// This just means we can't rewrite this particular expression,
// not that we have to exit altogether
return false, "", nil, nil
}
return false, "", nil, err
}
var name string
if isSchemaName {
name = sqltypes.BvSchemaName
} else {
name = reservedVars.ReserveColName(col.(*sqlparser.ColName))
}
replaceOther(sqlparser.NewArgument(name))
return isSchemaName, name, evalExpr, nil
}
}
}
return false, "", nil, nil
}
func findOtherComparator(cmp *sqlparser.ComparisonExpr) (bool, sqlparser.Expr, sqlparser.Expr, func(arg sqlparser.Argument)) {
if schema, table := isTableSchemaOrName(cmp.Left); schema || table {
return schema, cmp.Left, cmp.Right, func(arg sqlparser.Argument) {
cmp.Right = arg
}
}
if schema, table := isTableSchemaOrName(cmp.Right); schema || table {
return schema, cmp.Right, cmp.Left, func(arg sqlparser.Argument) {
cmp.Left = arg
}
}
return false, nil, nil, nil
}
func shouldRewrite(e sqlparser.Expr) bool {
switch node := e.(type) {
case *sqlparser.FuncExpr:
// we should not rewrite database() calls against information_schema
return !(node.Name.EqualString("database") || node.Name.EqualString("schema"))
}
return true
}
func isTableSchemaOrName(e sqlparser.Expr) (isTableSchema bool, isTableName bool) {
col, ok := e.(*sqlparser.ColName)
if !ok {
return false, false
}
return isDbNameCol(col), isTableNameCol(col)
}
func isDbNameCol(col *sqlparser.ColName) bool {
return col.Name.EqualString("table_schema") || col.Name.EqualString("constraint_schema") || col.Name.EqualString("schema_name") || col.Name.EqualString("routine_schema")
}
func isTableNameCol(col *sqlparser.ColName) bool {
return col.Name.EqualString("table_name")
}
type notImplementedSchemaInfoConverter struct{}
func (f *notImplementedSchemaInfoConverter) ColumnLookup(*sqlparser.ColName) (int, error) {
return 0, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "Comparing table schema name with a column name not yet supported")
}
func (f *notImplementedSchemaInfoConverter) CollationForExpr(sqlparser.Expr) collations.ID {
return collations.Unknown
}
func (f *notImplementedSchemaInfoConverter) DefaultCollation() collations.ID {
return collations.Default()
}
| vitessio/vitess | go/vt/vtgate/planbuilder/physical/system_tables.go | GO | apache-2.0 | 4,314 |
"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
| titilambert/home-assistant | homeassistant/components/template/switch.py | Python | apache-2.0 | 6,023 |
package org.whale.ext.domain;
import java.util.ArrayList;
import java.util.List;
import org.whale.system.annotation.jdbc.Column;
import org.whale.system.annotation.jdbc.Id;
import org.whale.system.annotation.jdbc.Table;
import org.whale.system.annotation.jdbc.Validate;
import org.whale.system.base.BaseEntry;
import org.whale.system.common.util.PropertiesUtil;
/**
* 实体对象
*
* @author wjs
* 2014年9月10日-上午10:12:48
*/
@Table(value="sys_domian", cnName="实体对象")
public class Domain extends BaseEntry{
private static final long serialVersionUID = -23042834921L;
@Id
@Column(cnName="id")
private Long id;
@Validate(required=true)
@Column(cnName="实体名")
private String domainName;
@Validate(required=true)
@Column(cnName="中文名")
private String domainCnName;
@Validate(required=true)
@Column(cnName="数据库", unique=true)
private String domainSqlName;
@Column(cnName="基础包路径")
private String pkgName = "org.whale.system";
//树模型
private Integer treeModel;
private String treeId;
private String treePid;
private String treeName;
//模板类型
private Integer ftlType;
//代码路径
private String codePath;
private String author = PropertiesUtil.getValue("author", "wjs");
//主键
private Attr idAttr;
private List<Attr> attrs;
private List<Attr> listAttrs = new ArrayList<Attr>();
private List<Attr> formAttrs = new ArrayList<Attr>();
private List<Attr> queryAttrs = new ArrayList<Attr>();
public Long getId() {
return id;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getDomainCnName() {
return domainCnName;
}
public void setDomainCnName(String domainCnName) {
this.domainCnName = domainCnName;
}
public String getDomainSqlName() {
return domainSqlName;
}
public void setDomainSqlName(String domainSqlName) {
this.domainSqlName = domainSqlName;
}
public String getPkgName() {
return pkgName;
}
public void setPkgName(String pkgName) {
this.pkgName = pkgName;
}
public Attr getIdAttr() {
return idAttr;
}
public void setIdAttr(Attr idAttr) {
this.idAttr = idAttr;
}
public List<Attr> getAttrs() {
return attrs;
}
public void setAttrs(List<Attr> attrs) {
this.attrs = attrs;
}
public List<Attr> getListAttrs() {
return listAttrs;
}
public void setListAttrs(List<Attr> listAttrs) {
this.listAttrs = listAttrs;
}
public List<Attr> getFormAttrs() {
return formAttrs;
}
public void setFormAttrs(List<Attr> formAttrs) {
this.formAttrs = formAttrs;
}
public List<Attr> getQueryAttrs() {
return queryAttrs;
}
public void setQueryAttrs(List<Attr> queryAttrs) {
this.queryAttrs = queryAttrs;
}
public void setId(Long id) {
this.id = id;
}
public Integer getFtlType() {
return ftlType;
}
public void setFtlType(Integer ftlType) {
this.ftlType = ftlType;
}
public String getCodePath() {
return codePath;
}
public void setCodePath(String codePath) {
this.codePath = codePath;
}
public Integer getTreeModel() {
return treeModel;
}
public void setTreeModel(Integer treeModel) {
this.treeModel = treeModel;
}
public String getTreeId() {
return treeId;
}
public void setTreeId(String treeId) {
this.treeId = treeId;
}
public String getTreePid() {
return treePid;
}
public void setTreePid(String treePid) {
this.treePid = treePid;
}
public String getTreeName() {
return treeName;
}
public void setTreeName(String treeName) {
this.treeName = treeName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
| fywxin/base | system-parent/ext-code/src/main/java/org/whale/ext/domain/Domain.java | Java | apache-2.0 | 3,741 |
/*
* syscall.cpp
*
* Created on: Jun 3, 2017
* Author: warlo
*/
#include "syscall.hpp"
#include <diag\Trace.h>
namespace os {
#if 0
static void dispatch_syscall(void) naked_function;
static void dispatch_syscall(void)
{
__asm__ __volatile__
(
" sub sp, sp, #16\n" /* Create a stack frame to hold 3 parms + lr */
" str r4, [sp, #0]\n" /* Move parameter 4 (if any) into position */
" str r5, [sp, #4]\n" /* Move parameter 5 (if any) into position */
" str r6, [sp, #8]\n" /* Move parameter 6 (if any) into position */
" str lr, [sp, #12]\n" /* Save lr in the stack frame */
" ldr ip, =g_stublookup\n" /* R12=The base of the stub lookup table */
" ldr ip, [ip, r0, lsl #2]\n" /* R12=The address of the stub for this syscall */
" blx ip\n" /* Call the stub (modifies lr) */
" ldr lr, [sp, #12]\n" /* Restore lr */
" add sp, sp, #16\n" /* Destroy the stack frame */
" mov r2, r0\n" /* R2=Save return value in R2 */
" mov r0, #3\n" /* R0=SYS_syscall_return */
" svc 0" /* Return from the syscall */
);
}
#endif
}
#if 0
enum register_stack_t {
/* Saved by hardware */
REG_R0,
REG_R1,
REG_R2,
REG_R3,
REG_R12,
REG_LR,
REG_PC,
REG_xPSR
};
#define RESERVED_STACK \
(8 * sizeof(uint32_t))
static void dispatch_syscall() __attribute((naked));
static void dispatch_syscall(uint32_t* caller) __attribute((naked)){
uint32_t svc_num = ((char *) caller[REG_PC])[-2];
}
void syscall_init(uint8_t nbr, uintptr_t call){
assert(nbr < MAX_SYSCALLS);
caller = call;
}
}
template<uintptr_t FROM, uintptr_t TO> static inline void copy_stack(){
__asm volatile(
"ldr r12, [sp, %0]\n"
"str r12, [sp, %1]\n"
: "i"(FROM), "i"(TO) ::"r12");
}
__attribute((always_inline) )static inline void copy_memory(uintptr from, uintptr_t to)
__attribute((always_inline) )static inline void copy_stack() {
__asm__ __volatile__ ("push {r12 }sub sp, #(8*4)\n");
copy_stack<REG_R0+8, REG_R0>();
}
#endif
//extern "C" void SVC_Handler() __attribute((naked)) ;
#if 0
extern "C" void SVC_Handler() {
assert(0);
}
#endif
| WarlockD/arm-cortex-v7-unix | f9_os/inc/os/syscall.cpp | C++ | apache-2.0 | 2,217 |
# Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
| google-research/federated | fedopt_guide/cifar10_resnet/federated_cifar10.py | Python | apache-2.0 | 5,796 |
/* ========================================================================= *
* Boarder *
* http://boarder.mikuz.org/ *
* ========================================================================= *
* Copyright (C) 2013 Boarder *
* *
* 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 fi.mikuz.boarder.util;
import org.acra.ACRA;
import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public abstract class ContextUtils {
private static final String TAG = ContextUtils.class.getSimpleName();
public static void toast(Context context, String toast) {
toast(context, toast, Toast.LENGTH_SHORT);
}
public static void toast(Context context, String toast, int duration) {
String errLogMsg = "Unable to toast message: \"" + toast + "\"";
if (Looper.myLooper() == null) {
Exception e = new IllegalStateException("Not running in a looper");
Log.e(TAG, errLogMsg, e);
ACRA.getErrorReporter().handleException(e);
} else if (Looper.myLooper() != Looper.getMainLooper()) {
Exception e = new IllegalStateException("Not running in the main looper");
Log.e(TAG, errLogMsg, e);
ACRA.getErrorReporter().handleException(e);
} else {
try {
Toast.makeText(context, toast, duration).show();
} catch (NullPointerException e) {
Log.e(TAG, errLogMsg, e);
}
}
}
}
| Mikuz/Boarder | src/fi/mikuz/boarder/util/ContextUtils.java | Java | apache-2.0 | 2,556 |
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <typeinfo>
#include "color/color.hpp"
int main( int argc, char *argv[] )
{
using namespace color;
using namespace std;
cout << "gray<std::uint8_t > is: " << typeid( trait::component< gray< std::uint8_t >::category_type >::instance_type ).name() << endl;
cout << "gray<std::uint32_t> is: " << typeid( trait::component< gray< std::uint32_t >::category_type >::instance_type ).name() << endl;
cout << "gray<float > is: " << typeid( trait::component< gray< float >::category_type >::instance_type ).name() << endl;
cout << "gray<double > is: " << typeid( trait::component< gray< double >::category_type >::instance_type ).name() << endl;
cout << "gray<long double > is: " << typeid( trait::component< gray< long double >::category_type >::instance_type ).name() << endl;
return EXIT_SUCCESS;
} | dmilos/color | example/less-than-1k/trait/component/gray.cpp | C++ | apache-2.0 | 928 |
package com.gentics.mesh.changelog.changes;
import static com.gentics.mesh.core.data.relationship.GraphRelationships.SCHEMA_CONTAINER_VERSION_KEY_PROPERTY;
import com.gentics.mesh.changelog.AbstractChange;
import com.tinkerpop.blueprints.Direction;
/**
* Changelog entry which removed the schema version edges with properties
*/
public class ReplaceSchemaVersionEdges extends AbstractChange {
@Override
public String getUuid() {
return "E737684330534623B768433053C623F2";
}
@Override
public String getName() {
return "ReplaceSchemaVersionEdges";
}
@Override
public String getDescription() {
return "Replaces edges from node content to schema versions with properties.";
}
@Override
public void applyInTx() {
replaceSingleEdge("NodeGraphFieldContainerImpl", Direction.OUT, "HAS_SCHEMA_CONTAINER_VERSION", SCHEMA_CONTAINER_VERSION_KEY_PROPERTY);
}
}
| gentics/mesh | changelog-system/src/main/java/com/gentics/mesh/changelog/changes/ReplaceSchemaVersionEdges.java | Java | apache-2.0 | 877 |
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using System;
#if Q8
using QuantumType = System.Byte;
#elif Q16
using QuantumType = System.UInt16;
#elif Q16HDRI
using QuantumType = System.Single;
#else
#error Not implemented!
#endif
namespace ImageMagick
{
/// <summary>
/// Class that represents a HSV color.
/// </summary>
public sealed class ColorHSV : ColorBase
{
/// <summary>
/// Initializes a new instance of the <see cref="ColorHSV"/> class.
/// </summary>
/// <param name="hue">Hue component value of this color.</param>
/// <param name="saturation">Saturation component value of this color.</param>
/// <param name="value">Value component value of this color.</param>
public ColorHSV(double hue, double saturation, double value)
: base(new MagickColor(0, 0, 0))
{
Hue = hue;
Saturation = saturation;
Value = value;
}
private ColorHSV(IMagickColor<QuantumType> color)
: base(color)
{
Initialize(color.R, color.G, color.B);
}
/// <summary>
/// Gets or sets the hue component value of this color.
/// </summary>
public double Hue { get; set; }
/// <summary>
/// Gets or sets the saturation component value of this color.
/// </summary>
public double Saturation { get; set; }
/// <summary>
/// Gets or sets the value component value of this color.
/// </summary>
public double Value { get; set; }
/// <summary>
/// Converts the specified <see cref="MagickColor"/> to an instance of this type.
/// </summary>
/// <param name="color">The color to use.</param>
/// <returns>A <see cref="ColorHSV"/> instance.</returns>
public static implicit operator ColorHSV?(MagickColor color)
=> FromMagickColor(color);
/// <summary>
/// Converts the specified <see cref="IMagickColor{QuantumType}"/> to an instance of this type.
/// </summary>
/// <param name="color">The color to use.</param>
/// <returns>A <see cref="ColorHSV"/> instance.</returns>
public static ColorHSV? FromMagickColor(IMagickColor<QuantumType> color)
{
if (color == null)
return null;
return new ColorHSV(color);
}
/// <summary>
/// Performs a hue shift with the specified degrees.
/// </summary>
/// <param name="degrees">The degrees.</param>
public void HueShift(double degrees)
{
Hue += degrees / 360.0;
while (Hue >= 1.0)
Hue -= 1.0;
while (Hue < 0.0)
Hue += 1.0;
}
/// <summary>
/// Updates the color value in an inherited class.
/// </summary>
protected override void UpdateColor()
{
if (Math.Abs(Saturation) < double.Epsilon)
{
Color.R = Color.G = Color.B = Quantum.ScaleToQuantum(Value);
return;
}
var h = 6.0 * (Hue - Math.Floor(Hue));
var f = h - Math.Floor(h);
var p = Value * (1.0 - Saturation);
var q = Value * (1.0 - (Saturation * f));
var t = Value * (1.0 - (Saturation * (1.0 - f)));
switch ((int)h)
{
case 0:
default:
Color.R = Quantum.ScaleToQuantum(Value);
Color.G = Quantum.ScaleToQuantum(t);
Color.B = Quantum.ScaleToQuantum(p);
break;
case 1:
Color.R = Quantum.ScaleToQuantum(q);
Color.G = Quantum.ScaleToQuantum(Value);
Color.B = Quantum.ScaleToQuantum(p);
break;
case 2:
Color.R = Quantum.ScaleToQuantum(p);
Color.G = Quantum.ScaleToQuantum(Value);
Color.B = Quantum.ScaleToQuantum(t);
break;
case 3:
Color.R = Quantum.ScaleToQuantum(p);
Color.G = Quantum.ScaleToQuantum(q);
Color.B = Quantum.ScaleToQuantum(Value);
break;
case 4:
Color.R = Quantum.ScaleToQuantum(t);
Color.G = Quantum.ScaleToQuantum(p);
Color.B = Quantum.ScaleToQuantum(Value);
break;
case 5:
Color.R = Quantum.ScaleToQuantum(Value);
Color.G = Quantum.ScaleToQuantum(p);
Color.B = Quantum.ScaleToQuantum(q);
break;
}
}
private void Initialize(double red, double green, double blue)
{
Hue = 0.0;
Saturation = 0.0;
Value = 0.0;
var min = Math.Min(Math.Min(red, green), blue);
var max = Math.Max(Math.Max(red, green), blue);
if (Math.Abs(max) < double.Epsilon)
return;
var delta = max - min;
Saturation = delta / max;
Value = (1.0 / Quantum.Max) * max;
if (Math.Abs(delta) < double.Epsilon)
return;
if (Math.Abs(red - max) < double.Epsilon)
Hue = (green - blue) / delta;
else if (Math.Abs(green - max) < double.Epsilon)
Hue = 2.0 + ((blue - red) / delta);
else
Hue = 4.0 + ((red - green) / delta);
Hue /= 6.0;
if (Hue < 0.0)
Hue += 1.0;
}
}
}
| dlemstra/Magick.NET | src/Magick.NET/Colors/ColorHSV.cs | C# | apache-2.0 | 5,867 |
package cc.mallet.util;
/**
* Static utility methods for Strings
*/
final public class Strings {
public static int commonPrefixIndex (String[] strings)
{
int prefixLen = strings[0].length();
for (int i = 1; i < strings.length; i++) {
if (strings[i].length() < prefixLen)
prefixLen = strings[i].length();
int j = 0;
if (prefixLen == 0)
return 0;
while (j < prefixLen) {
if (strings[i-1].charAt(j) != strings[i].charAt(j)) {
prefixLen = j;
break;
}
j++;
}
}
return prefixLen;
}
public static String commonPrefix (String[] strings)
{
return strings[0].substring (0, commonPrefixIndex(strings));
}
public static int count (String string, char ch)
{
int idx = -1;
int count = 0;
while ((idx = string.indexOf (ch, idx+1)) >= 0) { count++; };
return count;
}
public static double levenshteinDistance (String s, String t) {
int n = s.length();
int m = t.length();
int d[][]; // matrix
int i; // iterates through s
int j; // iterates through t
char s_i; // ith character of s
char t_j; // jth character of t
int cost; // cost
if (n == 0)
return 1.0;
if (m == 0)
return 1.0;
d = new int[n+1][m+1];
for (i = 0; i <= n; i++)
d[i][0] = i;
for (j = 0; j <= m; j++)
d[0][j] = j;
for (i = 1; i <= n; i++) {
s_i = s.charAt (i - 1);
for (j = 1; j <= m; j++) {
t_j = t.charAt (j - 1);
cost = (s_i == t_j) ? 0 : 1;
d[i][j] = minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);
}
}
int longer = (n > m) ? n : m;
return (double)d[n][m] / longer; // Normalize to 0-1.
}
private static int minimum (int a, int b, int c) {
int mi = a;
if (b < mi) {
mi = b;
}
if (c < mi) {
mi = c;
}
return mi;
}
}
| UnsupervisedOntologyLearning/hrLDA | hrLDA/src/cc/mallet/util/Strings.java | Java | apache-2.0 | 1,930 |
package org.museautomation.core.step;
import org.jetbrains.annotations.*;
import org.museautomation.core.*;
import org.museautomation.core.context.*;
import org.museautomation.core.step.descriptor.*;
import org.museautomation.core.steptask.*;
import org.museautomation.core.values.*;
import org.museautomation.core.values.descriptor.*;
import java.util.*;
/**
* Executes the steps contained within a Macro.
*
* Note that this does NOT execute those steps within a separate variable scope, despite this class extending
* ScopedGroup. It overrides #isCreateNewVariableScope to disable that behavior. That seems a bit strange, but
* CallFunction builds on the basic function of CallMacroStep and it needs to be scoped. We need multiple-inheritance
* to do this cleanly (yuck), but this will have to suffice.
*
* @see Macro
* @author Christopher L Merrill (see LICENSE.txt for license details)
*/
@MuseTypeId("callmacro")
@MuseStepName("Macro")
@MuseInlineEditString("call macro {id}")
@MuseStepIcon("glyph:FontAwesome:EXTERNAL_LINK")
@MuseStepTypeGroup("Structure")
@MuseStepLongDescription("The 'id' source is resolved to a string and used to find the macro in the project. The steps within the macro are then executed as children of the call-macro step, within the same variable scope as the parent. This means that steps within the macro have access to the same variables as the caller.")
@MuseSubsourceDescriptor(displayName = "Macro name", description = "The name (resource id) of the macro to call", type = SubsourceDescriptor.Type.Named, name = CallMacroStep.ID_PARAM)
public class CallMacroStep extends ScopedGroup
{
@SuppressWarnings("unused") // called via reflection
public CallMacroStep(StepConfiguration config, MuseProject project)
{
super(config, project);
_config = config;
_project = project;
}
@Override
protected StepExecutionContext createStepExecutionContextForChildren(StepExecutionContext context) throws MuseExecutionError
{
String id = getStepsId(context);
ContainsStep resource = _project.getResourceStorage().getResource(id, ContainsStep.class);
if (resource == null)
throw new StepExecutionError("unable to locate project resource, id=" + id);
StepConfiguration step = resource.getStep();
List<StepConfiguration> steps;
if (step.getChildren() != null && step.getChildren().size() > 0)
steps = step.getChildren();
else
{
steps = new ArrayList<>();
steps.add(step);
}
context.getStepLocator().loadSteps(steps);
context.raiseEvent(DynamicStepLoadingEventType.create(_config, steps));
return new ListOfStepsExecutionContext(context.getParent(), steps, isCreateNewVariableScope(), this);
}
/**
* Get the id of the project resource that contains the steps that should be run.
*/
@NotNull
@SuppressWarnings("WeakerAccess")
protected String getStepsId(StepExecutionContext context) throws MuseExecutionError
{
MuseValueSource id_source = getValueSource(_config, ID_PARAM, true, context.getProject());
return BaseValueSource.getValue(id_source, context, false, String.class);
}
@Override
protected boolean isCreateNewVariableScope()
{
return false;
}
protected MuseProject _project;
private StepConfiguration _config;
public final static String ID_PARAM = "id";
public final static String TYPE_ID = CallMacroStep.class.getAnnotation(MuseTypeId.class).value();
} | ChrisLMerrill/muse | core/src/main/java/org/museautomation/core/step/CallMacroStep.java | Java | apache-2.0 | 3,625 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.diff.impl.patch.formove;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diff.impl.patch.FilePatch;
import com.intellij.openapi.diff.impl.patch.TextFilePatch;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchBase;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchFactory;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.fileTypes.ex.FileTypeChooser;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.patch.RelativePathCalculator;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class PathsVerifier {
// in
private final Project myProject;
private final VirtualFile myBaseDirectory;
private final List<FilePatch> myPatches;
// temp
private final Map<VirtualFile, MovedFileData> myMovedFiles;
private final List<FilePath> myBeforePaths;
private final List<VirtualFile> myCreatedDirectories;
// out
private final List<PatchAndFile> myTextPatches;
private final List<PatchAndFile> myBinaryPatches;
@NotNull private final List<VirtualFile> myWritableFiles;
private final ProjectLevelVcsManager myVcsManager;
private final List<FilePatch> mySkipped;
private DelayedPrecheckContext myDelayedPrecheckContext;
private final List<FilePath> myAddedPaths;
private final List<FilePath> myDeletedPaths;
private boolean myIgnoreContentRootsCheck;
public PathsVerifier(@NotNull Project project,
@NotNull VirtualFile baseDirectory,
@NotNull List<FilePatch> patches) {
myProject = project;
myBaseDirectory = baseDirectory;
myPatches = patches;
myMovedFiles = new HashMap<>();
myBeforePaths = new ArrayList<>();
myCreatedDirectories = new ArrayList<>();
myTextPatches = new ArrayList<>();
myBinaryPatches = new ArrayList<>();
myWritableFiles = new ArrayList<>();
myVcsManager = ProjectLevelVcsManager.getInstance(myProject);
mySkipped = new ArrayList<>();
myAddedPaths = new ArrayList<>();
myDeletedPaths = new ArrayList<>();
}
// those to be moved to CL: target + created dirs
public List<FilePath> getDirectlyAffected() {
final List<FilePath> affected = new ArrayList<>();
addAllFilePath(myCreatedDirectories, affected);
addAllFilePath(myWritableFiles, affected);
affected.addAll(myBeforePaths);
return affected;
}
// old parents of moved files
public List<VirtualFile> getAllAffected() {
final List<VirtualFile> affected = new ArrayList<>();
affected.addAll(myCreatedDirectories);
affected.addAll(myWritableFiles);
// after files' parent
for (VirtualFile file : myMovedFiles.keySet()) {
final VirtualFile parent = file.getParent();
if (parent != null) {
affected.add(parent);
}
}
// before..
for (FilePath path : myBeforePaths) {
final FilePath parent = path.getParentPath();
if (parent != null) {
affected.add(parent.getVirtualFile());
}
}
return affected;
}
private static void addAllFilePath(final Collection<VirtualFile> files, final Collection<FilePath> paths) {
for (VirtualFile file : files) {
paths.add(VcsUtil.getFilePath(file));
}
}
@CalledInAwt
public List<FilePatch> nonWriteActionPreCheck() {
List<FilePatch> failedToApply = ContainerUtil.newArrayList();
myDelayedPrecheckContext = new DelayedPrecheckContext(myProject);
for (FilePatch patch : myPatches) {
final CheckPath checker = getChecker(patch);
if (!checker.canBeApplied(myDelayedPrecheckContext)) {
revert(checker.getErrorMessage());
failedToApply.add(patch);
}
}
final Collection<FilePatch> skipped = myDelayedPrecheckContext.doDelayed();
mySkipped.addAll(skipped);
myPatches.removeAll(skipped);
myPatches.removeAll(failedToApply);
return failedToApply;
}
public List<FilePatch> getSkipped() {
return mySkipped;
}
public List<FilePatch> execute() {
List<FilePatch> failedPatches = ContainerUtil.newArrayList();
try {
final List<CheckPath> checkers = new ArrayList<>(myPatches.size());
for (FilePatch patch : myPatches) {
final CheckPath checker = getChecker(patch);
checkers.add(checker);
}
for (CheckPath checker : checkers) {
if (!checker.check()) {
failedPatches.add(checker.getPatch());
revert(checker.getErrorMessage());
}
}
}
catch (IOException e) {
revert(e.getMessage());
}
myPatches.removeAll(failedPatches);
return failedPatches;
}
private CheckPath getChecker(final FilePatch patch) {
final String beforeFileName = patch.getBeforeName();
final String afterFileName = patch.getAfterName();
if (beforeFileName == null || patch.isNewFile()) {
return new CheckAdded(patch);
}
else if (afterFileName == null || patch.isDeletedFile()) {
return new CheckDeleted(patch);
}
else if (!beforeFileName.equals(afterFileName)) {
return new CheckMoved(patch);
}
else {
return new CheckModified(patch);
}
}
public Collection<FilePath> getToBeAdded() {
return myAddedPaths;
}
public Collection<FilePath> getToBeDeleted() {
return myDeletedPaths;
}
@NotNull
public Collection<FilePatch> filterBadFileTypePatches() {
List<PatchAndFile> failedTextPatches =
ContainerUtil.findAll(myTextPatches, textPatch -> !isFileTypeOk(textPatch.getFile()));
myTextPatches.removeAll(failedTextPatches);
return ContainerUtil.map(failedTextPatches, patchInfo -> patchInfo.getApplyPatch().getPatch());
}
private boolean isFileTypeOk(@NotNull VirtualFile file) {
if (file.isDirectory()) {
PatchApplier
.showError(myProject, "Cannot apply content for " + file.getPresentableName() + " file from patch because it is directory.");
return false;
}
FileType fileType = file.getFileType();
if (fileType == FileTypes.UNKNOWN) {
fileType = FileTypeChooser.associateFileType(file.getName());
if (fileType == null) {
PatchApplier
.showError(myProject, "Cannot apply content for " + file.getPresentableName() + " file from patch because its type not defined.");
return false;
}
}
if (fileType.isBinary()) {
PatchApplier.showError(myProject, "Cannot apply file " + file.getPresentableName() + " from patch because it is binary.");
return false;
}
return true;
}
private class CheckModified extends CheckDeleted {
private CheckModified(final FilePatch path) {
super(path);
}
}
private class CheckDeleted extends CheckPath {
protected CheckDeleted(final FilePatch path) {
super(path);
}
@Override
protected boolean precheck(final VirtualFile beforeFile, final VirtualFile afterFile, DelayedPrecheckContext context) {
if (beforeFile == null) {
context.addSkip(getMappedFilePath(myBeforeName), myPatch);
}
return true;
}
@Override
protected boolean check() {
final VirtualFile beforeFile = getMappedFile(myBeforeName);
if (! checkExistsAndValid(beforeFile, myBeforeName)) {
return false;
}
addPatch(myPatch, beforeFile);
FilePath filePath = VcsUtil.getFilePath(beforeFile.getParent(), beforeFile.getName(), beforeFile.isDirectory());
if (myPatch.isDeletedFile() || myPatch.getAfterName() == null) {
myDeletedPaths.add(filePath);
}
myBeforePaths.add(filePath);
return true;
}
}
private class CheckAdded extends CheckPath {
private CheckAdded(final FilePatch path) {
super(path);
}
@Override
protected boolean precheck(final VirtualFile beforeFile, final VirtualFile afterFile, DelayedPrecheckContext context) {
if (afterFile != null) {
context.addOverrideExisting(myPatch, VcsUtil.getFilePath(afterFile));
}
return true;
}
@Override
public boolean check() throws IOException {
final String[] pieces = RelativePathCalculator.split(myAfterName);
final VirtualFile parent = makeSureParentPathExists(pieces);
if (parent == null) {
setErrorMessage(fileNotFoundMessage(myAfterName));
return false;
}
String name = pieces[pieces.length - 1];
File afterFile = new File(parent.getPath(), name);
//if user already accepted overwriting, we shouldn't have created a new one
final VirtualFile file = myDelayedPrecheckContext.getOverridenPaths().contains(VcsUtil.getFilePath(afterFile))
? parent.findChild(name)
: createFile(parent, name);
if (file == null) {
setErrorMessage(fileNotFoundMessage(myAfterName));
return false;
}
myAddedPaths.add(VcsUtil.getFilePath(file));
if (! checkExistsAndValid(file, myAfterName)) {
return false;
}
addPatch(myPatch, file);
return true;
}
}
private class CheckMoved extends CheckPath {
private CheckMoved(final FilePatch path) {
super(path);
}
// before exists; after does not exist
@Override
protected boolean precheck(final VirtualFile beforeFile, final VirtualFile afterFile, final DelayedPrecheckContext context) {
if (beforeFile == null) {
setErrorMessage(fileNotFoundMessage(myBeforeName));
} else if (afterFile != null) {
setErrorMessage(fileAlreadyExists(afterFile.getPath()));
}
return beforeFile != null && afterFile == null;
}
@Override
public boolean check() throws IOException {
final String[] pieces = RelativePathCalculator.split(myAfterName);
final VirtualFile afterFileParent = makeSureParentPathExists(pieces);
if (afterFileParent == null) {
setErrorMessage(fileNotFoundMessage(myAfterName));
return false;
}
final VirtualFile beforeFile = getMappedFile(myBeforeName);
if (! checkExistsAndValid(beforeFile, myBeforeName)) {
return false;
}
assert beforeFile != null; // if beforeFile is null then checkExist returned false;
myMovedFiles.put(beforeFile, new MovedFileData(afterFileParent, beforeFile, myPatch.getAfterFileName()));
addPatch(myPatch, beforeFile);
return true;
}
}
private abstract class CheckPath {
protected final String myBeforeName;
protected final String myAfterName;
protected final FilePatch myPatch;
private String myErrorMessage;
CheckPath(final FilePatch path) {
myPatch = path;
myBeforeName = path.getBeforeName();
myAfterName = path.getAfterName();
}
public String getErrorMessage() {
return myErrorMessage;
}
public void setErrorMessage(final String errorMessage) {
myErrorMessage = errorMessage;
}
public boolean canBeApplied(DelayedPrecheckContext context) {
final VirtualFile beforeFile = getMappedFile(myBeforeName);
final VirtualFile afterFile = getMappedFile(myAfterName);
return precheck(beforeFile, afterFile, context);
}
protected abstract boolean precheck(final VirtualFile beforeFile,
final VirtualFile afterFile,
DelayedPrecheckContext context);
protected abstract boolean check() throws IOException;
protected boolean checkExistsAndValid(final VirtualFile file, final String name) {
if (file == null) {
setErrorMessage(fileNotFoundMessage(name));
return false;
}
return checkModificationValid(file, name);
}
protected boolean checkModificationValid(final VirtualFile file, final String name) {
if (ApplicationManager.getApplication().isUnitTestMode() && myIgnoreContentRootsCheck) return true;
// security check to avoid overwriting system files with a patch
if (file == null || !inContent(file) || myVcsManager.getVcsRootFor(file) == null) {
setErrorMessage("File to patch found outside content root: " + name);
return false;
}
return true;
}
@Nullable
protected VirtualFile getMappedFile(String path) {
return PathMerger.getFile(myBaseDirectory, path);
}
protected FilePath getMappedFilePath(String path) {
return PathMerger.getFile(VcsUtil.getFilePath(myBaseDirectory), path);
}
private boolean inContent(VirtualFile file) {
return myVcsManager.isFileInContent(file);
}
public FilePatch getPatch() {
return myPatch;
}
}
private void addPatch(final FilePatch patch, final VirtualFile file) {
if (patch instanceof TextFilePatch) {
myTextPatches.add(new PatchAndFile(file, ApplyFilePatchFactory.create((TextFilePatch)patch)));
}
else {
myBinaryPatches.add(new PatchAndFile(file, ApplyFilePatchFactory.createGeneral(patch)));
}
myWritableFiles.add(file);
}
private static String fileNotFoundMessage(final String path) {
return VcsBundle.message("cannot.find.file.to.patch", path);
}
private static String fileAlreadyExists(final String path) {
return VcsBundle.message("cannot.apply.file.already.exists", path);
}
private void revert(final String errorMessage) {
PatchApplier.showError(myProject, errorMessage);
// move back
/*for (MovedFileData movedFile : myMovedFiles) {
try {
final VirtualFile current = movedFile.getCurrent();
final VirtualFile newParent = current.getParent();
final VirtualFile file;
if (! Comparing.equal(newParent, movedFile.getOldParent())) {
file = moveFile(current, movedFile.getOldParent());
} else {
file = current;
}
if (! Comparing.equal(current.getName(), movedFile.getOldName())) {
file.rename(PatchApplier.class, movedFile.getOldName());
}
}
catch (IOException e) {
// ignore: revert as much as possible
}
}
// go back
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
for (int i = myCreatedDirectories.size() - 1; i >= 0; -- i) {
final VirtualFile file = myCreatedDirectories.get(i);
try {
file.delete(PatchApplier.class);
}
catch (IOException e) {
// ignore
}
}
}
});
myBinaryPatches.clear();
myTextPatches.clear();
myWritableFiles.clear();*/
}
private static VirtualFile createFile(final VirtualFile parent, final String name) throws IOException {
return parent.createChildData(PatchApplier.class, name);
/*final Ref<IOException> ioExceptionRef = new Ref<IOException>();
final Ref<VirtualFile> result = new Ref<VirtualFile>();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
result.set(parent.createChildData(PatchApplier.class, name));
}
catch (IOException e) {
ioExceptionRef.set(e);
}
}
});
if (! ioExceptionRef.isNull()) {
throw ioExceptionRef.get();
}
return result.get();*/
}
private static VirtualFile moveFile(final VirtualFile file, final VirtualFile newParent) throws IOException {
file.move(FilePatch.class, newParent);
return file;
/*final Ref<IOException> ioExceptionRef = new Ref<IOException>();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
file.move(FilePatch.class, newParent);
}
catch (IOException e) {
ioExceptionRef.set(e);
}
}
});
if (! ioExceptionRef.isNull()) {
throw ioExceptionRef.get();
}
return file;*/
}
@Nullable
private VirtualFile makeSureParentPathExists(final String[] pieces) throws IOException {
VirtualFile child = myBaseDirectory;
final int size = pieces.length - 1;
for (int i = 0; i < size; i++) {
final String piece = pieces[i];
if (StringUtil.isEmptyOrSpaces(piece)) {
continue;
}
if ("..".equals(piece)) {
child = child.getParent();
continue;
}
VirtualFile nextChild = child.findChild(piece);
if (nextChild == null) {
nextChild = VfsUtil.createDirectories(child.getPath() + '/' + piece);
myCreatedDirectories.add(nextChild);
}
child = nextChild;
}
return child;
}
public List<PatchAndFile> getTextPatches() {
return myTextPatches;
}
public List<PatchAndFile> getBinaryPatches() {
return myBinaryPatches;
}
@NotNull
public List<VirtualFile> getWritableFiles() {
return myWritableFiles;
}
public void doMoveIfNeeded(final VirtualFile file) throws IOException {
final MovedFileData movedFile = myMovedFiles.get(file);
if (movedFile != null) {
myBeforePaths.add(VcsUtil.getFilePath(file));
ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<VirtualFile, IOException>() {
@Override
public VirtualFile compute() throws IOException {
return movedFile.doMove();
}
});
}
}
private static class MovedFileData {
private final VirtualFile myNewParent;
private final VirtualFile myCurrent;
private final String myNewName;
private MovedFileData(@NotNull final VirtualFile newParent, @NotNull final VirtualFile current, @NotNull final String newName) {
myNewParent = newParent;
myCurrent = current;
myNewName = newName;
}
public VirtualFile getCurrent() {
return myCurrent;
}
public VirtualFile getNewParent() {
return myNewParent;
}
public String getNewName() {
return myNewName;
}
public VirtualFile doMove() throws IOException {
final VirtualFile oldParent = myCurrent.getParent();
boolean needRename = !Comparing.equal(myCurrent.getName(), myNewName);
boolean needMove = !myNewParent.equals(oldParent);
if (needRename) {
if (needMove) {
File oldParentFile = VfsUtilCore.virtualToIoFile(oldParent);
File targetAfterRenameFile = new File(oldParentFile, myNewName);
if (targetAfterRenameFile.exists() && myCurrent.exists()) {
// if there is a conflict during first rename we have to rename to third name, then move, then rename to final target
performRenameWithConflicts(oldParentFile);
return myCurrent;
}
}
myCurrent.rename(PatchApplier.class, myNewName);
}
if (needMove) {
myCurrent.move(PatchApplier.class, myNewParent);
}
return myCurrent;
}
private void performRenameWithConflicts(@NotNull File oldParent) throws IOException {
File tmpFileWithUniqueName = FileUtil.createTempFile(oldParent, "tempFileToMove", null, false);
File newParentFile = VfsUtilCore.virtualToIoFile(myNewParent);
File destFile = new File(newParentFile, tmpFileWithUniqueName.getName());
while (destFile.exists()) {
destFile = new File(newParentFile,
FileUtil.createTempFile(oldParent, FileUtil.getNameWithoutExtension(destFile.getName()), null, false)
.getName());
}
myCurrent.rename(PatchApplier.class, destFile.getName());
myCurrent.move(PatchApplier.class, myNewParent);
myCurrent.rename(PatchApplier.class, myNewName);
}
}
private static class DelayedPrecheckContext {
private final Map<FilePath, FilePatch> mySkipDeleted;
private final Map<FilePath, FilePatch> myOverrideExisting;
private final List<FilePath> myOverridenPaths;
private final Project myProject;
private DelayedPrecheckContext(final Project project) {
myProject = project;
myOverrideExisting = new HashMap<>();
mySkipDeleted = new HashMap<>();
myOverridenPaths = new LinkedList<>();
}
public void addSkip(final FilePath path, final FilePatch filePatch) {
mySkipDeleted.put(path, filePatch);
}
public void addOverrideExisting(final FilePatch patch, final FilePath filePath) {
if (! myOverrideExisting.containsKey(filePath)) {
myOverrideExisting.put(filePath, patch);
}
}
// returns those to be skipped
public Collection<FilePatch> doDelayed() {
final List<FilePatch> result = new LinkedList<>();
if (! myOverrideExisting.isEmpty()) {
final String title = "Overwrite Existing Files";
List<FilePath> files = new ArrayList<>(myOverrideExisting.keySet());
Collection<FilePath> selected = AbstractVcsHelper.getInstance(myProject).selectFilePathsToProcess(
files, title,
"\nThe following files should be created by patch, but they already exist.\nDo you want to overwrite them?\n", title,
"The following file should be created by patch, but it already exists.\nDo you want to overwrite it?\n{0}",
VcsShowConfirmationOption.STATIC_SHOW_CONFIRMATION,
"Overwrite", "Cancel");
if (selected != null) {
for (FilePath path : selected) {
myOverrideExisting.remove(path);
}
}
result.addAll(myOverrideExisting.values());
if (selected != null) {
myOverridenPaths.addAll(selected);
}
}
result.addAll(mySkipDeleted.values());
return result;
}
public List<FilePath> getOverridenPaths() {
return myOverridenPaths;
}
public Collection<FilePath> getAlreadyDeletedPaths() {
return mySkipDeleted.keySet();
}
}
public void setIgnoreContentRootsCheck(boolean ignoreContentRootsCheck) {
myIgnoreContentRootsCheck = ignoreContentRootsCheck;
}
public static class PatchAndFile {
private final VirtualFile myFile;
private final ApplyFilePatchBase<?> myPatch;
public PatchAndFile(VirtualFile file, ApplyFilePatchBase<?> patch) {
myFile = file;
myPatch = patch;
}
public VirtualFile getFile() {
return myFile;
}
public ApplyFilePatchBase<?> getApplyPatch() {
return myPatch;
}
}
}
| goodwinnk/intellij-community | platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/PathsVerifier.java | Java | apache-2.0 | 23,092 |
package com.therabbitmage.android.beacon.network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.message.BasicHeader;
import android.net.Uri;
import android.util.Log;
import com.therabbitmage.android.beacon.entities.google.urlshortener.Url;
public final class URLShortenerAPI {
private static final String TAG = URLShortenerAPI.class.getSimpleName();
private static final String BASE_URL = "https://www.googleapis.com/urlshortener/v1/url";
public static NetworkResponse urlShorten(String url) throws IOException, URISyntaxException{
android.net.Uri.Builder uriBuilder = Uri.parse(BASE_URL).buildUpon();
String uri = uriBuilder.build().toString();
Header[] headers = new Header[1];
headers[0] = new BasicHeader(ApacheNetworkUtils.HEADER_CONTENT_TYPE, ApacheNetworkUtils.TYPE_JSON);
ApacheNetworkUtils.getAndroidInstance(ApacheNetworkUtils.sUserAgent, false);
HttpResponse response = ApacheNetworkUtils.post(
uri,
ApacheNetworkUtils.getDefaultApacheHeaders(),
new Url(url).toJson());
ApacheNetworkUtils.toStringResponseHeaders(response.getAllHeaders());
ApacheNetworkUtils.toStringStatusLine(response.getStatusLine());
HttpEntity entity = response.getEntity();
NetworkResponse networkResponse = new NetworkResponse();
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
networkResponse.setError(0);
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
StringBuilder stringBuilder = new StringBuilder();
String output = new String();
while((output = br.readLine()) != null){
stringBuilder.append(output);
}
br.close();
Log.i(TAG, "Body: " + stringBuilder.toString());
networkResponse.setUrl(Url.fromJson(stringBuilder.toString()));
} else {
networkResponse.setError(1);
}
return networkResponse;
}
}
| GregSaintJean/Beacon | src/com/therabbitmage/android/beacon/network/URLShortenerAPI.java | Java | apache-2.0 | 2,158 |
#include "common/common/version.h"
std::string VersionInfo::version() {
return fmt::format("{}/{}", GIT_SHA.substr(0, 6),
#ifdef NDEBUG
"RELEASE"
#else
"DEBUG"
#endif
);
}
| timperrett/envoy | source/common/common/version.cc | C++ | apache-2.0 | 238 |
package org.apache.hadoop.hive.kafka.camus;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.UTF8;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
/**
* The key for the mapreduce job to pull kafka. Contains offsets and the
* checksum.
*/
public class KafkaKey implements WritableComparable<KafkaKey>, IKafkaKey {
public static final Text SERVER = new Text("server");
public static final Text SERVICE = new Text("service");
public static KafkaKey DUMMY_KEY = new KafkaKey();
private String leaderId = "";
private int partition = 0;
private long beginOffset = 0;
private long offset = 0;
private long checksum = 0;
private String topic = "";
private long time = 0;
private String server = "";
private String service = "";
private MapWritable partitionMap = new MapWritable();
/**
* dummy empty constructor
*/
public KafkaKey() {
this("dummy", "0", 0, 0, 0, 0);
}
public KafkaKey(KafkaKey other) {
this.partition = other.partition;
this.beginOffset = other.beginOffset;
this.offset = other.offset;
this.checksum = other.checksum;
this.topic = other.topic;
this.time = other.time;
this.server = other.server;
this.service = other.service;
this.partitionMap = new MapWritable(other.partitionMap);
}
public KafkaKey(String topic, String leaderId, int partition) {
this.set(topic, leaderId, partition, 0, 0, 0);
}
public KafkaKey(String topic, String leaderId, int partition, long beginOffset, long offset) {
this.set(topic, leaderId, partition, beginOffset, offset, 0);
}
public KafkaKey(String topic, String leaderId, int partition, long beginOffset, long offset, long checksum) {
this.set(topic, leaderId, partition, beginOffset, offset, checksum);
}
public void set(String topic, String leaderId, int partition, long beginOffset, long offset, long checksum) {
this.leaderId = leaderId;
this.partition = partition;
this.beginOffset = beginOffset;
this.offset = offset;
this.checksum = checksum;
this.topic = topic;
this.time = System.currentTimeMillis(); // if event can't be decoded,
// this time will be used for
// debugging.
}
public void clear() {
leaderId = "";
partition = 0;
beginOffset = 0;
offset = 0;
checksum = 0;
topic = "";
time = 0;
server = "";
service = "";
partitionMap = new MapWritable();
}
public String getServer() {
return partitionMap.get(SERVER).toString();
}
public void setServer(String newServer) {
partitionMap.put(SERVER, new Text(newServer));
}
public String getService() {
return partitionMap.get(SERVICE).toString();
}
public void setService(String newService) {
partitionMap.put(SERVICE, new Text(newService));
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getTopic() {
return topic;
}
public String getLeaderId() {
return leaderId;
}
public int getPartition() {
return this.partition;
}
public long getBeginOffset() {
return this.beginOffset;
}
public void setOffset(long offset) {
this.offset = offset;
}
public long getOffset() {
return this.offset;
}
public long getChecksum() {
return this.checksum;
}
@Override
public long getMessageSize() {
Text key = new Text("message.size");
if (this.partitionMap.containsKey(key))
return ((LongWritable) this.partitionMap.get(key)).get();
else
return 1024; //default estimated size
}
public void setMessageSize(long messageSize) {
Text key = new Text("message.size");
put(key, new LongWritable(messageSize));
}
public void put(Writable key, Writable value) {
this.partitionMap.put(key, value);
}
public void addAllPartitionMap(MapWritable partitionMap) {
this.partitionMap.putAll(partitionMap);
}
public MapWritable getPartitionMap() {
return partitionMap;
}
@Override
public void readFields(DataInput in) throws IOException {
this.leaderId = UTF8.readString(in);
this.partition = in.readInt();
this.beginOffset = in.readLong();
this.offset = in.readLong();
this.checksum = in.readLong();
this.topic = in.readUTF();
this.time = in.readLong();
this.server = in.readUTF(); // left for legacy
this.service = in.readUTF(); // left for legacy
this.partitionMap = new MapWritable();
try {
this.partitionMap.readFields(in);
} catch (IOException e) {
this.setServer(this.server);
this.setService(this.service);
}
}
@Override
public void write(DataOutput out) throws IOException {
UTF8.writeString(out, this.leaderId);
out.writeInt(this.partition);
out.writeLong(this.beginOffset);
out.writeLong(this.offset);
out.writeLong(this.checksum);
out.writeUTF(this.topic);
out.writeLong(this.time);
out.writeUTF(this.server); // left for legacy
out.writeUTF(this.service); // left for legacy
this.partitionMap.write(out);
}
@Override
public int compareTo(KafkaKey o) {
if (partition != o.partition) {
return partition = o.partition;
} else {
if (offset > o.offset) {
return 1;
} else if (offset < o.offset) {
return -1;
} else {
if (checksum > o.checksum) {
return 1;
} else if (checksum < o.checksum) {
return -1;
} else {
return 0;
}
}
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("topic=");
builder.append(topic);
builder.append(" partition=");
builder.append(partition);
builder.append("leaderId=");
builder.append(leaderId);
builder.append(" server=");
builder.append(server);
builder.append(" service=");
builder.append(service);
builder.append(" beginOffset=");
builder.append(beginOffset);
builder.append(" offset=");
builder.append(offset);
builder.append(" msgSize=");
builder.append(getMessageSize());
builder.append(" server=");
builder.append(server);
builder.append(" checksum=");
builder.append(checksum);
builder.append(" time=");
builder.append(time);
for (Map.Entry<Writable, Writable> e : partitionMap.entrySet()) {
builder.append(" " + e.getKey() + "=");
builder.append(e.getValue().toString());
}
return builder.toString();
}
}
| HiveKa/HiveKa | src/main/java/org/apache/hadoop/hive/kafka/camus/KafkaKey.java | Java | apache-2.0 | 6,733 |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.jstestdriver.output;
/**
* Escapes and formats a filename.
*
* @author Cory Smith (corbinrsmith@gmail.com)
*/
public class FileNameFormatter {
public String format(String path, String format) {
String escaped = path
.replace('/', 'a')
.replace('\\', 'a')
.replace(">", "a")
.replace(":", "a")
.replace(":", "a")
.replace(";", "a")
.replace("+", "a")
.replace(",", "a")
.replace("<", "a")
.replace("?", "a")
.replace("*", "a")
.replace(" ", "a");
return String.format(format, escaped.length() > 200 ? escaped.substring(0, 200) : escaped);
}
}
| BladeRunnerJS/brjs-JsTestDriver | JsTestDriver/src/com/google/jstestdriver/output/FileNameFormatter.java | Java | apache-2.0 | 1,271 |
/**
* Copyright 2014 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.wallet;
import com.google.bitcoin.crypto.*;
import com.google.bitcoin.store.UnreadableWalletException;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import org.bitcoinj.wallet.Protos;
import org.spongycastle.crypto.params.KeyParameter;
import javax.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.List;
import static com.google.bitcoin.core.Utils.HEX;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* Holds the seed bytes for the BIP32 deterministic wallet algorithm, inside a
* {@link com.google.bitcoin.wallet.DeterministicKeyChain}. The purpose of this wrapper is to simplify the encryption
* code.
*/
public class DeterministicSeed implements EncryptableItem {
// It would take more than 10^12 years to brute-force a 128 bit seed using $1B worth of computing equipment.
public static final int DEFAULT_SEED_ENTROPY_BITS = 128;
public static final int MAX_SEED_ENTROPY_BITS = 512;
@Nullable private final byte[] seed;
@Nullable private List<String> mnemonicCode;
@Nullable private EncryptedData encryptedMnemonicCode;
private final long creationTimeSeconds;
public DeterministicSeed(String mnemonicCode, String passphrase, long creationTimeSeconds) throws UnreadableWalletException {
this(decodeMnemonicCode(mnemonicCode), passphrase, creationTimeSeconds);
}
public DeterministicSeed(byte[] seed, List<String> mnemonic, long creationTimeSeconds) {
this.seed = checkNotNull(seed);
this.mnemonicCode = checkNotNull(mnemonic);
this.encryptedMnemonicCode = null;
this.creationTimeSeconds = creationTimeSeconds;
}
public DeterministicSeed(EncryptedData encryptedMnemonic, long creationTimeSeconds) {
this.seed = null;
this.mnemonicCode = null;
this.encryptedMnemonicCode = checkNotNull(encryptedMnemonic);
this.creationTimeSeconds = creationTimeSeconds;
}
/**
* Constructs a seed from a BIP 39 mnemonic code. See {@link com.google.bitcoin.crypto.MnemonicCode} for more
* details on this scheme.
* @param mnemonicCode A list of words.
* @param passphrase A user supplied passphrase, or an empty string if there is no passphrase
* @param creationTimeSeconds When the seed was originally created, UNIX time.
*/
public DeterministicSeed(List<String> mnemonicCode, String passphrase, long creationTimeSeconds) {
this(MnemonicCode.toSeed(mnemonicCode, passphrase), mnemonicCode, creationTimeSeconds);
}
/**
* Constructs a seed from a BIP 39 mnemonic code. See {@link com.google.bitcoin.crypto.MnemonicCode} for more
* details on this scheme.
* @param random Entropy source
* @param bits number of bits, must be divisible by 32
* @param passphrase A user supplied passphrase, or an empty string if there is no passphrase
* @param creationTimeSeconds When the seed was originally created, UNIX time.
*/
public DeterministicSeed(SecureRandom random, int bits, String passphrase, long creationTimeSeconds) {
this(getEntropy(random, bits), passphrase, creationTimeSeconds);
}
/**
* Constructs a seed from a BIP 39 mnemonic code. See {@link com.google.bitcoin.crypto.MnemonicCode} for more
* details on this scheme.
* @param entropy entropy bits, length must be divisible by 32
* @param passphrase A user supplied passphrase, or an empty string if there is no passphrase
* @param creationTimeSeconds When the seed was originally created, UNIX time.
*/
public DeterministicSeed(byte[] entropy, String passphrase, long creationTimeSeconds) {
Preconditions.checkArgument(entropy.length % 4 == 0, "entropy size in bits not divisible by 32");
Preconditions.checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, "entropy size too small");
try {
this.mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(entropy);
} catch (MnemonicException.MnemonicLengthException e) {
// cannot happen
throw new RuntimeException(e);
}
this.seed = MnemonicCode.toSeed(mnemonicCode, passphrase);
this.encryptedMnemonicCode = null;
this.creationTimeSeconds = creationTimeSeconds;
}
private static byte[] getEntropy(SecureRandom random, int bits) {
Preconditions.checkArgument(bits <= MAX_SEED_ENTROPY_BITS, "requested entropy size too large");
byte[] seed = new byte[bits / 8];
random.nextBytes(seed);
return seed;
}
@Override
public boolean isEncrypted() {
checkState(mnemonicCode != null || encryptedMnemonicCode != null);
return encryptedMnemonicCode != null;
}
@Override
public String toString() {
if (isEncrypted())
return "DeterministicSeed [encrypted]";
else
return "DeterministicSeed " + toHexString() +
((mnemonicCode != null) ? " " + Joiner.on(" ").join(mnemonicCode) : "");
}
/** Returns the seed as hex or null if encrypted. */
@Nullable
public String toHexString() {
if (seed != null)
return HEX.encode(seed);
else
return null;
}
@Nullable
@Override
public byte[] getSecretBytes() {
return getMnemonicAsBytes();
}
@Nullable
public byte[] getSeedBytes() {
return seed;
}
@Nullable
@Override
public EncryptedData getEncryptedData() {
return encryptedMnemonicCode;
}
@Override
public Protos.Wallet.EncryptionType getEncryptionType() {
return Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES;
}
@Override
public long getCreationTimeSeconds() {
return creationTimeSeconds;
}
public DeterministicSeed encrypt(KeyCrypter keyCrypter, KeyParameter aesKey) {
checkState(encryptedMnemonicCode == null, "Trying to encrypt seed twice");
checkState(mnemonicCode != null, "Mnemonic missing so cannot encrypt");
EncryptedData mnemonic = keyCrypter.encrypt(getMnemonicAsBytes(), aesKey);
return new DeterministicSeed(mnemonic, creationTimeSeconds);
}
private byte[] getMnemonicAsBytes() {
return Joiner.on(" ").join(mnemonicCode).getBytes(Charsets.UTF_8);
}
public DeterministicSeed decrypt(KeyCrypter crypter, String passphrase, KeyParameter aesKey) {
checkState(isEncrypted());
checkNotNull(encryptedMnemonicCode);
List<String> mnemonic = null;
try {
mnemonic = decodeMnemonicCode(crypter.decrypt(encryptedMnemonicCode, aesKey));
} catch (UnreadableWalletException e) {
// TODO what is the best way to handle this exception?
throw new RuntimeException(e);
}
return new DeterministicSeed(mnemonic, passphrase, creationTimeSeconds);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeterministicSeed seed = (DeterministicSeed) o;
if (creationTimeSeconds != seed.creationTimeSeconds) return false;
if (encryptedMnemonicCode != null) {
if (seed.encryptedMnemonicCode == null) return false;
if (!encryptedMnemonicCode.equals(seed.encryptedMnemonicCode)) return false;
} else {
if (!mnemonicCode.equals(seed.mnemonicCode)) return false;
}
return true;
}
@Override
public int hashCode() {
int result = encryptedMnemonicCode != null ? encryptedMnemonicCode.hashCode() : mnemonicCode.hashCode();
result = 31 * result + (int) (creationTimeSeconds ^ (creationTimeSeconds >>> 32));
return result;
}
/**
* Check if our mnemonic is a valid mnemonic phrase for our word list.
* Does nothing if we are encrypted.
*
* @throws com.google.bitcoin.crypto.MnemonicException if check fails
*/
public void check() throws MnemonicException {
if (mnemonicCode != null)
MnemonicCode.INSTANCE.check(mnemonicCode);
}
byte[] getEntropyBytes() throws MnemonicException {
return MnemonicCode.INSTANCE.toEntropy(mnemonicCode);
}
/** Get the mnemonic code, or null if unknown. */
@Nullable
public List<String> getMnemonicCode() {
return mnemonicCode;
}
private static List<String> decodeMnemonicCode(byte[] mnemonicCode) throws UnreadableWalletException {
try {
return Splitter.on(" ").splitToList(new String(mnemonicCode, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new UnreadableWalletException(e.toString());
}
}
private static List<String> decodeMnemonicCode(String mnemonicCode) {
return Splitter.on(" ").splitToList(mnemonicCode);
}
}
| troggy/bitcoinj | core/src/main/java/com/google/bitcoin/wallet/DeterministicSeed.java | Java | apache-2.0 | 9,791 |
using ClassLibrary;
using Pokemon_IMIE.Model;
using Pokemon_IMIE.usercontrols;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace Pokemon_IMIE.usercontrols
{
public sealed partial class PokemonStatus : BaseUserControl
{
private Model.Pokemon pokemon;
public Model.Pokemon Pokemon
{
get { return pokemon; }
set
{
pokemon = value;
base.OnPropertyChanged("Pokemon");
}
}
public PokemonStatus()
{
this.InitializeComponent();
base.DataContext = this;
}
}
}
| clementhouillere/Pokemon_IMIE | app/Pokemon_IMIE/Pokemon_IMIE/usercontrols/PokemonStatus.xaml.cs | C# | apache-2.0 | 1,107 |
#coding=utf-8
from django.db import models
from django.contrib.auth.models import User
class Activity(models.Model):
owner = models.ForeignKey(User, null=False)
text = models.CharField(max_length=20, unique=True)
class Dessert(models.Model):
activity = models.ForeignKey(Activity, null=False)
description = models.TextField()
photo = models.ImageField()
| Moonshile/goondream | src/desserts/models.py | Python | apache-2.0 | 376 |
var angularjs = angular.module('articleDetailModule', ['courseTagServiceModule', 'ngCookies', 'ngVideo']);
angularjs.controller('ArticleDetailController', ['$rootScope', '$scope',
'$http', '$stateParams', '$state', '$location',
'CourseTagService', '$sce', '$cookies', '$httpParamSerializer', 'video', '$route',
function($rootScope, $scope, $http, $stateParams,
$state, $location, courseTagSrv, $sce, $cookies, $httpParamSerializer,
video, $route) {
if ($stateParams.courseId === undefined) {
$state.go('home');
}
var token = $location.search().token;
if (token !== undefined) {
console.log('set token on cookie');
$cookies.put('access_token', token);
}
$scope.showShare = false;
$scope.shareImg = "img/share_400_400_2.png";
$scope.courseUrl = $location.absUrl();
console.log('location=', $scope.courseUrl);
var util = new DomainNameUtil($location);
$scope.originUrl = window.location.href;
console.log('get access token:', $cookies.get('access_token'));
$scope.favoriteCls = 'fontawesome-heart-empty';
$scope.favoriteText = '收藏';
$http.get(util.getBackendServiceUrl() +
'/course/proposal/' + $stateParams.courseId, {
headers: {
'access_token': $cookies.get('access_token')
}
}).
success(function(e) {
console.log('get course ', e);
$scope.course = e;
$rootScope.title = e.name;
var $body = $('body');
var $iframe = $('<iframe src="/favicon.ico"></iframe>');
$iframe.on('load', function() {
setTimeout(function() {
$iframe.off('load').remove();
}, 0);
}).appendTo($body);
$scope.course.videoUrl = $sce.trustAsResourceUrl($scope.course.videoUrl);
document.getElementById('article_content').innerHTML = $scope.course.content;
// video.addSource('mp4',$scope.course.videoUrl);
setFavoriteDom();
configJSAPI();
}).error(function(e) {
});
$http.get(util.getBackendServiceUrl() +
'/course/proposal/query?number=3&ignore_course_id=' + $stateParams.courseId)
.success(function(e) {
console.log('get related courses ', e);
$scope.relatedCourses = e;
}).error(function(e) {
});
courseTagSrv.getCourseTags().then(function(e) {
$scope.courseTags = e;
});
$scope.background = function(course) {
return {
'background-image': 'url(' + course.titleImageUrl + ')',
'background-size': '100%'
};
}
$scope.goToCourseTag = function(tag, $event) {
console.log('go to course tag');
$state.go('course_tags', {
courseTagId: tag.id,
courseName: tag.name
});
$event.stopPropagation();
}
$scope.share = function() {
console.log('share');
$scope.showShare = true;
// var ret = recordShareFavorite('SHARE');
// ret.success(function(e){
// });
}
$scope.favorite = function() {
console.log('favorite');
if ($cookies.get('access_token') === undefined) {
var redirect = encodeURI($scope.courseUrl).replace('#', '%23');
console.log('redirect=', encodeURI($scope.courseUrl).replace('#', '%23'));
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfe34c2ab5b5c5813&redirect_uri=http%3a%2f%2fwww.imzao.com%2feducation%2fzaozao%2fwechat%2flogin&response_type=code&scope=snsapi_userinfo&state=WECHAT_SERVICE-' + redirect + '#wechat_redirect';
return;
}
var promise = recordShareFavorite('FAVORITE');
promise.success(function(e) {
console.log('favorite success ', e);
$scope.course.favorited = !$scope.course.favorited;
setFavoriteDom();
}).error(function(e) {
console.log('share failed');
});
}
function setFavoriteDom() {
if ($scope.course.favorited === true) {
$scope.favoriteCls = 'fontawesome-heart';
$scope.favoriteText = '已收藏';
} else {
$scope.favoriteCls = 'fontawesome-heart-empty';
$scope.favoriteText = '收藏';
}
}
$scope.hideShare = function() {
$scope.showShare = false;
}
$scope.showPlayButton = true;
$scope.showVideo = false;
$scope.playVideo = function(e) {
console.log('course video,', $("#course_video"));
$("#course_video")[0].play();
}
document.getElementById('course_video').addEventListener('webkitendfullscreen', function(e) {
// handle end full screen
console.log('webkitendfullscreen');
$scope.showVideo = false;
$scope.showPlayButton = true;
$scope.$apply();
});
document.getElementById('course_video').addEventListener('webkitenterfullscreen', function(e) {
// handle end full screen
console.log('webkitenterfullscreen');
$scope.showVideo = true;
$scope.$apply();
});
// $scope.videoEnded = function(e) {
// console.log('video ended ');
// $scope.showPlayButton = true;
// }
// $scope.videoPaused = function(e) {
// console.log('video paused ');
// $scope.showPlayButton = true;
// }
function configJSAPI() {
console.log('js api config:', $scope.courseUrl);
$http.get(util.getBackendServiceUrl() + '/wechat/jsapi?url=' + $scope.courseUrl.split('#')[0].replace('&', '%26'))
.success(function(e) {
console.log(e);
var signature = e;
wx.config({
debug: false,
appId: e.appid,
timestamp: e.timestamp,
nonceStr: e.noncestr,
signature: e.signature,
jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
});
wx.ready(function() {
console.log('wx ready');
});
wx.error(function(res) {
console.log('wx error');
});
wx.onMenuShareTimeline({
title: $scope.course.name,
link: $scope.courseUrl,
imgUrl: encodeURI($scope.course.titleImageUrl),
success: function() {
console.log('share success');
scope.showShare = false;
recordShareFavorite('SHARE');
},
cancel: function() {
console.log('cancel share');
scope.showShare = false;
}
});
var shareDesc = '';
console.log('share desc:', $scope.course.introduction);
if ($scope.course.introduction !== null && $scope.course.introduction !== 'undefined') {
shareDesc = $scope.course.introduction;
}
wx.onMenuShareAppMessage({
title: $scope.course.name, // 分享标题
desc: shareDesc, // 分享描述
link: $scope.courseUrl, // 分享链接
imgUrl: encodeURI($scope.course.titleImageUrl), // 分享图标
// 分享类型,music、video或link,不填默认为link
// 如果type是music或video,则要提供数据链接,默认为空
success: function(res) {
// 用户确认分享后执行的回调函数
console.log('share success');
recordShareFavorite('SHARE');
scope.showShare = false;
},
cancel: function(res) {
// 用户取消分享后执行的回调函数
console.log('cancel share');
scope.showShare = false;
},
fail: function(res) {
}
});
}).error(function(e) {
});
}
function recordShareFavorite(activity) {
var link = util.getBackendServiceUrl() + '/course/interactive';
var req = {
method: 'POST',
url: link,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'access_token': $cookies.get('access_token')
//'Content-Type': 'multipart/form-data; charset=utf-8;'
},
data: $httpParamSerializer({
course_id: $scope.course.id,
flag: activity
})
};
return $http(req);
}
}
]);
angularjs.directive('videoLoader', function() {
return function(scope, element, attrs) {
scope.$watch(attrs.videoLoader, function() {
console.log('element:', element);
$("#course_video").bind('ended', function() {
console.log('video ended.');
// element.removeAttr('controls');
scope.showPlayButton = true;
scope.showVideo = false;
scope.$apply();
// $(this).unbind('ended');
// if (!this.hasPlayed) {
// return;
// }
});
$("#course_video").bind('pause', function() {
console.log('video paused.');
scope.showPlayButton = false;
scope.showVideo = true;
// element.attr('controls',true);
scope.$apply();
// $(this).unbind('paused');
// if (!this.hasPlayed) {
// return;
// }
});
$("#course_video").bind('play', function() {
console.log('video played.');
scope.showPlayButton = false;
scope.showVideo = true;
// element.attr('controls',true);
scope.$apply();
// $(this).unbind('played');
// if (!this.hasPlayed) {
// return;
// }
});
$("#course_video").bind('webkitfullscreenchange mozfullscreenchange fullscreenchange',
function(event) {
console.log('full screen ', event);
var state = document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement;
if (state !== undefined) {
scope.showVideo = true;
} else {
scope.showVideo = false;
}
scope.$apply();
});
});
}
});
| c2611261/zaozao2 | public/js/article_detail.js | JavaScript | apache-2.0 | 8,955 |
import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
| TheSolvingMachine/kangrouter-py | kangrouter.py | Python | apache-2.0 | 3,278 |
/* Copyright 2008, 2009, 2010 by the Oxford University Computing Laboratory
This file is part of HermiT.
HermiT is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
HermiT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with HermiT. If not, see <http://www.gnu.org/licenses/>.
*/
package org.semanticweb.HermiT.datatypes.owlreal;
import java.math.BigDecimal;
import java.math.BigInteger;
public enum NumberRange {
NOTHING, INTEGER, DECIMAL, RATIONAL, REAL;
public boolean isDense() {
return ordinal() >= DECIMAL.ordinal();
}
public static NumberRange intersection(NumberRange it1, NumberRange it2) {
int minOrdinal = Math.min(it1.ordinal(), it2.ordinal());
return values()[minOrdinal];
}
public static NumberRange union(NumberRange it1, NumberRange it2) {
int maxOrdinal = Math.max(it1.ordinal(), it2.ordinal());
return values()[maxOrdinal];
}
public static boolean isSubsetOf(NumberRange subset, NumberRange superset) {
return subset.ordinal() <= superset.ordinal();
}
public static NumberRange getMostSpecificRange(Number n) {
if (n instanceof Integer || n instanceof Long || n instanceof BigInteger)
return INTEGER;
else if (n instanceof BigDecimal)
return DECIMAL;
else if (n instanceof BigRational)
return RATIONAL;
else
throw new IllegalArgumentException();
}
} | CPoirot3/OWL-Reasoner | project/src/org/semanticweb/HermiT/datatypes/owlreal/NumberRange.java | Java | apache-2.0 | 1,986 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lookoutequipment.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.lookoutequipment.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateDatasetResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateDatasetResultJsonUnmarshaller implements Unmarshaller<CreateDatasetResult, JsonUnmarshallerContext> {
public CreateDatasetResult unmarshall(JsonUnmarshallerContext context) throws Exception {
CreateDatasetResult createDatasetResult = new CreateDatasetResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return createDatasetResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("DatasetName", targetDepth)) {
context.nextToken();
createDatasetResult.setDatasetName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DatasetArn", targetDepth)) {
context.nextToken();
createDatasetResult.setDatasetArn(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Status", targetDepth)) {
context.nextToken();
createDatasetResult.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return createDatasetResult;
}
private static CreateDatasetResultJsonUnmarshaller instance;
public static CreateDatasetResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateDatasetResultJsonUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-lookoutequipment/src/main/java/com/amazonaws/services/lookoutequipment/model/transform/CreateDatasetResultJsonUnmarshaller.java | Java | apache-2.0 | 3,307 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Recipe.cs" company="Dapr Labs">
// Copyright 2014, Dapr Labs Pty. Ltd.
// </copyright>
// <summary>
// Describes a recipe.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ForkTip.Models
{
using System;
using System.Collections.Generic;
/// <summary>
/// Describes a recipe.
/// </summary>
[Serializable]
public class Recipe
{
/// <summary>
/// Gets or sets the id.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the creator's name.
/// </summary>
public string Author { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the ingredients.
/// </summary>
public List<string> Ingredients { get; set; }
/// <summary>
/// Gets or sets the directions.
/// </summary>
public List<string> Directions { get; set; }
}
} | daprlabs/ForkTip | ForkTip/Models/Recipe.cs | C# | apache-2.0 | 1,399 |
package com.designpattern.structural.facade;
public class Facade {
SystemOne system1 = new SystemOne();
SystemTwo system2 = new SystemTwo();
SystemThree system3 = new SystemThree();
SystemFour system4 = new SystemFour();
public void facadeFunction1() {
System.out.println("---- facade function 1");
system1.methodOne();
system3.methodThree();
system4.methodFour();
System.out.println("---- facade function 1 end");
}
public void facadeFunction2() {
System.out.println("---- facade function 2");
system2.methodTwo();
system3.methodThree();
System.out.println("---- facade function 2 end");
}
}
| tyybjcc/Design-Patterns-in-java | DesignPatterns/src/com/designpattern/structural/facade/Facade.java | Java | apache-2.0 | 649 |
<?php
namespace Slime;
use Illuminate\Database\Eloquent\Model;
class Persona extends Model
{
protected $table = "Persona";
protected $fillable = ['nombre','apellido','Cargo_id'];
}
| rots87/Slime | SLIME/app/Persona.php | PHP | apache-2.0 | 192 |
/*
* Copyright (C) 2013 @JamesMontemagno http://www.montemagno.com http://www.refractored.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Runtime;
using Android.Util;
using Android.Widget;
using MyCompany.Visitors.Client.Droid;
namespace com.refractored.controls
{
public class RobotoTextView : TextView
{
private const int RobotoThin = 0;
private const int RobotoThinItalic = 1;
private const int RobotoLight = 2;
private const int RobotoLightItalic = 3;
private const int RobotoRegular = 4;
private const int RobotoItalic = 5;
private const int RobotoMedium = 6;
private const int RobotoMediumItalic = 7;
private const int RobotoBold = 8;
private const int RobotoBoldItalic = 9;
private const int RobotoBlack = 10;
private const int RobotoBlackItalic = 11;
private const int RobotoCondensed = 12;
private const int RobotoCondensedItalic = 13;
private const int RobotoCondensedBold = 14;
private const int RobotoCondensedBoldItalic = 15;
private TypefaceStyle m_Style = TypefaceStyle.Normal;
private static readonly Dictionary<int, Typeface> Typefaces = new Dictionary<int, Typeface>(16);
public RobotoTextView(Context context) :
base(context)
{
}
protected RobotoTextView(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
public RobotoTextView(Context context, IAttributeSet attrs) :
base(context, attrs)
{
this.Initialize(context, attrs);
}
public RobotoTextView(Context context, IAttributeSet attrs, int defStyle) :
base(context, attrs, defStyle)
{
this.Initialize(context, attrs);
}
private void Initialize(Context context, IAttributeSet attrs)
{
try
{
TypedArray values = context.ObtainStyledAttributes(attrs, Resource.Styleable.RobotoTextView);
int typefaceValue = values.GetInt(Resource.Styleable.RobotoTextView_typeface, 4);
values.Recycle();
var font = this.ObtainTypeface(context, typefaceValue);
this.SetTypeface(font, this.m_Style);
}
catch (Exception)
{
}
}
private Typeface ObtainTypeface(Context context, int typefaceValue)
{
try
{
Typeface typeface = null;
if (Typefaces.ContainsKey(typefaceValue))
typeface = Typefaces[typefaceValue];
if (typeface == null)
{
typeface = this.CreateTypeface(context, typefaceValue);
Typefaces.Add(typefaceValue, typeface);
}
return typeface;
}
catch (Exception ex)
{
}
return null;
}
private Typeface CreateTypeface(Context context, int typefaceValue)
{
try
{
Typeface typeface;
switch (typefaceValue)
{
case RobotoThin:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Thin.ttf");
break;
case RobotoThinItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-ThinItalic.ttf");
m_Style = TypefaceStyle.Italic;
break;
case RobotoLight:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Light.ttf");
break;
case RobotoLightItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-LightItalic.ttf");
m_Style = TypefaceStyle.Italic;
break;
case RobotoRegular:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Regular.ttf");
break;
case RobotoItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Italic.ttf");
m_Style = TypefaceStyle.Italic;
break;
case RobotoMedium:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Medium.ttf");
break;
case RobotoMediumItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-MediumItalic.ttf");
m_Style = TypefaceStyle.Italic;
break;
case RobotoBold:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Bold.ttf");
m_Style = TypefaceStyle.Bold;
break;
case RobotoBoldItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BoldItalic.ttf");
m_Style = TypefaceStyle.BoldItalic;
break;
case RobotoBlack:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Black.ttf");
break;
case RobotoBlackItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BlackItalic.ttf");
m_Style = TypefaceStyle.Italic;
break;
case RobotoCondensed:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Condensed.ttf");
break;
case RobotoCondensedItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-CondensedItalic.ttf");
m_Style = TypefaceStyle.Italic;
break;
case RobotoCondensedBold:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BoldCondensed.ttf");
m_Style = TypefaceStyle.Bold;
break;
case RobotoCondensedBoldItalic:
typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BoldCondensedItalic.ttf");
m_Style = TypefaceStyle.BoldItalic;
break;
default:
throw new ArgumentException("Unknown typeface attribute value " + typefaceValue);
}
return typeface;
}
catch (Exception)
{
}
return null;
}
}
} | xamarin/MyCompany | MyCompany.Visitors.Client.Droid/Extensions/RobotoTextView.cs | C# | apache-2.0 | 7,655 |
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Twig_' => array($vendorDir . '/twig/twig/lib'),
'Symfony\\Component\\Icu\\' => array($vendorDir . '/symfony/icu'),
'Symfony\\Bundle\\SwiftmailerBundle' => array($vendorDir . '/symfony/swiftmailer-bundle'),
'Symfony\\Bundle\\MonologBundle' => array($vendorDir . '/symfony/monolog-bundle'),
'Symfony\\Bundle\\AsseticBundle' => array($vendorDir . '/symfony/assetic-bundle'),
'Symfony\\' => array($vendorDir . '/symfony/symfony/src'),
'Sensio\\Bundle\\GeneratorBundle' => array($vendorDir . '/sensio/generator-bundle'),
'Sensio\\Bundle\\FrameworkExtraBundle' => array($vendorDir . '/sensio/framework-extra-bundle'),
'Sensio\\Bundle\\DistributionBundle' => array($vendorDir . '/sensio/distribution-bundle'),
'Psr\\Log\\' => array($vendorDir . '/psr/log'),
'PHPExcel' => array($vendorDir . '/phpoffice/phpexcel/Classes'),
'Gregwar\\CaptchaBundle' => array($vendorDir . '/gregwar/captcha-bundle'),
'Gregwar\\Captcha' => array($vendorDir . '/gregwar/captcha'),
'Doctrine\\ORM\\' => array($vendorDir . '/doctrine/orm/lib'),
'Doctrine\\DBAL\\' => array($vendorDir . '/doctrine/dbal/lib'),
'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib'),
'Doctrine\\Common\\Collections\\' => array($vendorDir . '/doctrine/collections/lib'),
'Doctrine\\Common\\Cache\\' => array($vendorDir . '/doctrine/cache/lib'),
'Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib'),
'Doctrine\\Common\\' => array($vendorDir . '/doctrine/common/lib'),
'Doctrine\\Bundle\\DoctrineBundle' => array($vendorDir . '/doctrine/doctrine-bundle'),
'Assetic' => array($vendorDir . '/kriswallsmith/assetic/src'),
array($baseDir . '/src')
);
| hlkzmy/evaluation-system | vendor/composer/autoload_namespaces.php | PHP | apache-2.0 | 1,967 |
/*
* Copyright 2019 Stephane Nicolas
* Copyright 2019 Daniel Molinero Reguera
*
* 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 toothpick.getInstance;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import toothpick.Scope;
import toothpick.ScopeImpl;
import toothpick.Toothpick;
import toothpick.config.Module;
import toothpick.configuration.Configuration;
import toothpick.configuration.CyclicDependencyException;
import toothpick.data.CyclicFoo;
import toothpick.data.CyclicNamedFoo;
import toothpick.data.IFoo;
import toothpick.locators.NoFactoryFoundException;
/*
* Creates a instance in the simplest possible way
* without any module.
*/
public class CycleCheckTest {
@BeforeClass
public static void setUp() {
Toothpick.setConfiguration(Configuration.forDevelopment());
}
@AfterClass
public static void staticTearDown() {
Toothpick.setConfiguration(Configuration.forProduction());
}
@After
public void tearDown() {
Toothpick.reset();
}
@Test(expected = CyclicDependencyException.class)
public void testSimpleCycleDetection() {
// GIVEN
Scope scope = new ScopeImpl("");
// WHEN
scope.getInstance(CyclicFoo.class);
// THEN
fail("Should throw an exception as a cycle is detected");
}
@Test
public void testCycleDetection_whenSameClass_and_differentName_shouldNotCrash() {
// GIVEN
final CyclicNamedFoo instance1 = new CyclicNamedFoo();
Scope scope = new ScopeImpl("");
scope.installModules(
new Module() {
{
bind(CyclicNamedFoo.class).withName("foo").toInstance(instance1);
}
});
// WHEN
CyclicNamedFoo instance2 = scope.getInstance(CyclicNamedFoo.class);
// THEN
// Should not crashed
assertThat(instance2, notNullValue());
assertThat(instance2.cyclicFoo, sameInstance(instance1));
}
@Test(expected = NoFactoryFoundException.class)
public void testCycleDetection_whenGetInstanceFails_shouldCloseCycle() {
// GIVEN
Scope scope = new ScopeImpl("");
// WHEN
try {
scope.getInstance(IFoo.class);
} catch (NoFactoryFoundException nfe) {
nfe.printStackTrace();
}
scope.getInstance(IFoo.class);
// THEN
fail(
"Should throw NoFactoryFoundException as IFoo does not have any implementation bound."
+ "But It should not throw CyclicDependencyException as it was removed from the stack.");
}
}
| stephanenicolas/toothpick | toothpick-runtime/src/test/java/toothpick/getInstance/CycleCheckTest.java | Java | apache-2.0 | 3,214 |
<?php
function geoip($dbipcsv, $ip){
$csvData = file_get_contents("/lib/".$dbipcsv);
$lines = explode(PHP_EOL, $csvData);
$rangeArray = array();
foreach ($lines as $line) {
$rangeArray[] = str_getcsv($line);
}
$input = $ip;
$array_input = explode(".", $input);
foreach($rangeArray as $current)
{
$array_start = explode(".", $current['0']);
$array_stop = explode(".", $current['1']);
if((int)$array_input[0] >= (int)$array_start[0]){
if((int)$array_input[0] <= (int)$array_stop[0]){
if((int)$array_input[1] >= (int)$array_start[1]){
if((int)$array_input[1] <= (int)$array_stop[1]){
if((int)$array_input[2] >= (int)$array_start[2]){
if((int)$array_input[2] <= (int)$array_stop[2]){
if((int)$array_input[3] >= (int)$array_start[3]){
if((int)$array_input[3] <= (int)$array_stop[3]){
$data = $current[2];
}
}
}
}
}
}
}
}
}
return $data;
}
?> | yeungalan/oauth_project | lib/dbip.php | PHP | apache-2.0 | 959 |
/*
* 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 com.intel.ssg.dcst.panthera.parse.sql.transformer.fb;
import java.util.ArrayList;
import java.util.List;
import org.antlr.runtime.tree.CommonTree;
import com.intel.ssg.dcst.panthera.parse.sql.PantheraExpParser;
import com.intel.ssg.dcst.panthera.parse.sql.SqlXlateException;
import com.intel.ssg.dcst.panthera.parse.sql.SqlXlateUtil;
import com.intel.ssg.dcst.panthera.parse.sql.TranslateContext;
import br.com.porcelli.parser.plsql.PantheraParser_PLSQLParser;
/**
* transform AND to JOIN(by rebuilding left select).<br>
* AndFilterBlock.
*
*/
public class AndFilterBlock extends LogicFilterBlock {
/**
* this must have two children.
*
* @throws SqlXlateException
*/
@Override
public void process(FilterBlockContext fbContext, TranslateContext context)
throws SqlXlateException {
FilterBlock leftFB = this.getChildren().get(0);
leftFB.process(fbContext, context);
fbContext.getQueryStack().peek().setQueryForTransfer(leftFB.getTransformedNode());
fbContext.getQueryStack().peek().setRebuildQueryForTransfer();
FilterBlock rightFB = this.getChildren().get(1);
CommonTree condition = rightFB.getASTNode();
TypeFilterBlock type = fbContext.getTypeStack().peek();
if (rightFB instanceof UnCorrelatedFilterBlock) {
// simple condition
if (type instanceof WhereFilterBlock) {
rebuildWhereCondition(leftFB, condition);
}
if (type instanceof HavingFilterBlock) {
rebuildHavingCondition(leftFB, condition);
}
this.setTransformedNode(leftFB.getTransformedNode());
} else {
rightFB.process(fbContext, context);
this.setTransformedNode(rightFB.getTransformedNode());
}
}
private void rebuildWhereCondition(FilterBlock leftFB, CommonTree condition) {
CommonTree transformedSelect = leftFB.getTransformedNode();
rebuildWhereCond(transformedSelect, condition);
}
private void rebuildWhereCond(CommonTree transformedSelect, CommonTree condition) {
if (transformedSelect.getType() == PantheraParser_PLSQLParser.SUBQUERY) {
for (int i = 0; i < transformedSelect.getChildCount(); i++) {
rebuildWhereCond((CommonTree) transformedSelect.getChild(i), condition);
}
} else if (transformedSelect.getType() == PantheraParser_PLSQLParser.SQL92_RESERVED_SELECT) {
rebuildWhereCondition(transformedSelect, condition);
} else if (transformedSelect.getType() == PantheraParser_PLSQLParser.SQL92_RESERVED_UNION) { // UNION node
rebuildWhereCond((CommonTree) transformedSelect.getChild(0), condition);
}
}
private void rebuildWhereCondition(CommonTree transformedSelect, CommonTree condition) {
CommonTree tableRefElement = (CommonTree) transformedSelect.getChild(0).getChild(0).getChild(0);
CommonTree subQuery = (CommonTree) tableRefElement.getChild(tableRefElement.getChildCount() - 1).getChild(0)
.getChild(0).getChild(0);
List<List<CommonTree>> selects = new ArrayList<List<CommonTree>>();
for (int i = 0; i < subQuery.getChildCount(); i++) {
List<CommonTree> selectLists = new ArrayList<CommonTree>();
FilterBlockUtil.findNode((CommonTree) subQuery.getChild(i),
PantheraExpParser.SELECT_LIST, selectLists);
assert(selectLists != null);
List<CommonTree> oneSelects = new ArrayList<CommonTree>();
for (CommonTree sl:selectLists) {
oneSelects.add((CommonTree) sl.getParent());
}
selects.add(oneSelects);
}
for (List<CommonTree> sels:selects) {
CommonTree sel = sels.get(0);
for (int j = 0; j < sels.size(); j++) {
sel = sels.get(j);
if(sel.getCharPositionInLine() == condition.getAncestor(PantheraParser_PLSQLParser.SQL92_RESERVED_SELECT).getCharPositionInLine()) {
break;
}
}
CommonTree where = (CommonTree) sel
.getFirstChildWithType(PantheraExpParser.SQL92_RESERVED_WHERE);
if (where == null) {
where = FilterBlockUtil.createSqlASTNode(condition, PantheraExpParser.SQL92_RESERVED_WHERE,
"where");
CommonTree group = (CommonTree) sel
.getFirstChildWithType(PantheraExpParser.SQL92_RESERVED_GROUP);
if (group != null) {
int groupIndex = group.getChildIndex();
SqlXlateUtil.addCommonTreeChild(sel, groupIndex, where);
} else {
sel.addChild(where);
}
CommonTree logicExpr = FilterBlockUtil.createSqlASTNode(condition,
PantheraExpParser.LOGIC_EXPR, "LOGIC_EXPR");
where.addChild(logicExpr);
logicExpr.addChild(condition);
} else {
CommonTree logicExpr = (CommonTree) where.getChild(0);
FilterBlockUtil.addConditionToLogicExpr(logicExpr, condition);
}
}
}
private void rebuildHavingCondition(FilterBlock leftFB, CommonTree condition) {
CommonTree transformedSelect = leftFB.getTransformedNode();
rebuildHavingCond(transformedSelect, condition);
}
private void rebuildHavingCond(CommonTree transformedSelect, CommonTree condition) {
if (transformedSelect.getType() == PantheraParser_PLSQLParser.SUBQUERY) {
for (int i = 0; i < transformedSelect.getChildCount(); i++) {
rebuildHavingCond((CommonTree) transformedSelect.getChild(i), condition);
}
} else if (transformedSelect.getType() == PantheraParser_PLSQLParser.SQL92_RESERVED_SELECT) {
rebuildHavingCondition(transformedSelect, condition);
} else if (transformedSelect.getType() == PantheraParser_PLSQLParser.SQL92_RESERVED_UNION) { // UNION node
rebuildHavingCond((CommonTree) transformedSelect.getChild(0), condition);
}
}
private void rebuildHavingCondition(CommonTree transformedSelect, CommonTree condition) {
CommonTree tableRefElement = (CommonTree) transformedSelect.getChild(0).getChild(0).getChild(0);
CommonTree subQuery = (CommonTree) tableRefElement.getChild(tableRefElement.getChildCount() - 1).getChild(0)
.getChild(0).getChild(0);
List<List<CommonTree>> groups = new ArrayList<List<CommonTree>>();
for(int i = 0; i < subQuery.getChildCount(); i++){
List<CommonTree> oneGroups = new ArrayList<CommonTree>();
FilterBlockUtil.findNode((CommonTree) subQuery.getChild(i),
PantheraExpParser.SQL92_RESERVED_GROUP, oneGroups);
assert(oneGroups != null);
groups.add(oneGroups);
}
for(List<CommonTree> grps:groups) {
CommonTree group = grps.get(0);
for (int j = 0; j < grps.size(); j++) {
group = grps.get(j);
if(group.getCharPositionInLine() == condition.getAncestor(PantheraParser_PLSQLParser.SQL92_RESERVED_GROUP).getCharPositionInLine()) {
break;
}
}
CommonTree having = (CommonTree) group
.getFirstChildWithType(PantheraExpParser.SQL92_RESERVED_HAVING);
if (having == null) {
having = FilterBlockUtil.createSqlASTNode(condition, PantheraExpParser.SQL92_RESERVED_HAVING,
"having");
group.addChild(having);
CommonTree logicExpr = FilterBlockUtil.createSqlASTNode(condition,
PantheraExpParser.LOGIC_EXPR, "LOGIC_EXPR");
having.addChild(logicExpr);
logicExpr.addChild(condition);
} else {
CommonTree logicExpr = (CommonTree) having.getChild(0);
FilterBlockUtil.addConditionToLogicExpr(logicExpr, condition);
}
}
}
}
| adrian-wang/project-panthera-skin | src/main/java/com/intel/ssg/dcst/panthera/parse/sql/transformer/fb/AndFilterBlock.java | Java | apache-2.0 | 8,205 |
package io.swagger.client.api;
import com.sun.jersey.api.client.GenericType;
import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.model.CodeSnippet;
import io.swagger.client.model.CodeSnippetList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-11T02:09:38.462Z")
public class DefaultApi {
private ApiClient apiClient;
public DefaultApi() {
this(Configuration.getDefaultApiClient());
}
public DefaultApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Creates a code snippet.
* Creates a code snippet in the specified language.
* @param codeSnippetBody Code snippet object.
* @throws ApiException if fails to make API call
*/
public void snipPost(CodeSnippet codeSnippetBody) throws ApiException {
Object localVarPostBody = codeSnippetBody;
// create path and map variables
String localVarPath = "/snip".replaceAll("\\{format\\}","json");
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
}
/**
* Retrieves the specified code snippet.
* Retrieves the specified code snippet.
* @param codeSnippetUuid Code snippet unique identifier.
* @return CodeSnippet
* @throws ApiException if fails to make API call
*/
public CodeSnippet snipCodeSnippetUuidGet(String codeSnippetUuid) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'codeSnippetUuid' is set
if (codeSnippetUuid == null) {
throw new ApiException(400, "Missing the required parameter 'codeSnippetUuid' when calling snipCodeSnippetUuidGet");
}
// create path and map variables
String localVarPath = "/snip/{code_snippet_uuid}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "code_snippet_uuid" + "\\}", apiClient.escapeString(codeSnippetUuid.toString()));
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
GenericType<CodeSnippet> localVarReturnType = new GenericType<CodeSnippet>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* Updates a code snippet.
* Updates a code snippet changes.
* @param codeSnippetUuid Code snippet unique identifier.
* @param codeSnippetBody Code snippet object.
* @throws ApiException if fails to make API call
*/
public void snipCodeSnippetUuidPut(String codeSnippetUuid, CodeSnippet codeSnippetBody) throws ApiException {
Object localVarPostBody = codeSnippetBody;
// verify the required parameter 'codeSnippetUuid' is set
if (codeSnippetUuid == null) {
throw new ApiException(400, "Missing the required parameter 'codeSnippetUuid' when calling snipCodeSnippetUuidPut");
}
// create path and map variables
String localVarPath = "/snip/{code_snippet_uuid}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "code_snippet_uuid" + "\\}", apiClient.escapeString(codeSnippetUuid.toString()));
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
}
/**
* Deletes the specified code snippet.
* Deletes the specified code snippet.
* @param codeSnippetUuid Code snippet unique identifier.
* @throws ApiException if fails to make API call
*/
public void snipCodeSnippetUuidDelete(String codeSnippetUuid) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'codeSnippetUuid' is set
if (codeSnippetUuid == null) {
throw new ApiException(400, "Missing the required parameter 'codeSnippetUuid' when calling snipCodeSnippetUuidDelete");
}
// create path and map variables
String localVarPath = "/snip/{code_snippet_uuid}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "code_snippet_uuid" + "\\}", apiClient.escapeString(codeSnippetUuid.toString()));
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
}
/**
* Retrieves all code snippets.
*
* @return CodeSnippetList
* @throws ApiException if fails to make API call
*/
public CodeSnippetList snipsGet() throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/snips".replaceAll("\\{format\\}","json");
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
GenericType<CodeSnippetList> localVarReturnType = new GenericType<CodeSnippetList>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
}
| jsodini/CodeSnip | sdk/java/src/main/java/io/swagger/client/api/DefaultApi.java | Java | apache-2.0 | 8,599 |
// Copyright 2016-2022 The Libsacloud 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 icon
import (
"github.com/sacloud/libsacloud/v2/helper/service"
"github.com/sacloud/libsacloud/v2/helper/validate"
"github.com/sacloud/libsacloud/v2/sacloud"
"github.com/sacloud/libsacloud/v2/sacloud/types"
)
type UpdateRequest struct {
ID types.ID `request:"-" validate:"required"`
Name *string `request:",omitempty" validate:"omitempty,min=1"`
Tags *types.Tags `request:",omitempty"`
}
func (req *UpdateRequest) Validate() error {
return validate.Struct(req)
}
func (req *UpdateRequest) ToRequestParameter(current *sacloud.Icon) (*sacloud.IconUpdateRequest, error) {
r := &sacloud.IconUpdateRequest{}
if err := service.RequestConvertTo(current, r); err != nil {
return nil, err
}
if err := service.RequestConvertTo(req, r); err != nil {
return nil, err
}
return r, nil
}
| sacloud/libsacloud | v2/helper/service/icon/update_request.go | GO | apache-2.0 | 1,414 |
/**
* CommonFramework
*
* Copyright (C) 2017 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* 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 com.blackducksoftware.tools.commonframework.standard.protex.report.template;
// TODO: Auto-generated Javadoc
/**
* Pojo representing the second sheet of our test template .
*
* @author akamen
*/
public class TestPojoPageTwo extends TestPojo {
/** The value1page2. */
public String value1page2;
/** The value2page2. */
public String value2page2;
/**
* Gets the value2 page2.
*
* @return the value2 page2
*/
public String getValue2Page2() {
return value2page2;
}
/**
* Sets the value2page2.
*
* @param value2page2
* the new value2page2
*/
public void setValue2page2(String value2page2) {
this.value2page2 = value2page2;
}
/**
* Gets the value1 page2.
*
* @return the value1 page2
*/
public String getValue1Page2() {
return value1page2;
}
/**
* Sets the value1page2.
*
* @param value1page2
* the new value1page2
*/
public void setValue1page2(String value1page2) {
this.value1page2 = value1page2;
}
}
| blackducksoftware/common-framework | src/test/java/com/blackducksoftware/tools/commonframework/standard/protex/report/template/TestPojoPageTwo.java | Java | apache-2.0 | 2,010 |