repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
1690296356/jdk | test/jdk/java/nio/channels/FileChannel/directio/PreadDirect.java | <gh_stars>0
/*
* Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8164900
* @summary Test positional read method of FileChannel with DirectIO
* (use -Dseed=X to set PRNG seed)
* @library .. /test/lib
* @build jdk.test.lib.RandomFactory
* DirectIOTest
* @run main/othervm PreadDirect
* @key randomness
*/
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.file.Files;
import java.nio.file.FileStore;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Random;
import com.sun.nio.file.ExtendedOpenOption;
import jdk.test.lib.RandomFactory;
/**
* Testing FileChannel's positional read method.
*/
public class PreadDirect {
private static PrintStream err = System.err;
private static Random generator = RandomFactory.getRandom();
private static int charsPerGroup = -1;
private static int alignment = -1;
public static void main(String[] args) throws Exception {
if (initTests()) {
genericTest();
testNotAlignedChannelPosition();
testNegativeChannelPosition();
}
}
private static boolean initTests() throws Exception {
Path p = DirectIOTest.createTempFile();
try {
FileStore fs = Files.getFileStore(p);
alignment = (int)fs.getBlockSize();
charsPerGroup = alignment;
} finally {
Files.delete(p);
}
return true;
}
private static void testNegativeChannelPosition() throws Exception {
Path p = DirectIOTest.createTempFile();
try (OutputStream fos = Files.newOutputStream(p)) {
fos.write(new byte[charsPerGroup]);
}
try (FileChannel fc = FileChannel.open(p,
StandardOpenOption.DELETE_ON_CLOSE, ExtendedOpenOption.DIRECT)) {
try {
fc.read(ByteBuffer.allocate(charsPerGroup), -1L);
throw new RuntimeException("Expected exception not thrown");
} catch(IllegalArgumentException e) {
// Correct result
}
}
}
private static void testNotAlignedChannelPosition() throws Exception {
Path p = DirectIOTest.createTempFile();
try (OutputStream fos = Files.newOutputStream(p)) {
fos.write(new byte[charsPerGroup]);
}
try (FileChannel fc = FileChannel.open(p,
StandardOpenOption.DELETE_ON_CLOSE, ExtendedOpenOption.DIRECT)) {
long pos = charsPerGroup - 1;
try {
fc.read(ByteBuffer.allocate(charsPerGroup), pos);
throw new RuntimeException("Expected exception not thrown");
} catch(IOException e) {
if (!e.getMessage().contains("Channel position (" + pos
+ ") is not a multiple of the block size (" + alignment + ")"))
throw new RuntimeException("Read test failed");
}
}
}
private static void genericTest() throws Exception {
StringBuffer sb = new StringBuffer();
sb.setLength(2);
Path p = DirectIOTest.createTempFile();
initTestFile(p);
try (FileChannel fc = FileChannel.open(p,
StandardOpenOption.DELETE_ON_CLOSE, ExtendedOpenOption.DIRECT)) {
ByteBuffer block =
ByteBuffer.allocateDirect(charsPerGroup + alignment - 1)
.alignedSlice(alignment);
for (int x = 0; x < 100; x++) {
block.clear();
long offset = generator.nextInt(100) * charsPerGroup;
long expectedResult = offset / charsPerGroup;
offset = expectedResult * charsPerGroup;
long originalPosition = fc.position();
int read = fc.read(block, offset);
if (read != charsPerGroup)
throw new Exception("Read failed");
long newPosition = fc.position();
for (int i = 0; i < 2; i++) {
byte aByte = block.get(i);
sb.setCharAt(i, (char)aByte);
}
int result = Integer.parseInt(sb.toString());
if (result != expectedResult) {
err.println("I expected "+ expectedResult);
err.println("I got "+ result);
throw new Exception("Read test failed");
}
// Ensure that file pointer position has not changed
if (originalPosition != newPosition)
throw new Exception("File position modified");
}
}
}
private static void initTestFile(Path p) throws Exception {
try (OutputStream fos = Files.newOutputStream(p)) {
try (BufferedWriter awriter
= new BufferedWriter(new OutputStreamWriter(fos, "8859_1"))) {
for (int i = 0; i < 100; i++) {
String number = new Integer(i).toString();
for (int h = 0; h < 2 - number.length(); h++)
awriter.write("0");
awriter.write(""+i);
for (int j = 0; j < (charsPerGroup - 2); j++)
awriter.write("0");
}
awriter.flush();
}
}
}
}
|
PopCap/GameIdea | Engine/Source/Runtime/UMG/Public/Components/TextBlock.h | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "TextBlock.generated.h"
/**
* A simple static text widget.
*
* ● No Children
* ● Text
*/
UCLASS(meta=(DisplayName="Text"))
class UMG_API UTextBlock : public UWidget
{
GENERATED_UCLASS_BODY()
public:
/**
* Sets the color and opacity of the text in this text block
*
* @param InColorAndOpacity The new text color and opacity
*/
UFUNCTION(BlueprintCallable, Category="Appearance")
void SetColorAndOpacity(FSlateColor InColorAndOpacity);
/**
* Sets the opacity of the text in this text block
*
* @param InOpacity The new text opacity
*/
UFUNCTION(BlueprintCallable, Category = "Appearance")
void SetOpacity(float InOpacity);
/**
* Sets the color and opacity of the text drop shadow
* Note: if opacity is zero no shadow will be drawn
*
* @param InShadowColorAndOpacity The new drop shadow color and opacity
*/
UFUNCTION(BlueprintCallable, Category="Appearance")
void SetShadowColorAndOpacity(FLinearColor InShadowColorAndOpacity);
/**
* Sets the offset that the text drop shadow should be drawn at
*
* @param InShadowOffset The new offset
*/
UFUNCTION(BlueprintCallable, Category="Appearance")
void SetShadowOffset(FVector2D InShadowOffset);
/**
* Dynamically set the font info for this text block
*
* @param InFontInfo THe new font info
*/
UFUNCTION(BlueprintCallable, Category = "Appearance")
void SetFont(FSlateFontInfo InFontInfo);
/**
* Set the text justification for this text block
*
* @param Justification new justification
*/
UFUNCTION( BlueprintCallable, Category = "Appearance" )
void SetJustification( ETextJustify::Type InJustification );
public:
UPROPERTY()
USlateWidgetStyleAsset* Style_DEPRECATED;
/** The text to display */
UPROPERTY(EditAnywhere, Category=Content, meta=( MultiLine="true" ))
FText Text;
/** A bindable delegate to allow logic to drive the text of the widget */
UPROPERTY()
FGetText TextDelegate;
/** The color of the text */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance)
FSlateColor ColorAndOpacity;
/** A bindable delegate for the ColorAndOpacity. */
UPROPERTY()
FGetSlateColor ColorAndOpacityDelegate;
/** The font to render the text with */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance)
FSlateFontInfo Font;
/** The direction the shadow is cast */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance)
FVector2D ShadowOffset;
/** The color of the shadow */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance, meta=( DisplayName="Shadow Color" ))
FLinearColor ShadowColorAndOpacity;
/** A bindable delegate for the ShadowColorAndOpacity. */
UPROPERTY()
FGetLinearColor ShadowColorAndOpacityDelegate;
/** How the text should be aligned with the margin. */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance)
TEnumAsByte<ETextJustify::Type> Justification;
/** True if we're wrapping text automatically based on the computed horizontal space for this widget */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance)
bool AutoWrapText;
/** Whether text wraps onto a new line when it's length exceeds this width; if this value is zero or negative, no wrapping occurs. */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance, AdvancedDisplay)
float WrapTextAt;
/** The minimum desired size for the text */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance, AdvancedDisplay)
float MinDesiredWidth;
/** The amount of blank space left around the edges of text area. */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance, AdvancedDisplay)
FMargin Margin;
/** The amount to scale each lines height by. */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Appearance, AdvancedDisplay)
float LineHeightPercentage;
///** Called when this text is double clicked */
//SLATE_EVENT(FOnClicked, OnDoubleClicked)
/**
* Gets the widget text
* @return The widget text
*/
UFUNCTION(BlueprintCallable, Category="Widget", meta=(DisplayName="GetText (Text)"))
FText GetText() const;
/**
* Directly sets the widget text.
* Warning: This will wipe any binding created for the Text property!
* @param InText The text to assign to the widget
*/
UFUNCTION(BlueprintCallable, Category="Widget", meta=(DisplayName="SetText (Text)"))
void SetText(FText InText);
// UWidget interface
virtual void SynchronizeProperties() override;
// End of UWidget interface
// UVisual interface
virtual void ReleaseSlateResources(bool bReleaseChildren) override;
// End of UVisual interface
// Begin UObject interface
virtual void PostLoad() override;
// End of UObject interface
#if WITH_EDITOR
// UWidget interface
virtual const FSlateBrush* GetEditorIcon() override;
virtual const FText GetPaletteCategory() override;
virtual void OnCreationFromPalette() override;
// End UWidget interface
virtual FString GetLabelMetadata() const override;
void HandleTextCommitted(const FText& InText, ETextCommit::Type CommitteType);
#endif
protected:
// UWidget interface
virtual TSharedRef<SWidget> RebuildWidget() override;
virtual void OnBindingChanged(const FName& Property) override;
// End of UWidget interface
protected:
TSharedPtr<STextBlock> MyTextBlock;
};
|
TimYagan/stroom | stroom-app/src/test/java/stroom/headless/TestCli.java | <gh_stars>1-10
/*
* Copyright 2016 Crown Copyright
*
* 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 stroom.headless;
import org.junit.jupiter.api.Test;
import stroom.test.common.ComparisonHelper;
import stroom.util.io.FileUtil;
import stroom.util.zip.ZipUtil;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class TestCli {
// private static final Version CORE_XML_SCHEMAS_VERSION = Version.of(1, 0);
// private static final Version EVENT_LOGGING_XML_SCHEMA_VERSION = Version.of(1, 0);
@Test
void test() throws IOException {
// Path newTempDir = FileUtil.getTempDir().resolve("headless");
// StroomProperties.setOverrideProperty("stroom.temp", FileUtil.getCanonicalPath(newTempDir), StroomProperties.Source.TEST);
//
// // Make sure the new temp directory is empty.
// if (Files.isDirectory(newTempDir)) {
// FileUtils.deleteDirectory(newTempDir.toFile());
// }
final Path base = StroomHeadlessTestFileUtil.getTestResourcesDir();
final Path testPath = base.resolve("TestHeadless");
final Path outputPath = testPath.resolve("output");
FileUtil.deleteDir(outputPath);
Files.createDirectories(outputPath);
// StroomProperties.setOverrideProperty("stroom.temp", FileUtil.getCanonicalPath(outputPath), StroomProperties.Source.TEST);
final Path contentDirPath = testPath.resolve("content");
final Path inputDirPath = testPath.resolve("input");
Files.createDirectories(contentDirPath);
Files.createDirectories(inputDirPath);
// final Path samplesPath = base.resolve("../../../../stroom-core/src/test/resources/samples").toAbsolutePath().normalize();
final Path errorFilePath = outputPath.resolve("error.log");
final Path expectedOutputFilePath = testPath.resolve("expectedOutput");
// Create input zip file
final Path inputSourcePath = testPath.resolve("input_source");
Files.createDirectories(inputSourcePath);
final Path inputFilePath = inputDirPath.resolve("001.zip");
Files.deleteIfExists(inputFilePath);
ZipUtil.zip(inputFilePath, inputSourcePath);
final Path outputFilePath = outputPath.resolve("output.log");
// // Create config zip file
// final Path contentPacks = tmpPath.resolve("contentPacks");
// Files.createDirectories(contentPacks);
// importXmlSchemas(contentPacks);
//
// // Copy required config into the temp dir.
// final Path rawConfigPath = tmpPath.resolve("config");
// Files.createDirectories(rawConfigPath);
// final Path configUnzippedDirPath = samplesPath.resolve("config");
// FileUtils.copyDirectory(configUnzippedDirPath.toFile(), rawConfigPath.toFile());
//
// // Unzip the downloaded content packs into the temp dir.
// try (final DirectoryStream<Path> stream = Files.newDirectoryStream(contentPacks)) {
// stream.forEach(file -> {
// try {
// ZipUtil.unzip(file, rawConfigPath);
// } catch (IOException e) {
// e.printStackTrace();
// }
// });
// } catch (final IOException e) {
// throw new UncheckedIOException(e);
// }
//
// // Build the config zip file.
// final Path configFilePath = tmpPath.resolve("config.zip");
// Files.deleteIfExists(configFilePath);
// ZipUtil.zip(configFilePath, rawConfigPath);
final Cli cli = new Cli();
// cli.setConfig(FileUtil.getCanonicalPath(configFilePath));
cli.setContent(FileUtil.getCanonicalPath(contentDirPath));
cli.setInput(FileUtil.getCanonicalPath(inputDirPath));
cli.setError(FileUtil.getCanonicalPath(errorFilePath));
cli.setTmp(FileUtil.getCanonicalPath(outputPath));
cli.run();
final List<String> expectedLines = Files.readAllLines(expectedOutputFilePath, Charset.defaultCharset());
final List<String> outputLines = Files.readAllLines(outputFilePath, Charset.defaultCharset());
final List<String> errorLines = Files.readAllLines(errorFilePath, Charset.defaultCharset());
// same number of lines output as expected
assertThat(outputLines).hasSize(expectedLines.size());
assertThat(errorLines).isEmpty();
// make sure all lines are present in both
assertThat(new HashSet<>(outputLines)).isEqualTo(new HashSet<>(expectedLines));
// content should exactly match expected file
ComparisonHelper.compareFiles(expectedOutputFilePath, outputFilePath);
}
// private void importXmlSchemas(final Path path) {
// importContentPacks(Arrays.asList(
// ContentPack.of("core-xml-schemas", CORE_XML_SCHEMAS_VERSION),
// ContentPack.of("event-logging-xml-schema", EVENT_LOGGING_XML_SCHEMA_VERSION)
// ), path);
// }
//
// private void importContentPacks(final List<ContentPack> packs, final Path path) {
// packs.forEach(pack -> ContentPackDownloader.downloadContentPack(pack.getName(), pack.getVersion(), path));
// }
}
|
marketmuse/editor | src/editor/normalizer/normalizer.spec.js | <filename>src/editor/normalizer/normalizer.spec.js
import { Editor, Transforms } from 'slate';
import mount from '@utils/test/mount';
import { types } from '@config/common';
describe('normalizer options', () => {
// ****
test('editor should accept multiple normalizer and work', () => {
const plugins = [
{
normalizerOptions: {
normalize: (editor, [ node, path ]) => {
const isTopLevel = path.length === 1;
const isFirst = path[0] === 0;
const isHeading = node.type === types.h1;
// make first block heading
if (isTopLevel && isFirst && !isHeading) {
Transforms.unwrapNodes(editor, { at: path });
Transforms.wrapNodes(editor, { children: [], type: types.h1 }, { at: path })
return true;
}
return false;
}
},
},
{
normalizerOptions: {
normalize: (editor, [ node, path ]) => {
const isTopLevel = path.length === 1;
const isSecond = path[0] === 1;
const isParagraph = node.type === types.p;
// make second block paragraph
if (isTopLevel && isSecond && !isParagraph) {
Transforms.unwrapNodes(editor, { at: path });
Transforms.wrapNodes(editor, { children: [], type: types.p }, { at: path })
return true;
}
return false;
}
}
},
];
// create the editor
const editor = mount({
mmsEditorProps: { plugins },
children: [
{ type: types.h2, children: [{ text: 'test1' }] },
{ type: types.h2, children: [{ text: 'test2' }] },
{ type: types.h2, children: [{ text: 'test3' }] },
]
});
// trigger normalization
Editor.normalize(editor, { force: true })
// normalizer should work and enforce layout
expect(editor.children).toEqual([
{ type: types.h1, children: [{ text: 'test1' }] },
{ type: types.p, children: [{ text: 'test2' }] },
{ type: types.h2, children: [{ text: 'test3' }] },
]);
});
});
|
opensourceways/app-cla-server | controllers/auth_on_corp_manager.go | <reponame>opensourceways/app-cla-server<gh_stars>1-10
package controllers
import (
"fmt"
"github.com/opensourceways/app-cla-server/dbmodels"
"github.com/opensourceways/app-cla-server/models"
"github.com/opensourceways/app-cla-server/util"
)
// @Title authenticate corporation manager
// @Description authenticate corporation manager
// @Param body body models.CorporationManagerAuthentication true "body for corporation manager info"
// @Success 201 {int} map
// @Failure util.ErrNoCLABindingDoc "no cla binding applied to corporation"
// @router /auth [post]
func (this *CorporationManagerController) Auth() {
action := "authenticate as corp/employee manager"
ip, fr := this.getRemoteAddr()
if fr != nil {
this.sendFailedResultAsResp(fr, action)
return
}
var info models.CorporationManagerAuthentication
if fr := this.fetchInputPayload(&info); fr != nil {
this.sendFailedResultAsResp(fr, action)
return
}
v, merr := (&info).Authenticate()
if merr != nil {
this.sendModelErrorAsResp(merr, action)
return
}
if len(v) == 0 {
this.sendFailedResponse(400, errWrongIDOrPassword, fmt.Errorf("wrong id or pw"), action)
return
}
type authInfo struct {
models.OrgRepo
Role string `json:"role"`
Token string `json:"token"`
InitialPWChanged bool `json:"initial_pw_changed"`
}
result := make([]authInfo, 0, len(v))
for linkID, item := range v {
token, err := this.newAccessToken(linkID, ip, &item)
if err != nil {
continue
}
result = append(result, authInfo{
OrgRepo: item.OrgRepo,
Role: item.Role,
Token: token,
InitialPWChanged: item.InitialPWChanged,
})
}
this.sendSuccessResp(result)
}
func (this *CorporationManagerController) newAccessToken(linkID, ip string, info *dbmodels.CorporationManagerCheckResult) (string, error) {
permission := ""
switch info.Role {
case dbmodels.RoleAdmin:
permission = PermissionCorpAdmin
case dbmodels.RoleManager:
permission = PermissionEmployeeManager
}
return this.newApiToken(
permission, ip,
&acForCorpManagerPayload{
Name: info.Name,
Email: info.Email,
LinkID: linkID,
OrgInfo: info.OrgInfo,
},
)
}
type acForCorpManagerPayload struct {
Name string `json:"name"`
Email string `json:"email"`
LinkID string `json:"link_id"`
models.OrgInfo
}
func (this *acForCorpManagerPayload) hasEmployee(email string) bool {
return util.EmailSuffix(this.Email) == util.EmailSuffix(email)
}
|
ppipada/tech-interview-prep | docs/pycode/trie/add-and-search-word.py | <filename>docs/pycode/trie/add-and-search-word.py
import collections
class TrieNode():
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isWord = False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
node = self.root
for w in word:
node = node.children[w]
node.isWord = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
node = self.root
self.res = False
self.dfs(node, word)
return self.res
def dfs(self, node, word):
if not word:
if node.isWord:
self.res = True
return
if word[0] == ".":
for n in node.children.values():
self.dfs(n, word[1:])
else:
node = node.children.get(word[0])
if not node:
return
self.dfs(node, word[1:])
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word) |
chriszs/documentcloud | lib/dc/embed.rb | <reponame>chriszs/documentcloud<filename>lib/dc/embed.rb
=begin
# Thoughts
Embeds can be categorized along four dimensions:
## Resource
The resource is the type of thing you are embedding. The contents of the embed
will depend on the resource. Each resource will include different code and
configuration options (the literal contents of the embed).
* Documents
* Pages (currently uses Document as its model)
* Notes
* Search
## Request Strategy
* oEmbed
* Literal
## DOM Mechanism
The mechanism used for containing the contents of an embed. Effectively there
are two types of mechanisms: inserting a JS application directly into the
embedding DOM, or inserting an iFrame which contains the contents of the embed.
* in-DOM (direct)
* iFrame
## Embedding Context
Embedding context is the manner in which the embed code is introduced to the web
page it has been instructed to load on (either contained in the markup sent to
the browser, or inserted dynamically via javascript). The embedding context is
generally not known to the embed generator.
* Embedded in markup (server_side)
* Client-side injection (client_side)
=end
require_relative 'embed/base'
require_relative 'embed/document'
require_relative 'embed/page'
require_relative 'embed/note'
require_relative 'embed/search'
# DC::Embed is a collection of presenters which provide a
# serializable representation of embeddable resources (for example, oEmbed).
module DC
module Embed
# List the resources which are supported for serialization
EMBED_RESOURCE_MAP = {
:document => self::Document,
:page => self::Page,
:note => self::Note,
:search => self::Search,
}
EMBEDDABLE_RESOURCES = EMBED_RESOURCE_MAP.keys
# also list the mapping between model classes
# and embeddable resources (where there is one).
EMBEDDABLE_MODEL_MAP = {
::Document => :document,
::Annotation => :note,
}
EMBEDDABLE_MODELS = EMBEDDABLE_MODEL_MAP.keys
# Determine & return the appropriate presenter class for a resource
def self.embed_type(resource)
case
when EMBEDDABLE_MODELS.any?{ |model_klass| resource.kind_of? model_klass }
# by looking up whether the resource's model is embeddable
EMBEDDABLE_MODEL_MAP[resource.class]
when EMBEDDABLE_RESOURCES.include?(resource.type)
# or if the resource specifies a type of embed explicitly.
resource.type
else
# set up a system to actually register types of things as embeddable
raise ArgumentError, "#{resource} is not registered as an embeddable resource"
end
end
def self.embed_klass(type)
raise ArgumentError, "#{type} is not a recognized resource type" unless EMBEDDABLE_RESOURCES.include? type
EMBED_RESOURCE_MAP[type]
end
def self.embed_for(resource, config={}, options={})
self.embed_klass(self.embed_type(resource)).new(resource, config, options)
end
end
end
|
aquila-zyy/Botania | src/main/java/vazkii/botania/api/BotaniaAPIClient.java | <filename>src/main/java/vazkii/botania/api/BotaniaAPIClient.java<gh_stars>100-1000
/*
* This class is distributed as part of the Botania Mod.
* Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*/
package vazkii.botania.api;
import com.google.common.base.Suppliers;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import org.apache.logging.log4j.LogManager;
import vazkii.botania.api.block.IFloatingFlower;
import java.util.Collections;
import java.util.Map;
import java.util.function.Supplier;
/**
* Class for API calls that must be made clientside
*/
public interface BotaniaAPIClient {
Supplier<BotaniaAPIClient> INSTANCE = Suppliers.memoize(() -> {
try {
return (BotaniaAPIClient) Class.forName("vazkii.botania.client.impl.BotaniaAPIClientImpl")
.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
LogManager.getLogger().warn("Unable to find BotaniaAPIClientImpl, using a dummy");
return new BotaniaAPIClient() {};
}
});
static BotaniaAPIClient instance() {
return INSTANCE.get();
}
/**
* Registers your model for island type islandType here.
* Call this during {@link net.minecraftforge.client.event.ModelRegistryEvent}.
*
* @param islandType The islandtype to register
* @param model The model, only {@link ResourceLocation} allowed, no {@link ModelResourceLocation} allowed.
*/
default void registerIslandTypeModel(IFloatingFlower.IslandType islandType, ResourceLocation model) {}
/**
* @return An immutable and live view of the registered island type model map
*/
default Map<IFloatingFlower.IslandType, ResourceLocation> getRegisteredIslandTypeModels() {
return Collections.emptyMap();
}
/**
* Draw a mana bar on the screen
*/
default void drawSimpleManaHUD(PoseStack ms, int color, int mana, int maxMana, String name) {}
/**
* Performs the effects of {@link #drawSimpleManaHUD}, then renders {@code bindDisplay}, and a checkmark or x-mark
* dependong on the value of {@code properlyBound}.
*/
default void drawComplexManaHUD(PoseStack ms, int color, int mana, int maxMana, String name, ItemStack bindDisplay, boolean properlyBound) {}
}
|
hmrc/cds-imports-dds-frontend | test/uk/gov/hmrc/cdsimportsddsfrontend/domain/SubmissionStatusSpec.scala | <reponame>hmrc/cds-imports-dds-frontend
/*
* Copyright 2019 HM Revenue & Customs
*
* 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 uk.gov.hmrc.cdsimportsddsfrontend.domain
import org.scalatest.{Matchers, WordSpec}
import uk.gov.hmrc.cdsimportsddsfrontend.domain.SubmissionStatus._
class SubmissionStatusSpec extends WordSpec with Matchers {
"Reads for status" should {
"correctly retrieve a value for every scenario" in {
retrieve("Pending") shouldBe PENDING
retrieve("Cancellation Requested") shouldBe REQUESTED_CANCELLATION
retrieve("01") shouldBe ACCEPTED
retrieve("02") shouldBe RECEIVED
retrieve("03") shouldBe REJECTED
retrieve("05") shouldBe UNDERGOING_PHYSICAL_CHECK
retrieve("06") shouldBe ADDITIONAL_DOCUMENTS_REQUIRED
retrieve("07") shouldBe AMENDED
retrieve("08") shouldBe RELEASED
retrieve("09") shouldBe CLEARED
retrieve("10") shouldBe CANCELLED
retrieve("11", Some("39")) shouldBe CUSTOMS_POSITION_GRANTED
retrieve("11", Some("41")) shouldBe CUSTOMS_POSITION_DENIED
retrieve("13") shouldBe TAX_LIABILITY
retrieve("14") shouldBe INSUFFICIENT_BALANCE_IN_DAN
retrieve("15") shouldBe INSUFFICIENT_BALANCE_IN_DAN_REMINDER
retrieve("17") shouldBe DECLARATION_HANDLED_EXTERNALLY
retrieve("UnknownStatus") shouldBe UNKNOWN
retrieve("WrongStatus") shouldBe UNKNOWN
}
}
} |
ypiel-talend/components | components/components-localio/localio-definition/src/test/java/org/talend/components/localio/fixed/FixedInputPropertiesTest.java | <filename>components/components-localio/localio-definition/src/test/java/org/talend/components/localio/fixed/FixedInputPropertiesTest.java
// ============================================================================
//
// Copyright (C) 2006-2017 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.components.localio.fixed;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.talend.daikon.properties.presentation.Form.MAIN;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.talend.daikon.properties.presentation.Form;
import org.talend.daikon.properties.presentation.Widget;
import org.talend.daikon.serialize.jsonschema.JsonSchemaUtil;
import java.util.Arrays;
/**
* Unit tests for {@link FixedInputProperties}.
*/
public class FixedInputPropertiesTest {
/**
* Instance to test. A new instance is created for each test.
*/
private FixedInputProperties properties = null;
@Before
public void setup() {
properties = new FixedInputProperties("test");
properties.init();
}
/**
* Check the correct default values in the properties.
*/
@Test
public void testDefaultProperties() {
assertThat(properties.repeat.getValue(), is(1));
assertThat(properties.useOverrideValues.getValue(), is(false));
assertThat(properties.overrideValuesAction.getValue(), is(FixedInputProperties.OverrideValuesAction.NONE));
assertThat(properties.overrideValues.getValue(), is(""));
}
/**
* Check the setup of the form layout.
*/
@Test
public void testSetupLayout() {
properties.setupLayout();
Form main = properties.getForm(Form.MAIN);
assertThat(main, notNullValue());
assertThat(main.getWidgets(), hasSize(3));
// Check the widgets.
Widget w = main.getWidget(properties.repeat.getName());
assertThat(w.getWidgetType(), is(Widget.DEFAULT_WIDGET_TYPE));
assertThat(w.isVisible(), is(true));
w = main.getWidget(properties.overrideValuesAction.getName());
assertThat(w.getWidgetType(), is(Widget.DEFAULT_WIDGET_TYPE));
assertThat(w.isVisible(), is(false));
w = main.getWidget(properties.overrideValues.getName());
assertThat(w.getWidgetType(), is(Widget.CODE_WIDGET_TYPE));
assertThat(w.isVisible(), is(false));
}
/**
* Check the changes to the form.
*/
@Test
public void testRefreshLayout() {
properties.setupLayout();
Form main = properties.getForm(Form.MAIN);
assertThat(main, notNullValue());
assertThat(main.getWidgets(), hasSize(3));
// Turn the override values on.
properties.useOverrideValues.setValue(true);
properties.refreshLayout(main);
assertThat(main.getWidget(properties.repeat.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValuesAction.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValues.getName()).isVisible(), is(false));
// Check the different values for APPEND and REPLACE and NONE
properties.overrideValuesAction.setValue(FixedInputProperties.OverrideValuesAction.APPEND);
properties.refreshLayout(main);
assertThat(main.getWidget(properties.repeat.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValuesAction.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValues.getName()).isVisible(), is(true));
properties.overrideValuesAction.setValue(FixedInputProperties.OverrideValuesAction.REPLACE);
properties.refreshLayout(main);
assertThat(main.getWidget(properties.repeat.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValuesAction.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValues.getName()).isVisible(), is(true));
properties.overrideValuesAction.setValue(FixedInputProperties.OverrideValuesAction.NONE);
properties.refreshLayout(main);
assertThat(main.getWidget(properties.repeat.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValuesAction.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValues.getName()).isVisible(), is(false));
// Turn the override values off.
properties.useOverrideValues.setValue(false);
properties.refreshLayout(main);
assertThat(main.getWidget(properties.repeat.getName()).isVisible(), is(true));
assertThat(main.getWidget(properties.overrideValuesAction.getName()).isVisible(), is(false));
assertThat(main.getWidget(properties.overrideValues.getName()).isVisible(), is(false));
}
@Test
public void testJsonSchemaSerialization() throws JSONException {
String jsonString = JsonSchemaUtil.toJson(properties, MAIN, FixedInputDefinition.NAME);
assertThat(jsonString, notNullValue());
JSONObject node = new JSONObject(jsonString);
assertThat(node, notNullValue());
JSONAssert.assertEquals("{\"jsonSchema\": {},\"uiSchema\": {},\"properties\": {}} ", node, false);
// Check the properties.
JSONObject jsonProps = node.getJSONObject("properties");
JSONAssert.assertEquals("{\"@definitionName\": \"FixedInput\",\"outgoing\": {},\"repeat\": 1} ", jsonProps, false);
}
} |
LlimaV10/example-react-native-app | screens/Fundamentals/Example4.js | import React, {useState} from 'react'
import {View, Text, Button} from "react-native";
const Example4 = () => {
const [isActivated, setIsActivated] = useState(false);
return (
<View>
<Text>{"Used state and <Button> component:"}</Text>
<Text>{"const [isActivated, setIsActivated] = useState(false);"}</Text>
<Text />
<Text>{"<Button\n" +
" onPress={() => {\n" +
" setIsActivated(true)\n" +
" }}\n" +
" disabled={isActivated}\n" +
" title={isActivated ? 'Activated' : 'Not activated'}\n" +
"/>"}</Text>
<Text />
<Text>{"Result:"}</Text>
<Button
onPress={() => {
setIsActivated(true)
}}
disabled={isActivated}
title={isActivated ? 'Activated' : 'Not activated'}
/>
</View>
)
};
export default Example4
|
zxp19960123/cos-snippets | JavaScript/test/src/put_object.js | // 简单上传对象
function putObject(assert) {
//.cssg-snippet-body-start:[put-object]
cos.putObject({
Bucket: 'examplebucket-1250000000', /* 必须 */
Region: 'COS_REGION', /* 存储桶所在地域,必须字段 */
Key: 'exampleobject', /* 必须 */
StorageClass: 'STANDARD',
Body: fileObject, // 上传文件对象
onProgress: function(progressData) {
console.log(JSON.stringify(progressData));
}
}, function(err, data) {
console.log(err || data);
});
//.cssg-snippet-body-end
}
// 简单上传对象
function putObjectString(assert) {
//.cssg-snippet-body-start:[put-object-string]
cos.putObject({
Bucket: 'examplebucket-1250000000', /* 必须 */
Region: 'COS_REGION', /* 存储桶所在地域,必须字段 */
Key: 'exampleobject', /* 必须 */
Body: 'hello!',
}, function(err, data) {
console.log(err || data);
});
//.cssg-snippet-body-end
}
// 简单上传对象
function putObjectFolder(assert) {
//.cssg-snippet-body-start:[put-object-folder]
cos.putObject({
Bucket: 'examplebucket-1250000000', /* 必须 */
Region: 'COS_REGION', /* 存储桶所在地域,必须字段 */
Key: 'a/', /* 必须 */
Body: '',
}, function(err, data) {
console.log(err || data);
});
//.cssg-snippet-body-end
}
//.cssg-methods-pragma
test("PutObject", async function(assert) {
// 简单上传对象
await putObject(assert)
// 简单上传对象
await putObjectString(assert)
// 简单上传对象
await putObjectFolder(assert)
//.cssg-methods-pragma
}) |
GothAck/FlatRPC | examples/simple/client.cpp | #include <thread>
#include <plog/Log.h>
#include <plog/Appenders/ColorConsoleAppender.h>
#include "simple_flatrpc.hpp"
using namespace std;
using namespace examples::simple;
zmqpp::context ctx;
GreeterClient client(ctx);
int main(int argc, char *argv[]) {
static plog::ColorConsoleAppender<plog::TxtFormatter> consoleAppender;
plog::init(plog::verbose, &consoleAppender);
if (argc == 1) {
PLOG_ERROR << "Please call this binary with your name as the first argument";
return 1;
}
client.connect("unix:///tmp/greeterserver");
thread clientThread([] {
client.run(); // Run the client event loop
});
auto req = make_shared<HelloRequestT>();
req->name = argv[1];
try {
auto rep = client.SayHello(move(req)).get();
PLOG_INFO << "Reply: " << rep->message;
} catch (exception &e) {
PLOG_ERROR << "Exception: " << e.what();
}
client.Quit().get();
client.stop();
clientThread.join();
return 0;
}
|
galterlibrary/InvenioRDM-at-NU | cd2h_repo_project/modules/__init__.py | <filename>cd2h_repo_project/modules/__init__.py
"""cd2h-repo-project modules."""
|
guoshucan/mpaas | ghost.framework.module/src/main/java/ghost/framework/module/reflect/annotations/InterfaceParentId.java | <gh_stars>1-10
package ghost.framework.module.reflect.annotations;
import java.lang.annotation.*;
/**
* @Author: 郭树灿{guoshucan-pc}
* @link: 手机:13715848993, QQ 27048384
* @Description:父级接口id
* @Date: 23:50 2018-09-20
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE,
ElementType.FIELD,
ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.PARAMETER,
ElementType.ANNOTATION_TYPE,
ElementType.PACKAGE,
ElementType.TYPE_PARAMETER,
ElementType.LOCAL_VARIABLE,
ElementType.TYPE_USE})
@Inherited
public @interface InterfaceParentId {
/**
* 获取接口Id。
*
* @return
*/
String id();
}
|
alphagov-mirror/paas-cf | tools/pipecleaner/utils.go | package main
import (
"fmt"
"os"
"regexp"
"golang.org/x/crypto/ssh/terminal"
"github.com/logrusorgru/aurora"
)
var (
indentRegexp = regexp.MustCompile("(?m)^")
concourseVarRegexp = regexp.MustCompile(`\(\((!?[-/\.\w\pL]+)\)\)`)
resourceTriggerRegexp = regexp.MustCompile(`trigger:\s+\(\((!?[-/\.\w\pL]+)\)\)`)
)
func indent(s interface{}) string {
return indentRegexp.ReplaceAllLiteralString(fmt.Sprintf("%s", s), "\t")
}
func rColor(s string) string {
if terminal.IsTerminal(int(os.Stdout.Fd())) {
return fmt.Sprint(aurora.Red(s))
}
return s
}
func gColor(s string) string {
if terminal.IsTerminal(int(os.Stdout.Fd())) {
return fmt.Sprint(aurora.Green(s))
}
return s
}
func yColor(s string) string {
if terminal.IsTerminal(int(os.Stdout.Fd())) {
return fmt.Sprint(aurora.Yellow(s))
}
return s
}
|
maddler-hub/Ocelot-Social | cypress/integration/Moderation.ReportContent/I_click_on_the_author.js | <filename>cypress/integration/Moderation.ReportContent/I_click_on_the_author.js
import { When } from "cypress-cucumber-preprocessor/steps";
When('I click on the author', () => {
cy.get('.user-teaser')
.click()
.url().should('include', '/profile/')
}) |
javadude/605.686-samples | Module - Sensors/Sensors/app/src/main/java/com/javadude/sensors/PuckView.java | <reponame>javadude/605.686-samples
package com.javadude.sensors;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class PuckView extends View {
private int cx = 0;
private int cy = 0;
private int dx = 10;
private int dy = 20;
private int ax = 0;
private int ay = 0;
private Paint paint;
private int radius;
private Thread mover;
public PuckView(Context context) {
super(context);
}
public void changeAccel(int ax, int ay) {
this.ax = ax;
this.ay = ay;
}
private void move() {
dx += ax;
dy += ay;
cx += dx;
cy += dy;
if (cx < radius) {
dx = -dx/2;
cx = radius;
}
if (cy < radius) {
dy = -dy/2;
cy = radius;
}
if (cx > getWidth() - radius) {
dx = -dx/2;
cx = getWidth() - radius;
}
if (cy > getHeight() - radius) {
dy = -dy/2;
cy = getHeight() - radius;
}
}
private void init() {
paint = new Paint();
paint.setColor(Color.RED);
radius = Math.min(getWidth(), getHeight()) / 10;
mover = new Thread() {
@Override
public void run() {
while(!isInterrupted()) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
interrupt();
}
move();
postInvalidate();
}
}
};
mover.start();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mover.interrupt();
mover = null;
paint = null;
}
@Override
protected void onDraw(Canvas canvas) {
if (paint == null)
init();
canvas.drawColor(Color.WHITE);
canvas.drawCircle(cx, cy, radius, paint);
}
}
|
ohanlonl/qCMAT | plugins/core/qPCL/PclUtils/filters/dialogs/MLSDialog.h | //##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: qPCL #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: <NAME> #
//# #
//##########################################################################
//
#ifndef MLSDIALOG_H
#define MLSDIALOG_H
#include <ui_MLSDialog.h>
//Qt
#include <QDialog>
class MLSDialog : public QDialog, public Ui::MLSDialog
{
Q_OBJECT
public:
explicit MLSDialog(QWidget *parent = 0);
protected slots:
void activateMenu(QString name);
void toggleMethods(bool status);
void updateSquaredGaussian(double radius);
protected:
void updateCombo();
void deactivateAllMethods();
};
#endif // MLSDIALOG_H
|
microsoft/HybridRow | src/Serialization/HybridRow.Native/DateTime.h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------
#pragma once
#include <cstdint>
namespace cdb_hr
{
/// <summary>C# DateTime type.</summary>
/// <remarks>CoreCLR DateTime definition: https://referencesource.microsoft.com/#mscorlib/system/datetime.cs </remarks>
#pragma pack(push, 1)
struct DateTime final
{
constexpr DateTime() noexcept : m_data(0) { }
~DateTime() noexcept = default;
constexpr DateTime(int64_t ticks) noexcept : m_data(static_cast<uint64_t>(ticks)) { }
DateTime(const DateTime& other) = default;
DateTime(DateTime&& other) noexcept = default;
DateTime& operator=(const DateTime& other) = default;
DateTime& operator=(DateTime&& other) noexcept = default;
[[nodiscard]] int64_t Ticks() const noexcept { return static_cast<int64_t>(m_data); }
friend bool operator==(const DateTime& lhs, const DateTime& rhs) { return lhs.m_data == rhs.m_data; }
friend bool operator!=(const DateTime& lhs, const DateTime& rhs) { return !(lhs == rhs); }
private:
friend std::hash<cdb_hr::DateTime>;
// The data is stored as an unsigned 64-bit integer
// Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value
// 12/31/9999 23:59:59.9999999
// Bits 63-64: A four-state value that describes the DateTimeKind value of the date time, with a 2nd
// value for the rare case where the date time is local, but is in an overlapped daylight
// savings time hour and it is in daylight savings time. This allows distinction of these
// otherwise ambiguous local times and prevents data loss when round tripping from Local to
// UTC time.
uint64_t m_data;
};
#pragma pack(pop)
}
namespace std
{
template<>
struct hash<cdb_hr::DateTime>
{
constexpr std::size_t operator()(cdb_hr::DateTime const& s) const noexcept
{
return cdb_core::HashCode::Combine(s.m_data);
}
};
}
|
Terryhata6/Mengine | src/Plugins/TTFPlugin/TTFPrototypeGenerator.h | <gh_stars>10-100
#pragma once
#include "Kernel/FactoryPrototypeGenerator.h"
#include "Kernel/Factory.h"
#include "ft2build.h"
#include "freetype/freetype.h"
#include "freetype/ftglyph.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
class TTFPrototypeGenerator
: public FactoryPrototypeGenerator
{
public:
TTFPrototypeGenerator();
~TTFPrototypeGenerator() override;
public:
void setFTLibrary( FT_Library _ftlibrary );
public:
FactoryPtr _initializeFactory() override;
void _finalizeFactory() override;
public:
FactorablePointer generate( const DocumentPtr & _doc ) override;
protected:
FT_Library m_ftlibrary;
FactoryPtr m_factoryFont;
};
//////////////////////////////////////////////////////////////////////////
typedef IntrusivePtr<TTFPrototypeGenerator> TTFPrototypeGeneratorPtr;
//////////////////////////////////////////////////////////////////////////
} |
awf/ELL | tools/utilities/finetune/src/Report.cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: Report.cpp (finetune)
// Authors: <NAME>
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Report.h"
#include "FineTuneArguments.h"
#include "FineTuneModel.h"
#include "ModelUtils.h"
#include "TransformData.h"
#include <utilities/include/StringUtil.h>
namespace ell
{
Report::Report(std::ostream& stream, ReportFormat format) :
_stream(stream)
{
}
Report::~Report()
{
_stream << "\n"
<< std::endl;
}
template <typename ValueType>
void Report::WriteKeyValue(std::string key, const ValueType& value)
{
_stream << key << ":\t" << value << "\n";
}
void Report::Flush()
{
_stream << std::flush;
}
void Report::WriteParameters(const FineTuneArguments& args)
{
WriteKeyValue("TrainingExamples", args.maxTrainingRows);
WriteKeyValue("TestExamples", args.maxTestingRows);
WriteKeyValue("TrainingDataset", args.trainDataArguments.GetDataFilePath());
WriteKeyValue("TestDataset", args.testDataArguments.GetDataFilePath());
WriteKeyValue("L2Regularization", args.l2Regularization);
if (args.sparsityTarget != 0)
{
WriteKeyValue("DesiredSparsity", args.sparsityTarget);
WriteKeyValue("DesiredSparsityEps", args.sparsityTargetEpsilon);
}
else if (args.l1Regularization > 0)
{
WriteKeyValue("L1Regularization", args.l1Regularization);
}
WriteKeyValue("DesiredPrecision", args.desiredPrecision);
WriteKeyValue("MaxEpochs", args.maxEpochs);
WriteKeyValue("LossFunction", ToString(args.lossFunction));
WriteKeyValue("NormalizeInputs", args.normalizeInputs);
WriteKeyValue("NormalizeOutputs", args.normalizeOutputs);
WriteKeyValue("ReoptimizeWeights", args.reoptimizeSparseWeights);
WriteKeyValue("FineTuneFullyConnectedLayers", args.fineTuneFullyConnectedNodes);
WriteKeyValue("FineTuneConvolutionalLayers", args.fineTuneConvolutionalNodes);
WriteKeyValue("TrainFiltersIndependently", args.optimizeFiltersIndependently);
WriteKeyValue("LayersToSkip", args.numPrefixNodesToSkip);
WriteKeyValue("LayersToSkipAtEnd", args.numSuffixNodesToSkip);
if (!args.specificNodesToSkip.empty())
{
WriteKeyValue("SpecificLayersToSkip", utilities::Join(args.specificNodesToSkip, ","));
}
WriteKeyValue("RandomSeed", args.randomSeed);
Flush();
}
void Report::WriteLayerOptimizationResult(const FineTuningLayerResult& layerInfo)
{
const model::OutputPortBase& originalOutput = *layerInfo.originalOutput;
const optimization::SDCASolutionInfo& optimizationInfo = layerInfo.solutionInfo.info;
std::string nodeType = "";
if (IsConvolutionalLayerNode(originalOutput.GetNode()))
nodeType = "Convolutional";
else if (IsFullyConnectedLayerNode(originalOutput.GetNode()))
nodeType = "FullyConnected";
auto nodeId = originalOutput.GetNode()->GetId().ToString();
WriteLayerOptimizationInfo(nodeType, nodeId, optimizationInfo);
WriteLayerRegularizationParameters(nodeType, nodeId, layerInfo.solutionInfo.l2Regularization, layerInfo.solutionInfo.l1Regularization);
WriteLayerStatistics(nodeType, nodeId, "Original", "Weights", layerInfo.statistics.originalWeightsStatistics);
WriteLayerStatistics(nodeType, nodeId, "Final", "Weights", layerInfo.statistics.finalWeightsStatistics);
WriteLayerActivationStatistics(nodeType, nodeId, layerInfo.statistics.originalActivationStatistics, layerInfo.statistics.rawFineTunedActivationStatistics, layerInfo.statistics.fineTunedActivationStatistics);
WriteLayerTiming(nodeType, nodeId, layerInfo.dataTransformTime, layerInfo.optimizationTime);
}
void Report::WriteLayerOptimizationInfo(std::string nodeType, std::string nodeId, const optimization::SDCASolutionInfo& info)
{
auto prefix = nodeType + "_" + nodeId + "_";
WriteKeyValue(prefix + "NumEpochs", info.numEpochsPerformed);
WriteKeyValue(prefix + "DualityGap", info.DualityGap());
WriteKeyValue(prefix + "PrimalObjective", info.primalObjective);
}
void Report::WriteLayerRegularizationParameters(std::string nodeType, std::string nodeId, double l2Regularization, double l1Regularization)
{
auto prefix = nodeType + "_" + nodeId + "_";
WriteKeyValue(prefix + "L2Regularization", l2Regularization);
WriteKeyValue(prefix + "L1Regularization", l1Regularization);
}
void Report::WriteLayerStatistics(std::string nodeType, std::string nodeId, std::string tag, std::string statsType, const DataStatistics& statistics)
{
WriteKeyValue(nodeType + "_" + nodeId + "_" + tag + "Num" + statsType, statistics.sparsity[0].numValues);
WriteKeyValue(nodeType + "_" + nodeId + "_" + tag + "NumZero" + statsType, statistics.sparsity[0].numZeros);
WriteKeyValue(nodeType + "_" + nodeId + "_" + tag + statsType + "Sparsity", statistics.sparsity[0].GetSparsity());
WriteKeyValue(nodeType + "_" + nodeId + "_" + tag + statsType + "Mean", statistics.mean[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_" + tag + statsType + "Variance", statistics.variance[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_" + tag + statsType + "StdDev", statistics.stdDev[0]);
Flush();
}
void Report::WriteLayerActivationStatistics(std::string nodeType, std::string nodeId, const DataStatistics& originalStatistics, const std::optional<DataStatistics>& unnormalizedFineTunedStatistics, const std::optional<DataStatistics>& fineTunedStatistics)
{
WriteKeyValue(nodeType + "_" + nodeId + "_OriginalNumActivations", originalStatistics.sparsity[0].numValues);
WriteKeyValue(nodeType + "_" + nodeId + "_OriginalNumZeroActivations", originalStatistics.sparsity[0].numZeros);
WriteKeyValue(nodeType + "_" + nodeId + "_OriginalActivationsSparsity", originalStatistics.sparsity[0].GetSparsity());
WriteKeyValue(nodeType + "_" + nodeId + "_OriginalActivationsMean", originalStatistics.mean[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_OriginalActivationsVariance", originalStatistics.variance[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_OriginalActivationsStdDev", originalStatistics.stdDev[0]);
if (unnormalizedFineTunedStatistics)
{
WriteKeyValue(nodeType + "_" + nodeId + "_PreNormFineTunedNumActivations", unnormalizedFineTunedStatistics.value().sparsity[0].numValues);
WriteKeyValue(nodeType + "_" + nodeId + "_PreNormFineTunedNumZeroActivations", unnormalizedFineTunedStatistics.value().sparsity[0].numZeros);
WriteKeyValue(nodeType + "_" + nodeId + "_PreNormFineTunedActivationsSparsity", unnormalizedFineTunedStatistics.value().sparsity[0].GetSparsity());
WriteKeyValue(nodeType + "_" + nodeId + "_PreNormFineTunedActivationsMean", unnormalizedFineTunedStatistics.value().mean[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_PreNormFineTunedActivationsVariance", unnormalizedFineTunedStatistics.value().variance[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_PreNormFineTunedActivationsStdDev", unnormalizedFineTunedStatistics.value().stdDev[0]);
}
if (fineTunedStatistics)
{
WriteKeyValue(nodeType + "_" + nodeId + "_FineTunedNumActivations", fineTunedStatistics.value().sparsity[0].numValues);
WriteKeyValue(nodeType + "_" + nodeId + "_FineTunedNumZeroActivations", fineTunedStatistics.value().sparsity[0].numZeros);
WriteKeyValue(nodeType + "_" + nodeId + "_FineTunedActivationsSparsity", fineTunedStatistics.value().sparsity[0].GetSparsity());
WriteKeyValue(nodeType + "_" + nodeId + "_FineTunedActivationsMean", fineTunedStatistics.value().mean[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_FineTunedActivationsVariance", fineTunedStatistics.value().variance[0]);
WriteKeyValue(nodeType + "_" + nodeId + "_FineTunedActivationsStdDev", fineTunedStatistics.value().stdDev[0]);
}
Flush();
}
void Report::WriteLayerTiming(std::string nodeType, std::string nodeId, int transformTime, int optimizationTime)
{
WriteTiming(nodeType + "_" + nodeId + "_DataTransformTime", transformTime);
WriteTiming(nodeType + "_" + nodeId + "_OptimizationTime", optimizationTime);
}
void Report::WriteModelAccuracy(std::string modelName, std::string datasetName, double accuracy)
{
WriteKeyValue(modelName + "_" + datasetName + "_Accuracy", accuracy);
}
void Report::WriteModelSparsity(std::string modelName, const Sparsity& sparsity)
{
WriteKeyValue(modelName + "_TotalWeights", sparsity.numValues);
WriteKeyValue(modelName + "_TotalZeros", sparsity.numZeros);
WriteKeyValue(modelName + "_Sparsity", sparsity.GetSparsity());
Flush();
}
void Report::WriteTiming(std::string tag, int milliseconds)
{
WriteKeyValue(tag, milliseconds);
}
} // namespace ell
|
vsamy/labyfou | src/Container.cpp | <gh_stars>0
#include "Container.h"
#include <SFML/Graphics/RenderTarget.hpp>
namespace GUI
{
Container::Container() : children_(), selectedChild_(-1)
{
}
void Container::pack(Component::sPtr component)
{
children_.push_back(component);
if (!hasSelection() && component->isSelectable())
selectComponent(children_.size() - 1);
}
bool Container::isSelectable() const
{
return false;
}
void Container::handleEvent(const sf::Event & event)
{
// Should be scoped in an unique hasSelection() if
if (hasSelection() && children_[static_cast<std::size_t>(selectedChild_)]->isActive()) //Cast ok because selectedChild_ can never be signed thanks to hasSelection()
children_[static_cast<std::size_t>(selectedChild_)]->handleEvent(event);
else if (event.type == sf::Event::KeyReleased)
{
if (event.key.code == sf::Keyboard::Z || event.key.code == sf::Keyboard::Up)
selectPreviousComponent();
else if (event.key.code == sf::Keyboard::S || event.key.code == sf::Keyboard::Down)
selectNextComponent();
else if (event.key.code == sf::Keyboard::Return || event.key.code == sf::Keyboard::Space)
if (hasSelection())
children_[static_cast<std::size_t>(selectedChild_)]->activate();
}
}
bool Container::hasSelection() const
{
return selectedChild_ >= 0;
}
void Container::selectPreviousComponent()
{
if (!hasSelection()) //Impossible to go to the previous component if there is no selected component
return;
// Search previous component that is selectable
std::size_t prev = static_cast<std::size_t>(selectedChild_);
do
prev = (prev + children_.size() - 1) % children_.size();
while (!children_[prev]->isSelectable());
// Select that component
selectComponent(prev);
}
void Container::selectNextComponent()
{
if (!hasSelection()) //Impossible to go to the next component if there is no selected component
return;
// Search next component that is selectable
std::size_t next = static_cast<std::size_t>(selectedChild_);
do
next = (next + 1) % children_.size();
while (!children_[next]->isSelectable());
// Select that component
selectComponent(next);
}
void Container::selectComponent(std::size_t index)
{
if (children_[index]->isSelectable())
{
if (hasSelection())
children_[static_cast<std::size_t>(selectedChild_)]->deselect();
children_[index]->select();
selectedChild_ = static_cast<int>(index);
}
}
void Container::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
states.transform *= getTransform();
for (const Component::sPtr& child : children_)
target.draw(*child, states);
}
} |
vinirms/sites-responsivos | site arquiteto/node_modules/@fortawesome/free-brands-svg-icons/faTiktok.js | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fab';
var iconName = 'tiktok';
var width = 448;
var height = 512;
var aliases = [];
var unicode = 'e07b';
var svgPathData = 'M448 209.9a210.1 210.1 0 0 1 -122.8-39.25V349.4A162.6 162.6 0 1 1 185 188.3V278.2a74.62 74.62 0 1 0 52.23 71.18V0l88 0a121.2 121.2 0 0 0 1.86 22.17h0A122.2 122.2 0 0 0 381 102.4a121.4 121.4 0 0 0 67 20.14z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
aliases,
unicode,
svgPathData
]};
exports.faTiktok = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = aliases;
exports.unicode = unicode;
exports.svgPathData = svgPathData;
exports.aliases = aliases; |
Harry-Hopkinson/VSCoding-Sequence | node_modules/molstar/lib/commonjs/mol-script/runtime/query/table.js | "use strict";
/**
* Copyright (c) 2018-2019 Mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
Object.defineProperty(exports, "__esModule", { value: true });
var symbol_table_1 = require("../../language/symbol-table");
var base_1 = require("./base");
var structure_1 = require("../../../mol-model/structure");
var types_1 = require("../../../mol-model/structure/model/types");
var set_1 = require("../../../mol-util/set");
var string_1 = require("../../../mol-util/string");
var atomic_1 = require("../../../mol-model/structure/model/properties/atomic");
var util_1 = require("../../../mol-data/util");
var internal_1 = require("../../../mol-model/structure/query/queries/internal");
var array_1 = require("../../../mol-util/array");
var C = base_1.QuerySymbolRuntime.Const;
var D = base_1.QuerySymbolRuntime.Dynamic;
var symbols = [
// ============= TYPES =============
C(symbol_table_1.MolScriptSymbolTable.core.type.bool, function core_type_bool(ctx, v) { return !!v[0](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.type.num, function core_type_num(ctx, v) { return +v[0](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.type.str, function core_type_str(ctx, v) { return '' + v[0](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.type.list, function core_type_list(ctx, xs) { return base_1.QueryRuntimeArguments.forEachEval(xs, ctx, function (v, i, list) { return list[i] = v; }, []); }),
C(symbol_table_1.MolScriptSymbolTable.core.type.set, function core_type_set(ctx, xs) { return base_1.QueryRuntimeArguments.forEachEval(xs, ctx, function core_type_set_argEval(v, i, set) { return set.add(v); }, new Set()); }),
C(symbol_table_1.MolScriptSymbolTable.core.type.regex, function core_type_regex(ctx, v) { return new RegExp(v[0](ctx), (v[1] && v[1](ctx)) || ''); }),
C(symbol_table_1.MolScriptSymbolTable.core.type.bitflags, function core_type_bitflags(ctx, v) { return +v[0](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.type.compositeKey, function core_type_compositeKey(ctx, xs) { return base_1.QueryRuntimeArguments.forEachEval(xs, ctx, function (v, i, list) { return list[i] = '' + v; }, []).join('-'); }),
// ============= LOGIC ================
C(symbol_table_1.MolScriptSymbolTable.core.logic.not, function (ctx, v) { return !v[0](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.logic.and, function (ctx, xs) {
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
if (!xs[i](ctx))
return false;
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
if (!xs[k](ctx))
return false;
}
}
return true;
}),
C(symbol_table_1.MolScriptSymbolTable.core.logic.or, function (ctx, xs) {
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
if (xs[i](ctx))
return true;
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
if (xs[k](ctx))
return true;
}
}
return false;
}),
// ============= RELATIONAL ================
C(symbol_table_1.MolScriptSymbolTable.core.rel.eq, function (ctx, v) { return v[0](ctx) === v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.rel.neq, function (ctx, v) { return v[0](ctx) !== v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.rel.lt, function (ctx, v) { return v[0](ctx) < v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.rel.lte, function (ctx, v) { return v[0](ctx) <= v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.rel.gr, function (ctx, v) { return v[0](ctx) > v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.rel.gre, function (ctx, v) { return v[0](ctx) >= v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.rel.inRange, function (ctx, v) {
var x = v[0](ctx);
return x >= v[1](ctx) && x <= v[2](ctx);
}),
// ============= ARITHMETIC ================
C(symbol_table_1.MolScriptSymbolTable.core.math.add, function (ctx, xs) {
var ret = 0;
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret += xs[i](ctx);
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
ret += xs[k](ctx);
}
}
return ret;
}),
C(symbol_table_1.MolScriptSymbolTable.core.math.sub, function (ctx, xs) {
var ret = 0;
if (typeof xs.length === 'number') {
if (xs.length === 1)
return -xs[0](ctx);
ret = xs[0](ctx) || 0;
for (var i = 1, _i = xs.length; i < _i; i++)
ret -= xs[i](ctx);
}
else {
var keys = Object.keys(xs);
if (keys.length === 1)
return -xs[keys[0]](ctx);
ret = xs[keys[0]](ctx) || 0;
for (var i = 1, _i = keys.length; i < _i; i++)
ret -= xs[keys[i]](ctx);
}
return ret;
}),
C(symbol_table_1.MolScriptSymbolTable.core.math.mult, function (ctx, xs) {
var ret = 1;
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret *= xs[i](ctx);
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
ret *= xs[k](ctx);
}
}
return ret;
}),
C(symbol_table_1.MolScriptSymbolTable.core.math.div, function (ctx, v) { return v[0](ctx) / v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.pow, function (ctx, v) { return Math.pow(v[0](ctx), v[1](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.mod, function (ctx, v) { return v[0](ctx) % v[1](ctx); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.min, function (ctx, xs) {
var ret = Number.POSITIVE_INFINITY;
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret = Math.min(xs[i](ctx), ret);
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
ret = Math.min(xs[k](ctx), ret);
}
}
return ret;
}),
C(symbol_table_1.MolScriptSymbolTable.core.math.max, function (ctx, xs) {
var ret = Number.NEGATIVE_INFINITY;
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret = Math.max(xs[i](ctx), ret);
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
ret = Math.max(xs[k](ctx), ret);
}
}
return ret;
}),
C(symbol_table_1.MolScriptSymbolTable.core.math.floor, function (ctx, v) { return Math.floor(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.ceil, function (ctx, v) { return Math.ceil(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.roundInt, function (ctx, v) { return Math.round(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.abs, function (ctx, v) { return Math.abs(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.sqrt, function (ctx, v) { return Math.sqrt(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.cbrt, function (ctx, v) { return Math.cbrt(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.sin, function (ctx, v) { return Math.sin(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.cos, function (ctx, v) { return Math.cos(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.tan, function (ctx, v) { return Math.tan(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.asin, function (ctx, v) { return Math.asin(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.acos, function (ctx, v) { return Math.acos(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.atan, function (ctx, v) { return Math.atan(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.sinh, function (ctx, v) { return Math.sinh(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.cosh, function (ctx, v) { return Math.cosh(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.tanh, function (ctx, v) { return Math.tanh(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.exp, function (ctx, v) { return Math.exp(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.log, function (ctx, v) { return Math.log(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.log10, function (ctx, v) { return Math.log10(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.math.atan2, function (ctx, v) { return Math.atan2(v[0](ctx), v[1](ctx)); }),
// ============= STRING ================
C(symbol_table_1.MolScriptSymbolTable.core.str.match, function (ctx, v) { return v[0](ctx).test(v[1](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.str.concat, function (ctx, xs) {
var ret = [];
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret.push(xs[i](ctx).toString());
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
ret.push(xs[k](ctx).toString());
}
}
return ret.join('');
}),
// ============= LIST ================
C(symbol_table_1.MolScriptSymbolTable.core.list.getAt, function (ctx, v) { return v[0](ctx)[v[1](ctx)]; }),
C(symbol_table_1.MolScriptSymbolTable.core.list.equal, function (ctx, v) { return (0, array_1.arrayEqual)(v[0](ctx), v[1](ctx)); }),
// ============= SET ================
C(symbol_table_1.MolScriptSymbolTable.core.set.has, function core_set_has(ctx, v) { return v[0](ctx).has(v[1](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.core.set.isSubset, function core_set_isSubset(ctx, v) { return set_1.SetUtils.isSuperset(v[1](ctx), v[0](ctx)); }),
// ============= FLAGS ================
C(symbol_table_1.MolScriptSymbolTable.core.flags.hasAny, function (ctx, v) {
var test = v[1](ctx);
var tested = v[0](ctx);
if (!test)
return !!tested;
return (tested & test) !== 0;
}),
C(symbol_table_1.MolScriptSymbolTable.core.flags.hasAll, function (ctx, v) {
var test = v[1](ctx);
var tested = v[0](ctx);
if (!test)
return !tested;
return (tested & test) === test;
}),
// Structure
// ============= TYPES ================
C(symbol_table_1.MolScriptSymbolTable.structureQuery.type.elementSymbol, function (ctx, v) { return (0, types_1.ElementSymbol)(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.structureQuery.type.atomName, function (ctx, v) { return (0, string_1.upperCaseAny)(v[0](ctx)); }),
C(symbol_table_1.MolScriptSymbolTable.structureQuery.type.bondFlags, function (ctx, xs) {
var ret = 0 /* None */;
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret = bondFlag(ret, xs[i](ctx));
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
ret = bondFlag(ret, xs[k](ctx));
}
}
return ret;
}),
C(symbol_table_1.MolScriptSymbolTable.structureQuery.type.ringFingerprint, function (ctx, xs) { return structure_1.UnitRing.elementFingerprint(getArray(ctx, xs)); }),
C(symbol_table_1.MolScriptSymbolTable.structureQuery.type.secondaryStructureFlags, function (ctx, xs) {
var ret = 0 /* None */;
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret = secondaryStructureFlag(ret, xs[i](ctx));
}
else {
for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
var k = _b[_a];
ret = secondaryStructureFlag(ret, xs[k](ctx));
}
}
return ret;
}),
// TODO:
// C(MolScript.structureQuery.type.entityType, (ctx, v) => StructureRuntime.Common.entityType(v[0](ctx))),
// C(MolScript.structureQuery.type.authResidueId, (ctx, v) => ResidueIdentifier.auth(v[0](ctx), v[1](ctx), v[2] && v[2](ctx))),
// C(MolScript.structureQuery.type.labelResidueId, (ctx, v) => ResidueIdentifier.label(v[0](ctx), v[1](ctx), v[2](ctx), v[3] && v[3](ctx))),
// ============= SLOTS ================
// TODO: slots might not be needed after all: reducer simply pushes/pops current element
// C(MolScript.structureQuery.slot.element, (ctx, _) => ctx_.element),
// C(MolScript.structureQuery.slot.elementSetReduce, (ctx, _) => ctx_.element),
// ============= FILTERS ================
D(symbol_table_1.MolScriptSymbolTable.structureQuery.filter.pick, function (ctx, xs) { return structure_1.Queries.filters.pick(xs[0], xs['test'])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.filter.first, function (ctx, xs) { return structure_1.Queries.filters.first(xs[0])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.filter.withSameAtomProperties, function (ctx, xs) { return structure_1.Queries.filters.withSameAtomProperties(xs[0], xs['source'], xs['property'])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.filter.intersectedBy, function (ctx, xs) { return structure_1.Queries.filters.areIntersectedBy(xs[0], xs['by'])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.filter.within, function (ctx, xs) { return structure_1.Queries.filters.within({
query: xs[0],
target: xs['target'],
minRadius: xs['min-radius'],
maxRadius: xs['max-radius'],
elementRadius: xs['atom-radius'],
invert: xs['invert']
})(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.filter.isConnectedTo, function (ctx, xs) { return structure_1.Queries.filters.isConnectedTo({
query: xs[0],
target: xs['target'],
disjunct: xs['disjunct'],
invert: xs['invert'],
bondTest: xs['bond-test']
})(ctx); }),
// ============= GENERATORS ================
D(symbol_table_1.MolScriptSymbolTable.structureQuery.generator.atomGroups, function structureQuery_generator_atomGroups(ctx, xs) {
return structure_1.Queries.generators.atoms({
entityTest: xs['entity-test'],
chainTest: xs['chain-test'],
residueTest: xs['residue-test'],
atomTest: xs['atom-test'],
groupBy: xs['group-by']
})(ctx);
}),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.generator.all, function structureQuery_generator_all(ctx) { return structure_1.Queries.generators.all(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.generator.empty, function structureQuery_generator_empty(ctx) { return structure_1.Queries.generators.none(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.generator.bondedAtomicPairs, function structureQuery_generator_bondedAtomicPairs(ctx, xs) {
return structure_1.Queries.generators.bondedAtomicPairs(xs && xs[0])(ctx);
}),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.generator.rings, function structureQuery_generator_rings(ctx, xs) {
var _a, _b;
return structure_1.Queries.generators.rings((_a = xs === null || xs === void 0 ? void 0 : xs['fingerprint']) === null || _a === void 0 ? void 0 : _a.call(xs, ctx), (_b = xs === null || xs === void 0 ? void 0 : xs['only-aromatic']) === null || _b === void 0 ? void 0 : _b.call(xs, ctx))(ctx);
}),
// ============= MODIFIERS ================
D(symbol_table_1.MolScriptSymbolTable.structureQuery.modifier.includeSurroundings, function structureQuery_modifier_includeSurroundings(ctx, xs) {
return structure_1.Queries.modifiers.includeSurroundings(xs[0], {
radius: xs['radius'](ctx),
wholeResidues: !!(xs['as-whole-residues'] && xs['as-whole-residues'](ctx)),
elementRadius: xs['atom-radius']
})(ctx);
}),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.modifier.surroundingLigands, function structureQuery_modifier_includeSurroundingLigands(ctx, xs) {
return structure_1.Queries.modifiers.surroundingLigands({
query: xs[0],
radius: xs['radius'](ctx),
includeWater: !!(xs['include-water'] && xs['include-water'](ctx)),
})(ctx);
}),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.modifier.wholeResidues, function structureQuery_modifier_wholeResidues(ctx, xs) { return structure_1.Queries.modifiers.wholeResidues(xs[0])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.modifier.union, function structureQuery_modifier_union(ctx, xs) { return structure_1.Queries.modifiers.union(xs[0])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.modifier.expandProperty, function structureQuery_modifier_expandProperty(ctx, xs) { return structure_1.Queries.modifiers.expandProperty(xs[0], xs['property'])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.modifier.exceptBy, function structureQuery_modifier_exceptBy(ctx, xs) { return structure_1.Queries.modifiers.exceptBy(xs[0], xs['by'])(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.modifier.includeConnected, function structureQuery_modifier_includeConnected(ctx, xs) {
var _a, _b;
return structure_1.Queries.modifiers.includeConnected({
query: xs[0],
bondTest: xs['bond-test'],
wholeResidues: !!(xs['as-whole-residues'] && xs['as-whole-residues'](ctx)),
layerCount: (xs['layer-count'] && xs['layer-count'](ctx)) || 1,
fixedPoint: (_b = (_a = xs['fixed-point']) === null || _a === void 0 ? void 0 : _a.call(xs, ctx)) !== null && _b !== void 0 ? _b : false
})(ctx);
}),
// ============= COMBINATORS ================
D(symbol_table_1.MolScriptSymbolTable.structureQuery.combinator.merge, function (ctx, xs) { return structure_1.Queries.combinators.merge(xs)(ctx); }),
// ============= ATOM PROPERTIES ================
// ~~~ CORE ~~~
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.elementSymbol, atomProp(structure_1.StructureProperties.atom.type_symbol)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.vdw, function (ctx, xs) { return (0, atomic_1.VdwRadius)(structure_1.StructureProperties.atom.type_symbol((xs && xs[0] && xs[0](ctx)) || ctx.element)); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.mass, function (ctx, xs) { return (0, atomic_1.AtomWeight)(structure_1.StructureProperties.atom.type_symbol((xs && xs[0] && xs[0](ctx)) || ctx.element)); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.atomicNumber, function (ctx, xs) { return (0, atomic_1.AtomNumber)(structure_1.StructureProperties.atom.type_symbol((xs && xs[0] && xs[0](ctx)) || ctx.element)); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.x, atomProp(structure_1.StructureProperties.atom.x)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.y, atomProp(structure_1.StructureProperties.atom.y)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.z, atomProp(structure_1.StructureProperties.atom.z)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.sourceIndex, atomProp(structure_1.StructureProperties.atom.sourceIndex)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.operatorName, atomProp(structure_1.StructureProperties.unit.operator_name)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.modelIndex, atomProp(structure_1.StructureProperties.unit.model_index)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.modelLabel, atomProp(structure_1.StructureProperties.unit.model_label)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.core.atomKey, function (ctx, xs) {
var e = (xs && xs[0] && xs[0](ctx)) || ctx.element;
return (0, util_1.cantorPairing)(e.unit.id, e.element);
}),
// TODO:
// D(MolScript.structureQuery.atomProperty.core.bondCount, (ctx, _) => ),
// ~~~ TOPOLOGY ~~~
// TODO
// ~~~ MACROMOLECULAR ~~~
// TODO:
// // identifiers
// labelResidueId: prop((env, v) => ResidueIdentifier.labelOfResidueIndex(env.context.model, getAddress(env, v).residue)),
// authResidueId: prop((env, v) => ResidueIdentifier.authOfResidueIndex(env.context.model, getAddress(env, v).residue)),
// keys
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.residueKey, function (ctx, xs) { return structure_1.StructureElement.residueIndex((xs && xs[0] && xs[0](ctx)) || ctx.element); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.chainKey, function (ctx, xs) { return structure_1.StructureElement.chainIndex((xs && xs[0] && xs[0](ctx)) || ctx.element); }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.entityKey, function (ctx, xs) { return structure_1.StructureElement.entityIndex((xs && xs[0] && xs[0](ctx)) || ctx.element); }),
// mmCIF
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.id, atomProp(structure_1.StructureProperties.atom.id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.isHet, function (ctx, xs) { return structure_1.StructureProperties.residue.group_PDB((xs && xs[0] && xs[0](ctx)) || ctx.element) !== 'ATOM'; }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.label_atom_id, atomProp(structure_1.StructureProperties.atom.label_atom_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.label_alt_id, atomProp(structure_1.StructureProperties.atom.label_alt_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.label_comp_id, atomProp(structure_1.StructureProperties.atom.label_comp_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.label_seq_id, atomProp(structure_1.StructureProperties.residue.label_seq_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.label_asym_id, atomProp(structure_1.StructureProperties.chain.label_asym_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.label_entity_id, atomProp(structure_1.StructureProperties.entity.id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.auth_atom_id, atomProp(structure_1.StructureProperties.atom.auth_atom_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.auth_comp_id, atomProp(structure_1.StructureProperties.atom.auth_comp_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.auth_seq_id, atomProp(structure_1.StructureProperties.residue.auth_seq_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.auth_asym_id, atomProp(structure_1.StructureProperties.chain.auth_asym_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.pdbx_PDB_ins_code, atomProp(structure_1.StructureProperties.residue.pdbx_PDB_ins_code)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.pdbx_formal_charge, atomProp(structure_1.StructureProperties.atom.pdbx_formal_charge)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.occupancy, atomProp(structure_1.StructureProperties.atom.occupancy)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.B_iso_or_equiv, atomProp(structure_1.StructureProperties.atom.B_iso_or_equiv)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.entityType, atomProp(structure_1.StructureProperties.entity.type)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.entitySubtype, atomProp(structure_1.StructureProperties.entity.subtype)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.entityPrdId, atomProp(structure_1.StructureProperties.entity.prd_id)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.entityDescription, atomProp(structure_1.StructureProperties.entity.pdbx_description)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.objectPrimitive, atomProp(structure_1.StructureProperties.unit.object_primitive)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.isNonStandard, atomProp(structure_1.StructureProperties.residue.isNonStandard)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.secondaryStructureKey, atomProp(structure_1.StructureProperties.residue.secondary_structure_key)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.secondaryStructureFlags, atomProp(structure_1.StructureProperties.residue.secondary_structure_type)),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.atomProperty.macromolecular.chemCompType, atomProp(structure_1.StructureProperties.residue.chem_comp_type)),
// ============= BOND PROPERTIES ================
D(symbol_table_1.MolScriptSymbolTable.structureQuery.bondProperty.order, function (ctx, xs) { return ctx.atomicBond.order; }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.bondProperty.flags, function (ctx, xs) { return ctx.atomicBond.type; }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.bondProperty.atomA, function (ctx, xs) { return ctx.atomicBond.a; }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.bondProperty.atomB, function (ctx, xs) { return ctx.atomicBond.b; }),
D(symbol_table_1.MolScriptSymbolTable.structureQuery.bondProperty.length, function (ctx, xs) { return ctx.atomicBond.length; }),
// Internal
D(symbol_table_1.MolScriptSymbolTable.internal.generator.bundleElement, function internal_generator_bundleElement(ctx, xs) { return (0, internal_1.bundleElementImpl)(xs.groupedUnits(ctx), xs.ranges(ctx), xs.set(ctx)); }),
D(symbol_table_1.MolScriptSymbolTable.internal.generator.bundle, function internal_generator_bundle(ctx, xs) { return (0, internal_1.bundleGenerator)(xs.elements(ctx))(ctx); }),
D(symbol_table_1.MolScriptSymbolTable.internal.generator.current, function internal_generator_current(ctx, xs) { return ctx.tryGetCurrentSelection(); }),
];
function atomProp(p) {
return function (ctx, xs) { return p((xs && xs[0] && xs[0](ctx)) || ctx.element); };
}
function bondFlag(current, f) {
return current | (types_1.BondType.isName(f) ? types_1.BondType.fromName(f) : 0 /* None */);
}
function secondaryStructureFlag(current, f) {
switch (f.toLowerCase()) {
case 'helix': return current | 2 /* Helix */;
case 'alpha': return current | 2 /* Helix */ | 4096 /* HelixAlpha */;
case 'pi': return current | 2 /* Helix */ | 32768 /* HelixPi */;
case '310': return current | 2 /* Helix */ | 2048 /* Helix3Ten */;
case 'beta': return current | 4 /* Beta */;
case 'strand': return current | 4 /* Beta */ | 4194304 /* BetaStrand */;
case 'sheet': return current | 4 /* Beta */ | 8388608 /* BetaSheet */;
case 'turn': return current | 16 /* Turn */;
case 'bend': return current | 8 /* Bend */;
case 'coil': return current | 536870912 /* NA */;
default: return current;
}
}
function getArray(ctx, xs) {
var ret = [];
if (!xs)
return ret;
if (typeof xs.length === 'number') {
for (var i = 0, _i = xs.length; i < _i; i++)
ret.push(xs[i](ctx));
}
else {
var keys = Object.keys(xs);
for (var i = 1, _i = keys.length; i < _i; i++)
ret.push(xs[keys[i]](ctx));
}
return ret;
}
(function () {
for (var _a = 0, symbols_1 = symbols; _a < symbols_1.length; _a++) {
var s = symbols_1[_a];
base_1.DefaultQueryRuntimeTable.addSymbol(s);
}
})();
//# sourceMappingURL=table.js.map |
FHDortmund/Termserver | src/TermBrowser/TermBrowser/src/main/java/de/fhdo/collaboration/db/classes/Statusrel.java | package de.fhdo.collaboration.db.classes;
// Generated 30.06.2015 09:32:45 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* Statusrel generated by hbm2java
*/
@Entity
@Table(name="statusrel"
)
public class Statusrel implements java.io.Serializable {
private Long id;
private Action action;
private Status statusByStatusIdTo;
private Status statusByStatusIdFrom;
private Set<Role> roles = new HashSet<Role>(0);
public Statusrel() {
}
public Statusrel(Status statusByStatusIdTo, Status statusByStatusIdFrom) {
this.statusByStatusIdTo = statusByStatusIdTo;
this.statusByStatusIdFrom = statusByStatusIdFrom;
}
public Statusrel(Action action, Status statusByStatusIdTo, Status statusByStatusIdFrom, Set<Role> roles) {
this.action = action;
this.statusByStatusIdTo = statusByStatusIdTo;
this.statusByStatusIdFrom = statusByStatusIdFrom;
this.roles = roles;
}
@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="id", unique=true, nullable=false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="actionId")
public Action getAction() {
return this.action;
}
public void setAction(Action action) {
this.action = action;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="statusIdTo", nullable=false)
public Status getStatusByStatusIdTo() {
return this.statusByStatusIdTo;
}
public void setStatusByStatusIdTo(Status statusByStatusIdTo) {
this.statusByStatusIdTo = statusByStatusIdTo;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="statusIdFrom", nullable=false)
public Status getStatusByStatusIdFrom() {
return this.statusByStatusIdFrom;
}
public void setStatusByStatusIdFrom(Status statusByStatusIdFrom) {
this.statusByStatusIdFrom = statusByStatusIdFrom;
}
@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="role2action", joinColumns = {
@JoinColumn(name="statusRelId", nullable=false, updatable=false) }, inverseJoinColumns = {
@JoinColumn(name="roleId", nullable=false, updatable=false) })
public Set<Role> getRoles() {
return this.roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
|
minerba/c | kubernetes/unit-test/test_extensions_v1beta1_http_ingress_path.c | #ifndef extensions_v1beta1_http_ingress_path_TEST
#define extensions_v1beta1_http_ingress_path_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define extensions_v1beta1_http_ingress_path_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/extensions_v1beta1_http_ingress_path.h"
extensions_v1beta1_http_ingress_path_t* instantiate_extensions_v1beta1_http_ingress_path(int include_optional);
#include "test_extensions_v1beta1_ingress_backend.c"
extensions_v1beta1_http_ingress_path_t* instantiate_extensions_v1beta1_http_ingress_path(int include_optional) {
extensions_v1beta1_http_ingress_path_t* extensions_v1beta1_http_ingress_path = NULL;
if (include_optional) {
extensions_v1beta1_http_ingress_path = extensions_v1beta1_http_ingress_path_create(
// false, not to have infinite recursion
instantiate_extensions_v1beta1_ingress_backend(0),
"0"
);
} else {
extensions_v1beta1_http_ingress_path = extensions_v1beta1_http_ingress_path_create(
NULL,
"0"
);
}
return extensions_v1beta1_http_ingress_path;
}
#ifdef extensions_v1beta1_http_ingress_path_MAIN
void test_extensions_v1beta1_http_ingress_path(int include_optional) {
extensions_v1beta1_http_ingress_path_t* extensions_v1beta1_http_ingress_path_1 = instantiate_extensions_v1beta1_http_ingress_path(include_optional);
cJSON* jsonextensions_v1beta1_http_ingress_path_1 = extensions_v1beta1_http_ingress_path_convertToJSON(extensions_v1beta1_http_ingress_path_1);
printf("extensions_v1beta1_http_ingress_path :\n%s\n", cJSON_Print(jsonextensions_v1beta1_http_ingress_path_1));
extensions_v1beta1_http_ingress_path_t* extensions_v1beta1_http_ingress_path_2 = extensions_v1beta1_http_ingress_path_parseFromJSON(jsonextensions_v1beta1_http_ingress_path_1);
cJSON* jsonextensions_v1beta1_http_ingress_path_2 = extensions_v1beta1_http_ingress_path_convertToJSON(extensions_v1beta1_http_ingress_path_2);
printf("repeating extensions_v1beta1_http_ingress_path:\n%s\n", cJSON_Print(jsonextensions_v1beta1_http_ingress_path_2));
}
int main() {
test_extensions_v1beta1_http_ingress_path(1);
test_extensions_v1beta1_http_ingress_path(0);
printf("Hello world \n");
return 0;
}
#endif // extensions_v1beta1_http_ingress_path_MAIN
#endif // extensions_v1beta1_http_ingress_path_TEST
|
eikeschumann971/kspp | include/kspp/serdes/avro_serdes.h | #include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/string_generator.hpp>
#include <ostream>
#include <istream>
#include <vector>
#include <typeinfo>
#include <tuple>
#include <avro/Encoder.hh>
#include <avro/Decoder.hh>
#include <avro/Compiler.hh>
#include <avro/Generic.hh>
#include <avro/Specific.hh>
#include <glog/logging.h>
#include <kspp/avro/generic_avro.h>
#include <kspp/avro/avro_schema_registry.h>
#include <kspp/avro/avro_utils.h>
#pragma once
namespace kspp {
class avro_serdes
{
template<typename T> struct fake_dependency : public std::false_type {};
public:
avro_serdes(std::shared_ptr<avro_schema_registry> registry, bool relaxed_parsing)
: _registry(registry)
, _relaxed_parsing(relaxed_parsing){
}
static std::string name() { return "kspp::avro"; }
template<class T>
int32_t register_schema(std::string name, const T& dummy){
int32_t schema_id=0;
std::shared_ptr<const avro::ValidSchema> not_used;
std::tie(schema_id, not_used) = _put_schema(name, avro_utils::avro_utils<T>::schema_as_string(dummy));
return schema_id;
}
/*
* confluent avro encoded data
* write avro format
* confluent framing marker 0x00 (binary)
* schema id from registry (htonl - encoded)
* avro encoded payload
*/
template<class T>
size_t encode(const T& src, std::ostream& dst) {
static int32_t schema_id = -1;
if (schema_id < 0) {
int32_t res = _registry->put_schema(src.avro_schema_name(), src.valid_schema());
if (res >= 0)
schema_id = res;
else
return 0;
}
return encode(schema_id, src, dst);
}
/*
* confluent avro encoded data
* write avro format
* confluent framing marker 0x00 (binary)
* schema id from registry (htonl - encoded)
* avro encoded payload
*/
template<class T>
size_t encode(const std::string& name, const T& src, std::ostream& dst) {
static int32_t schema_id = -1;
if (schema_id < 0) {
int32_t res = _registry->put_schema(name, src.valid_schema());
if (res >= 0)
schema_id = res;
else
return 0;
}
return encode(schema_id, src, dst);
}
/*
* confluent avro encoded data
* write avro format
* confluent framing marker 0x00 (binary)
* schema id from registry (htonl - encoded)
* avro encoded payload
*/
template<class T>
size_t encode(int32_t schema_id, const T& src, std::ostream& dst) {
/* write framing */
char zero = 0x00;
dst.write(&zero, 1);
int32_t encoded_schema_id = htonl(schema_id);
dst.write((const char*) &encoded_schema_id, 4);
auto bin_os = avro::memoryOutputStream();
avro::EncoderPtr bin_encoder = avro::binaryEncoder();
bin_encoder->init(*bin_os.get());
avro::encode(*bin_encoder, src);
bin_encoder->flush(); /* push back unused characters to the output stream again, otherwise content_length will be a multiple of 4096 */
//get the data from the internals of avro stream
auto v = avro::snapshot(*bin_os.get());
size_t avro_size = v->size();
if (avro_size) {
dst.write((const char*) v->data(), avro_size);
return avro_size + 5;
}
return 5; // this is probably wrong - is there a 0 size avro message???
}
/*
* read confluent avro format
* confluent framing marker 0x00 (binary)
* schema id from registry (htonl - encoded)
* avro encoded payload
*/
template<class T>
size_t decode(const char* payload, size_t size, T& dst) {
static int32_t schema_id = -1;
if (schema_id < 0) {
int32_t res = _registry->put_schema(dst.avro_schema_name(), dst.valid_schema());
if (res >= 0)
schema_id = res;
else
return 0;
}
return decode(schema_id, dst.valid_schema(), payload, size, dst);
}
template<class T>
size_t decode(int32_t expected_schema_id, std::shared_ptr<const avro::ValidSchema> schema, const char* payload, size_t size, T& dst) {
if (expected_schema_id < 0 || schema == nullptr || size < 5 || payload[0])
return 0;
/* read framing */
int32_t encoded_schema_id = -1;
memcpy(&encoded_schema_id, &payload[1], 4);
int32_t schema_id = ntohl(encoded_schema_id);
if (expected_schema_id != schema_id) {
if (!_relaxed_parsing) {
LOG(ERROR) << "expected schema id " << expected_schema_id << ", actual: " << schema_id;
return 0;
}
}
try {
auto bin_is = avro::memoryInputStream((const uint8_t *) payload + 5, size - 5);
avro::DecoderPtr bin_decoder = avro::binaryDecoder();
bin_decoder->init(*bin_is);
avro::decode(*bin_decoder, dst);
return bin_is->byteCount() + 5;
}
catch (const avro::Exception &e) {
LOG(ERROR) << "Avro deserialization failed: " << e.what();
return 0;
}
return 0; // should never get here
}
private:
std::tuple<int32_t, std::shared_ptr<const avro::ValidSchema>> _put_schema(std::string schema_name, std::string schema_as_string) {
auto valid_schema = std::make_shared<const avro::ValidSchema>(avro::compileJsonSchemaFromString(schema_as_string));
auto schema_id = _registry->put_schema(schema_name, valid_schema);
return std::make_tuple(schema_id, valid_schema);
}
std::shared_ptr<avro_schema_registry> _registry;
bool _relaxed_parsing=false;
};
template<> inline size_t avro_serdes::encode(const std::string& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, src, dst);
std::tie(schema_id, not_used) = _put_schema("string", "{\"type\":\"string\"}");
if (schema_id > 0)
return encode(schema_id, src, dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, std::string& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
if (schema_id>0)
return decode(schema_id, valid_schema, payload, size, dst);
std::tie(schema_id, valid_schema) = _put_schema("string", "{\"type\":\"string\"}");
if (schema_id > 0)
return decode(schema_id, valid_schema, payload, size, dst);
else
return 0;
}
template<> inline size_t avro_serdes::encode(const int64_t& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, src, dst);
std::tie(schema_id, not_used) = _put_schema("long", "{\"type\":\"long\"}");
if (schema_id > 0)
return encode(schema_id, src, dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, int64_t& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
if (schema_id>0)
return decode(schema_id, valid_schema, payload, size, dst);
std::tie(schema_id, valid_schema) = _put_schema("long", "{\"type\":\"long\"}");
if (schema_id > 0)
return decode(schema_id, valid_schema, payload, size, dst);
else
return 0;
}
template<> inline size_t avro_serdes::encode(const int32_t& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, src, dst);
std::tie(schema_id, not_used) = _put_schema("int", "{\"type\":\"int\"}");
if (schema_id > 0)
return encode(schema_id, src, dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, int32_t& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
if (schema_id>0)
return decode(schema_id, valid_schema, payload, size, dst);
std::tie(schema_id, valid_schema) = _put_schema("int", "{\"type\":\"int\"}");
if (schema_id > 0)
return decode(schema_id, valid_schema, payload, size, dst);
else
return 0;
}
template<> inline size_t avro_serdes::encode(const bool& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, src, dst);
std::tie(schema_id, not_used) = _put_schema("boolean", "{\"type\":\"boolean\"}");
if (schema_id > 0)
return encode(schema_id, src, dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, bool& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
if (schema_id>0)
return decode(schema_id, valid_schema, payload, size, dst);
std::tie(schema_id, valid_schema) = _put_schema("boolean", "{\"type\":\"boolean\"}");
if (schema_id > 0)
return decode(schema_id, valid_schema, payload, size, dst);
else
return 0;
}
template<> inline size_t avro_serdes::encode(const float& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, src, dst);
std::tie(schema_id, not_used) = _put_schema("float", "{\"type\":\"float\"}");
if (schema_id > 0)
return encode(schema_id, src, dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, float& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
if (schema_id>0)
return decode(schema_id, valid_schema, payload, size, dst);
std::tie(schema_id, valid_schema) = _put_schema("float", "{\"type\":\"float\"}");
if (schema_id > 0)
return decode(schema_id, valid_schema, payload, size, dst);
else
return 0;
}
template<> inline size_t avro_serdes::encode(const double& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, src, dst);
std::tie(schema_id, not_used) = _put_schema("double", "{\"type\":\"double\"}");
if (schema_id > 0)
return encode(schema_id, src, dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, double& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
if (schema_id>0)
return decode(schema_id, valid_schema, payload, size, dst);
std::tie(schema_id, valid_schema) = _put_schema("double", "{\"type\":\"double\"}");
if (schema_id > 0)
return decode(schema_id, valid_schema, payload, size, dst);
else
return 0;
}
template<> inline size_t avro_serdes::encode(const std::vector<uint8_t>& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, src, dst);
std::tie(schema_id, not_used) = _put_schema("bytes", "{\"type\":\"bytes\"}");
if (schema_id > 0)
return encode(schema_id, src, dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, std::vector<uint8_t>& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
if (schema_id>0)
return decode(schema_id, valid_schema, payload, size, dst);
std::tie(schema_id, valid_schema) = _put_schema("bytes", "{\"type\":\"bytes\"}");
if (schema_id > 0)
return decode(schema_id, valid_schema, payload, size, dst);
else
return 0;
}
template<> inline size_t avro_serdes::encode(const boost::uuids::uuid& src, std::ostream& dst) {
static int32_t schema_id = -1;
std::shared_ptr<const avro::ValidSchema> not_used;
if (schema_id > 0)
return encode(schema_id, boost::uuids::to_string(src), dst);
std::tie(schema_id, not_used) = _put_schema("uuid", "{\"type\":\"string\"}");
if (schema_id > 0)
return encode(schema_id, boost::uuids::to_string(src), dst);
else
return 0;
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, boost::uuids::uuid& dst) {
static int32_t schema_id = -1;
static std::shared_ptr<const avro::ValidSchema> valid_schema; // this means we never free memory from used schemas???
static boost::uuids::string_generator gen;
if (schema_id > 0) {
std::string s;
size_t sz = decode(schema_id, valid_schema, payload, size, s);
try {
dst = gen(s);
return sz;
}
catch (...) {
//log something
return 0;
}
}
std::tie(schema_id, valid_schema) = _put_schema("uuid", "{\"type\":\"string\"}");
if (schema_id > 0) {
std::string s;
size_t sz = decode(schema_id, valid_schema, payload, size, s);
try {
dst = gen(s);
return sz;
}
catch (...) {
//log something
return 0;
}
} else {
return 0;
}
}
template<> inline size_t avro_serdes::decode(const char* payload, size_t size, kspp::generic_avro& dst) {
if (size < 5 || payload[0])
return 0;
/* read framing */
int32_t encoded_schema_id = -1;
memcpy(&encoded_schema_id, &payload[1], 4);
int32_t schema_id = ntohl(encoded_schema_id);
// this should net be in the stream - not possible to decode
if (schema_id<0) {
LOG(ERROR) << "schema id invalid: " << schema_id;
return 0;
}
auto validSchema = _registry->get_schema(schema_id);
if (validSchema == nullptr)
return 0;
try {
auto bin_is = avro::memoryInputStream((const uint8_t *) payload + 5, size - 5);
avro::DecoderPtr bin_decoder = avro::validatingDecoder(*validSchema, avro::binaryDecoder());
dst.create(validSchema, schema_id);
bin_decoder->init(*bin_is);
avro::decode(*bin_decoder, *dst.generic_datum());
return bin_is->byteCount() + 5;
}
catch (const avro::Exception &e) {
LOG(ERROR) << "avro deserialization failed: " << e.what();
return 0;
}
return 0; // should never get here
}
template<> inline size_t avro_serdes::encode(const kspp::generic_avro& src, std::ostream& dst) {
assert(src.schema_id()>=0);
return encode(src.schema_id(), *src.generic_datum(), dst);
}
}
|
rzats/enso | engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala | <reponame>rzats/enso
package org.enso.compiler
import java.io.StringReader
import com.oracle.truffle.api.TruffleFile
import com.oracle.truffle.api.source.Source
import org.enso.compiler.codegen.{AstToIR, IRToTruffle}
import org.enso.compiler.core.IR
import org.enso.compiler.core.IR.{Expression, Module}
import org.enso.compiler.pass.IRPass
import org.enso.compiler.pass.analyse.ApplicationSaturation
import org.enso.compiler.pass.desugar.{LiftSpecialOperators, OperatorToFunction}
import org.enso.flexer.Reader
import org.enso.interpreter.Language
import org.enso.interpreter.node.{ExpressionNode => RuntimeExpression}
import org.enso.interpreter.runtime.Context
import org.enso.interpreter.runtime.error.ModuleDoesNotExistException
import org.enso.interpreter.runtime.scope.{
LocalScope,
ModuleScope,
TopLevelScope
}
import org.enso.polyglot.LanguageInfo
import org.enso.syntax.text.{AST, Parser}
/**
* This class encapsulates the static transformation processes that take place
* on source code, including parsing, desugaring, type-checking, static
* analysis, and optimisation.
*/
class Compiler(
val language: Language,
val topScope: TopLevelScope,
val context: Context
) {
/** A list of the compiler phases, in the order they should be run. */
val compilerPhaseOrdering: List[IRPass] = List(
LiftSpecialOperators,
OperatorToFunction,
ApplicationSaturation()
)
/**
* Processes the provided language sources, registering any bindings in the
* given scope.
*
* @param source the source code to be processed
* @param scope the scope into which new bindings are registered
* @return an interpreter node whose execution corresponds to the top-level
* executable functionality in the module corresponding to `source`.
*/
def run(source: Source, scope: ModuleScope): Unit = {
val parsedAST = parse(source)
val expr = generateIR(parsedAST)
val compilerOutput = runCompilerPhases(expr)
truffleCodegen(compilerOutput, source, scope)
}
/**
* Processes the language sources in the provided file, registering any
* bindings in the given scope.
*
* @param file the file containing the source code
* @param scope the scope into which new bindings are registered
* @return an interpreter node whose execution corresponds to the top-level
* executable functionality in the module corresponding to `source`.
*/
def run(file: TruffleFile, scope: ModuleScope): Unit = {
run(Source.newBuilder(LanguageInfo.ID, file).build, scope)
}
/**
* Processes the provided language sources, registering their bindings in a
* new scope.
*
* @param source the source code to be processed
* @return an interpreter node whose execution corresponds to the top-level
* executable functionality in the module corresponding to `source`.
*/
def run(source: Source, moduleName: String): Unit = {
run(source, context.createScope(moduleName))
}
/**
* Processes the language sources in the provided file, registering any
* bindings in a new scope.
*
* @param file the file containing the source code
* @return an interpreter node whose execution corresponds to the top-level
* executable functionality in the module corresponding to `source`.
*/
def run(file: TruffleFile, moduleName: String): Unit = {
run(Source.newBuilder(LanguageInfo.ID, file).build, moduleName)
}
/**
* Processes the language source, interpreting it as an expression.
* Processes the source in the context of given local and module scopes.
*
* @param srcString string representing the expression to process
* @param localScope local scope to process the source in
* @param moduleScope module scope to process the source in
* @return an expression node representing the parsed and analyzed source
*/
def runInline(
srcString: String,
localScope: LocalScope,
moduleScope: ModuleScope
): Option[RuntimeExpression] = {
val source = Source
.newBuilder(
LanguageInfo.ID,
new StringReader(srcString),
"<interactive_source>"
)
.build()
val parsed: AST = parse(source)
generateIRInline(parsed).flatMap { ir =>
Some({
val compilerOutput = runCompilerPhasesInline(ir)
truffleCodegenInline(
compilerOutput,
source,
moduleScope,
localScope
)
})
}
}
/**
* Finds and processes a language source by its qualified name.
*
* The results of this operation are cached internally so we do not need to
* process the same source file multiple times.
*
* @param qualifiedName the qualified name of the module
* @return the scope containing all definitions in the requested module
*/
def requestProcess(qualifiedName: String): ModuleScope = {
val module = topScope.getModule(qualifiedName)
if (module.isPresent) {
module.get().getScope(context)
} else {
throw new ModuleDoesNotExistException(qualifiedName)
}
}
/**
* Parses the provided language sources.
*
* @param source the code to parse
* @return an AST representation of `source`
*/
def parse(source: Source): AST = {
val parser: Parser = Parser()
val unresolvedAST: AST.Module =
parser.run(source.getCharacters.toString)
val resolvedAST: AST.Module = parser.dropMacroMeta(unresolvedAST)
resolvedAST
}
/**
* Lowers the input AST to the compiler's high-level intermediate
* representation.
*
* @param sourceAST the parser AST input
* @return an IR representation of the program represented by `sourceAST`
*/
def generateIR(sourceAST: AST): Module =
AstToIR.translate(sourceAST)
/**
* Lowers the input AST to the compiler's high-level intermediate
* representation.
*
* @param sourceAST the parser AST representing the program source
* @return an IR representation of the program represented by `sourceAST`
*/
def generateIRInline(sourceAST: AST): Option[Expression] =
AstToIR.translateInline(sourceAST)
/** Runs the various compiler passes.
*
* @param ir the compiler intermediate representation to transform
* @return the output result of the
*/
def runCompilerPhases(ir: IR.Module): IR.Module = {
compilerPhaseOrdering.foldLeft(ir)(
(intermediateIR, pass) => pass.runModule(intermediateIR)
)
}
/** Runs the various compiler passes in an inline context.
*
* @param ir the compiler intermediate representation to transform
* @return the output result of the
*/
def runCompilerPhasesInline(ir: IR.Expression): IR.Expression = {
compilerPhaseOrdering.foldLeft(ir)(
(intermediateIR, pass) => pass.runExpression(intermediateIR)
)
}
/** Generates code for the truffle interpreter.
*
* @param ir the program to translate
* @param source the source code of the program represented by `ir`
* @param scope the module scope in which the code is to be generated
*/
def truffleCodegen(
ir: IR.Module,
source: Source,
scope: ModuleScope
): Unit = {
new IRToTruffle(language, source, scope).run(ir)
}
/** Generates code for the truffle interpreter in an inline context.
*
* @param ir the prorgam to translate
* @param source the source code of the program represented by `ir`
* @param moduleScope the module scope in which the code is to be generated
* @param localScope the local scope in which the inline code is to be
* located
* @return the runtime representation of the program represented by `ir`
*/
def truffleCodegenInline(
ir: IR.Expression,
source: Source,
moduleScope: ModuleScope,
localScope: LocalScope
): RuntimeExpression = {
new IRToTruffle(this.language, source, moduleScope)
.runInline(ir, localScope, "<inline_source>")
}
}
|
beckje01/ratpack | ratpack-core/src/main/java/ratpack/health/HealthCheckResults.java | <reponame>beckje01/ratpack
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ratpack.health;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
/**
* A value type representing the result of running multiple health checks.
*
* @see ratpack.health.HealthCheckHandler
*/
public class HealthCheckResults {
private final ImmutableSortedMap<String, HealthCheck.Result> results;
private final static HealthCheckResults EMPTY = new HealthCheckResults(ImmutableSortedMap.of());
private final boolean unhealthy;
/**
* Empty results.
*
* @return empty results.
* @since 1.5
*/
public static HealthCheckResults empty() {
return EMPTY;
}
/**
* Constructor.
*
* @param results the results
*/
public HealthCheckResults(ImmutableSortedMap<String, HealthCheck.Result> results) {
this.results = results;
this.unhealthy = Iterables.any(results.values(), Predicates.not(HealthCheck.Result::isHealthy));
}
/**
* The results.
*
* @return the results
*/
public ImmutableSortedMap<String, HealthCheck.Result> getResults() {
return results;
}
/**
* Whether any result is unhealthy.
*
* @return whether any result is unhealthy
* @since 1.5
*/
public boolean isUnhealthy() {
return unhealthy;
}
/**
* Writes a string representation of the results to the given writer.
* <p>
* This object's {@link #toString()} provides this representation as a string.
*
* @param writer the writer to write to.
* @throws IOException any thrown by {@code writer}
* @since 1.5
*/
public void writeTo(Writer writer) throws IOException {
boolean first = true;
for (Map.Entry<String, HealthCheck.Result> entry : results.entrySet()) {
if (first) {
first = false;
} else {
writer.write("\n");
}
String name = entry.getKey();
HealthCheck.Result result = entry.getValue();
writer.append(name).append(" : ").append(result.isHealthy() ? "HEALTHY" : "UNHEALTHY");
String message = result.getMessage();
if (message != null) {
writer.append(" [").append(message).append("]");
}
Throwable error = result.getError();
if (error != null) {
writer.append(" [").append(error.toString()).append("]");
}
}
}
/**
* Provides a string representation of the results.
*
* @return a string representation of the results.
* @since 1.5
*/
@Override
public String toString() {
StringWriter stringWriter = new StringWriter();
try {
writeTo(stringWriter);
} catch (IOException e) {
return "HealthCheckResults";
}
return stringWriter.toString();
}
}
|
fsancheztemprano/chess-lite | apps/api/src/main/java/dev/kurama/api/core/hateoas/processor/UserModelProcessor.java | package dev.kurama.api.core.hateoas.processor;
import static dev.kurama.api.core.authority.UserAuthority.PROFILE_DELETE;
import static dev.kurama.api.core.authority.UserAuthority.PROFILE_READ;
import static dev.kurama.api.core.authority.UserAuthority.PROFILE_UPDATE;
import static dev.kurama.api.core.authority.UserAuthority.USER_DELETE;
import static dev.kurama.api.core.authority.UserAuthority.USER_READ;
import static dev.kurama.api.core.authority.UserAuthority.USER_UPDATE;
import static dev.kurama.api.core.authority.UserAuthority.USER_UPDATE_AUTHORITIES;
import static dev.kurama.api.core.authority.UserAuthority.USER_UPDATE_ROLE;
import static dev.kurama.api.core.authority.UserPreferencesAuthority.USER_PREFERENCES_READ;
import static dev.kurama.api.core.hateoas.relations.HateoasRelations.SELF;
import static dev.kurama.api.core.hateoas.relations.UserRelations.USERS_REL;
import static dev.kurama.api.core.hateoas.relations.UserRelations.USER_PREFERENCES_REL;
import static dev.kurama.api.core.utility.AuthorityUtils.hasAuthority;
import static org.springframework.hateoas.mediatype.Affordances.of;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.afford;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
import dev.kurama.api.core.hateoas.model.UserModel;
import dev.kurama.api.core.hateoas.relations.HateoasRelations;
import dev.kurama.api.core.rest.UserController;
import dev.kurama.api.core.rest.UserPreferencesController;
import dev.kurama.api.core.rest.UserProfileController;
import dev.kurama.api.core.utility.AuthorityUtils;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.hateoas.Affordance;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
@RequiredArgsConstructor
@Component
public class UserModelProcessor extends DomainModelProcessor<UserModel> {
@NonNull
UserPreferencesModelProcessor userPreferencesModelProcessor;
@Override
protected Class<UserController> getClazz() {
return UserController.class;
}
@Override
public @NonNull UserModel process(@NonNull UserModel entity) {
boolean isCurrentUser = AuthorityUtils.isCurrentUsername(entity.getUsername());
boolean canUpdateOwnProfile = hasAuthority(PROFILE_UPDATE);
userPreferencesModelProcessor.process(entity.getUserPreferences());
return entity
.add(getModelSelfLink(entity.getId()))
.mapLinkIf(isCurrentUser && !hasAuthority(USER_READ) && hasAuthority(PROFILE_READ),
LinkRelation.of(SELF),
link -> getCurrentUserSelfLink())
.addIf(hasAuthority(USER_READ), this::getParentLink)
.add(getPreferencesLink(entity.getUserPreferences().getId()))
.mapLinkIf(isCurrentUser && !hasAuthority(USER_PREFERENCES_READ) && hasAuthority(PROFILE_READ),
LinkRelation.of(USER_PREFERENCES_REL),
link -> getCurrentUserPreferencesSelfLink())
.mapLinkIf(hasAuthority(USER_DELETE),
LinkRelation.of(SELF),
link -> link.andAffordance(getDeleteAffordance(entity.getId())))
.mapLinkIf(hasAuthority(USER_UPDATE),
LinkRelation.of(SELF),
link -> link.andAffordance(getUpdateAffordance(entity.getId())))
.mapLinkIf(hasAuthority(USER_UPDATE_ROLE),
LinkRelation.of(SELF),
link -> link.andAffordance(getUpdateRoleAffordance(entity.getId())))
.mapLinkIf(hasAuthority(USER_UPDATE_AUTHORITIES),
LinkRelation.of(SELF),
link -> link.andAffordance(getUpdateAuthoritiesAffordance(entity.getId())))
.mapLinkIf(hasAuthority(USER_UPDATE),
LinkRelation.of(SELF),
link -> link.andAffordance(getSendActivationTokenAffordance(entity.getId())))
.mapLinkIf((isCurrentUser && canUpdateOwnProfile),
LinkRelation.of(SELF),
link -> link.andAffordance(getUpdateProfileAffordance()))
.mapLinkIf((isCurrentUser && canUpdateOwnProfile),
LinkRelation.of(SELF),
link -> link.andAffordance(getChangePasswordAffordance()))
.mapLinkIf((isCurrentUser && canUpdateOwnProfile),
LinkRelation.of(SELF),
link -> link.andAffordance(getUploadAvatarAffordance()))
.mapLinkIf((isCurrentUser && hasAuthority(PROFILE_DELETE)),
LinkRelation.of(SELF),
link -> link.andAffordance(getDeleteProfileAffordance()))
;
}
@SneakyThrows
@Override
public WebMvcLinkBuilder getSelfLink(String id) {
return linkTo(methodOn(getClazz()).get(id));
}
private @NonNull
Link getParentLink() {
return linkTo(methodOn(getClazz()).getAll(null, null)).withRel(USERS_REL);
}
@SneakyThrows
public Link getCurrentUserSelfLink() {
return of(linkTo(methodOn(UserProfileController.class).get()).withSelfRel()).afford(HttpMethod.HEAD)
.withName(HateoasRelations.DEFAULT).toLink();
}
@SneakyThrows
private Link getPreferencesLink(String userPreferencesId) {
return linkTo(methodOn(UserPreferencesController.class).get(userPreferencesId)).withRel(USER_PREFERENCES_REL);
}
public Link getCurrentUserPreferencesSelfLink() {
return linkTo(methodOn(UserProfileController.class).getPreferences()).withRel(USER_PREFERENCES_REL);
}
@SneakyThrows
private @NonNull Affordance getUpdateAffordance(String username) {
return afford(methodOn(getClazz()).update(username, null));
}
@SneakyThrows
private @NonNull Affordance getUpdateRoleAffordance(String username) {
return afford(methodOn(getClazz()).updateRole(username, null));
}
@SneakyThrows
private @NonNull Affordance getUpdateAuthoritiesAffordance(String username) {
return afford(methodOn(getClazz()).updateAuthorities(username, null));
}
@SneakyThrows
private @NonNull Affordance getDeleteAffordance(String userId) {
return afford(methodOn(getClazz()).delete(userId));
}
@SneakyThrows
private @NonNull Affordance getSendActivationTokenAffordance(String userId) {
return afford(methodOn(getClazz()).requestActivationToken(userId));
}
@SneakyThrows
private @NonNull Affordance getUpdateProfileAffordance() {
return afford(methodOn(UserProfileController.class).updateProfile(null));
}
@SneakyThrows
private @NonNull Affordance getChangePasswordAffordance() {
return afford(methodOn(UserProfileController.class).changePassword(null));
}
@SneakyThrows
private @NonNull Affordance getUploadAvatarAffordance() {
return afford(methodOn(UserProfileController.class).uploadAvatar(null));
}
@SneakyThrows
private @NonNull Affordance getDeleteProfileAffordance() {
return afford(methodOn(UserProfileController.class).deleteProfile());
}
}
|
zi-NaN/algorithm_exercise | google questions/20191a_alien.py | from collections import Counter
class Node:
def __init__(self, val, child=None):
self.val = val
self.child = child
def alien(words):
# as we use stdin to read in word, it is assumed that len(any word) > 0
if not words:
return 0
# end of words with max frequency
end = [word[-1] for word in words]
counter = Counter(end)
root = Node(counter.most_common(1)[0][0])
trie =
|
BeiJiaan/ace | ACEXML/common/StrCharStream.cpp | <reponame>BeiJiaan/ace
// $Id$
#include "ACEXML/common/StrCharStream.h"
#include "ACEXML/common/Encoding.h"
#include "ace/ACE.h"
#include "ace/Log_Msg.h"
#include "ace/OS_NS_string.h"
ACEXML_StrCharStream::ACEXML_StrCharStream (void)
: start_ (0), ptr_ (0), end_ (0), encoding_ (0), name_ (0)
{
}
ACEXML_StrCharStream::~ACEXML_StrCharStream (void)
{
this->close();
}
int
ACEXML_StrCharStream::open (const ACEXML_Char *str, const ACEXML_Char* name)
{
if (str != 0 && name != 0)
{
delete [] this->start_;
if ((this->start_ = ACE::strnew (str)) == 0)
return -1;
delete [] this->name_;
if ((this->name_ = ACE::strnew (name)) == 0)
return -1;
this->ptr_ = this->start_;
this->end_ = this->start_ + ACE_OS::strlen (this->start_);
return this->determine_encoding();
}
return -1; // Invalid string passed.
}
int
ACEXML_StrCharStream::available (void)
{
if (this->start_ != 0)
return static_cast<int> (this->end_ - this->start_); // @@ Will this work on all platforms?
return -1;
}
int
ACEXML_StrCharStream::close (void)
{
delete[] this->start_;
delete[] this->encoding_;
this->encoding_ = 0;
delete[] this->name_;
this->name_ = 0;
this->start_ = this->ptr_ = this->end_ = 0;
return 0;
}
int
ACEXML_StrCharStream::determine_encoding (void)
{
if (this->start_ == 0)
return -1;
char input[4] = {0,0,0,0};
char* sptr = (char*)this->start_;
int i = 0;
for ( ; i < 4 && sptr != (char*)this->end_; ++sptr, ++i)
input[i] = *sptr;
const ACEXML_Char* temp = ACEXML_Encoding::get_encoding (input);
if (!temp)
return -1;
else
{
delete [] this->encoding_;
this->encoding_ = ACE::strnew (temp);
// ACE_DEBUG ((LM_DEBUG, "String's encoding is %s\n", this->encoding_));
}
return 0;
}
void
ACEXML_StrCharStream::rewind (void)
{
this->ptr_ = this->start_;
this->determine_encoding();
}
int
ACEXML_StrCharStream::get (ACEXML_Char& ch)
{
if (this->start_ != 0 && this->ptr_ != this->end_)
{
ch = *this->ptr_++;
return 0;
}
return -1;
}
int
ACEXML_StrCharStream::read (ACEXML_Char *str, size_t len)
{
if (this->start_ != 0 &&
this->ptr_ != this->end_)
{
if (len * sizeof (ACEXML_Char) > (size_t) (this->end_ - this->ptr_))
len = this->end_ - this->ptr_;
ACE_OS::strncpy (str, this->ptr_, len);
this->ptr_ += len;
return static_cast<int> (len);
}
return 0;
}
int
ACEXML_StrCharStream::peek (void)
{
if (this->start_ != 0 && this->ptr_ != this->end_)
return *this->ptr_;
return -1;
}
const ACEXML_Char*
ACEXML_StrCharStream::getEncoding (void)
{
return this->encoding_;
}
const ACEXML_Char*
ACEXML_StrCharStream::getSystemId(void)
{
return this->name_;
}
|
echothreellc/echothree | src/java/com/echothree/model/control/associate/server/transfer/AssociateReferralTransferCache.java | <filename>src/java/com/echothree/model/control/associate/server/transfer/AssociateReferralTransferCache.java<gh_stars>1-10
// --------------------------------------------------------------------------------
// Copyright 2002-2021 Echo Three, 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.
// --------------------------------------------------------------------------------
package com.echothree.model.control.associate.server.transfer;
import com.echothree.model.control.associate.common.transfer.AssociatePartyContactMechanismTransfer;
import com.echothree.model.control.associate.common.transfer.AssociateReferralTransfer;
import com.echothree.model.control.associate.common.transfer.AssociateTransfer;
import com.echothree.model.control.associate.server.control.AssociateControl;
import com.echothree.model.control.core.common.transfer.EntityInstanceTransfer;
import com.echothree.model.control.core.server.control.CoreControl;
import com.echothree.model.data.associate.server.entity.AssociatePartyContactMechanism;
import com.echothree.model.data.associate.server.entity.AssociateReferral;
import com.echothree.model.data.associate.server.entity.AssociateReferralDetail;
import com.echothree.model.data.core.server.entity.EntityInstance;
import com.echothree.model.data.user.server.entity.UserVisit;
import com.echothree.util.server.persistence.Session;
public class AssociateReferralTransferCache
extends BaseAssociateTransferCache<AssociateReferral, AssociateReferralTransfer> {
CoreControl coreControl = Session.getModelController(CoreControl.class);
/** Creates a new instance of AssociateReferralTransferCache */
public AssociateReferralTransferCache(UserVisit userVisit, AssociateControl associateControl) {
super(userVisit, associateControl);
setIncludeEntityInstance(true);
}
@Override
public AssociateReferralTransfer getTransfer(AssociateReferral associateReferral) {
AssociateReferralTransfer associateReferralTransfer = get(associateReferral);
if(associateReferralTransfer == null) {
AssociateReferralDetail associateReferralDetail = associateReferral.getLastDetail();
String associateReferralName = associateReferralDetail.getAssociateReferralName();
AssociateTransfer associateTransfer = associateControl.getAssociateTransfer(userVisit, associateReferralDetail.getAssociate());
AssociatePartyContactMechanism associatePartyContactMechanism = associateReferralDetail.getAssociatePartyContactMechanism();
AssociatePartyContactMechanismTransfer associatePartyContactMechanismTransfer = associatePartyContactMechanism == null ? null : associateControl.getAssociatePartyContactMechanismTransfer(userVisit, associatePartyContactMechanism);
EntityInstance targetEntityInstance = associateReferralDetail.getTargetEntityInstance();
EntityInstanceTransfer targetEntityInstanceTransfer = targetEntityInstance == null ? null : coreControl.getEntityInstanceTransfer(userVisit, targetEntityInstance, false, false, false, false, false);
Long unformattedAssociateReferralTime = associateReferralDetail.getAssociateReferralTime();
String associateReferralTime = formatTypicalDateTime(unformattedAssociateReferralTime);
associateReferralTransfer = new AssociateReferralTransfer(associateReferralName, associateTransfer, associatePartyContactMechanismTransfer,
targetEntityInstanceTransfer, unformattedAssociateReferralTime, associateReferralTime);
put(associateReferral, associateReferralTransfer);
}
return associateReferralTransfer;
}
}
|
td00/pretix | src/pretix/sentry.py | from threading import Lock
from raven.contrib.celery import SentryCeleryHandler
from raven.contrib.django.apps import RavenConfig
from raven.contrib.django.models import (
SentryDjangoHandler, client, get_client, install_middleware,
register_serializers,
)
_setup_lock = Lock()
_initialized = False
class CustomSentryDjangoHandler(SentryDjangoHandler):
def install_celery(self):
self.celery_handler = SentryCeleryHandler(client, ignore_expected=True).install()
def initialize():
global _initialized
with _setup_lock:
if _initialized:
return
register_serializers()
install_middleware()
handler = CustomSentryDjangoHandler()
handler.install()
# instantiate client so hooks get registered
get_client() # NOQA
_initialized = True
class App(RavenConfig):
def ready(self):
initialize()
|
cirope/mawidabp | test/controllers/control_objective_items_controller_test.rb | <reponame>cirope/mawidabp
require 'test_helper'
# Pruebas para el controlador de items de objetivos de control
class ControlObjectiveItemsControllerTest < ActionController::TestCase
fixtures :control_objective_items, :control_objectives, :reviews
# Prueba que sin realizar autenticación esten accesibles las partes publicas
# y no accesibles las privadas
test 'public and private actions' do
id_param = {
:params => {
:id => control_objective_items(:management_dependency_item).to_param
}
}
public_actions = []
private_actions = [
[:get, :index, {}],
[:get, :show, id_param],
[:get, :edit, id_param],
[:patch, :update, id_param],
[:delete, :destroy, id_param]
]
private_actions.each do |action|
options = action.pop
send *action, **options
assert_redirected_to login_url
assert_equal I18n.t('message.must_be_authenticated'), flash.alert
end
public_actions.each do |action|
send *action
assert_response :success
end
end
test 'list control objective items' do
login
get :index
assert_response :success
assert_not_nil assigns(:control_objectives)
assert_template 'control_objective_items/index'
end
test 'list control objective items with search' do
login
get :index, :params => {
:search => {
:query => 'seguridad',
:columns => ['control_objective_text', 'review']
}
}
assert_response :success
assert_not_nil assigns(:control_objectives)
assert assigns(:control_objectives).count > 0
assert(assigns(:control_objectives).all? do |coi|
coi.control_objective_text.match(/seguridad/i)
end)
assert_template 'control_objective_items/index'
end
test 'show control_objective_item' do
login
get :show, :params => {
:id => control_objective_items(:management_dependency_item).id
}
assert_response :success
assert_not_nil assigns(:control_objective_item)
assert_template 'control_objective_items/show'
end
test 'edit control_objective_item' do
login
get :edit, :params => {
:id => control_objective_items(:management_dependency_item_editable).id
}
assert_response :success
assert_not_nil assigns(:control_objective_item)
assert_template 'control_objective_items/edit'
end
test 'update control_objective_item' do
control_objective_item = control_objective_items(:management_dependency_item_editable)
assert_no_difference ['ControlObjectiveItem.count', 'Control.count'] do
assert_difference 'WorkPaper.count', 2 do
login
patch :update, :params => {
:id => control_objective_item.id,
:control_objective_item => {
:control_objective_text => 'Updated text',
:relevance => ControlObjectiveItem.relevances_values.last,
:control_attributes => {
:id => controls(:management_dependency_item_editable_control_1).id,
:control => 'Updated control',
:effects => 'Updated effects',
:design_tests => 'Updated design tests',
:compliance_tests => 'Updated compliance tests',
:sustantive_tests => 'Updated sustantive tests'
},
:design_score => ControlObjectiveItem.qualifications_values.last,
:compliance_score => ControlObjectiveItem.qualifications_values.last,
:audit_date => 10.days.from_now.to_date,
:auditor_comment => 'Updated comment',
:control_objective_id =>
control_objectives(:organization_security_4_1).id,
:review_id => reviews(:review_with_conclusion).id,
:work_papers_attributes => [
{
:name => 'New workpaper name',
:code => 'PTOC 20',
:number_of_pages => '10',
:description => 'New workpaper description',
:organization_id => organizations(:cirope).id,
:file_model_attributes =>
{ :file => fixture_file_upload(TEST_FILE, 'text/plain') }
},
{
:name => 'New workpaper2 name',
:code => 'PTOC 21',
:number_of_pages => '10',
:description => 'New workpaper2 description',
:organization_id => organizations(:cirope).id,
:file_model_attributes =>
{ :file => fixture_file_upload(TEST_FILE, 'text/plain') }
}
]
}
}
end
end
assert_redirected_to edit_control_objective_item_url(
control_objective_item)
assert_not_nil assigns(:control_objective_item)
assert_equal 'Updated text',
assigns(:control_objective_item).control_objective_text
end
test 'update control_objective_item with business unit scores' do
assert_no_difference ['ControlObjectiveItem.count', 'Control.count'] do
# One explicit and two via business unit type
assert_difference 'BusinessUnitScore.count', 3 do
login
patch :update, :params => {
:id => control_objective_items(:organization_security_4_4_item).id,
:control_objective_item => {
:control_objective_text => 'Updated text',
:relevance => ControlObjectiveItem.relevances_values.last,
:control_attributes => {
:id => controls(:organization_security_4_4_item_control_1).id,
:control => 'Updated control',
:effects => 'Updated effects',
:design_tests => 'Updated design tests',
:compliance_tests => 'Updated compliance tests',
:sustantive_tests => 'Updated sustantive tests'
},
:design_score => ControlObjectiveItem.qualifications_values.last,
:compliance_score => ControlObjectiveItem.qualifications_values.last,
:sustantive_score => ControlObjectiveItem.qualifications_values.last,
:audit_date => 10.days.from_now.to_date,
:auditor_comment => 'Updated comment',
:control_objective_id => control_objectives(:organization_security_4_4).id,
:review_id => reviews(:review_without_conclusion).id,
:business_unit_scores_attributes => [
{
:business_unit_id => business_units(:business_unit_two).id,
:design_score => ControlObjectiveItem.qualifications_values.last.to_s,
:compliance_score => ControlObjectiveItem.qualifications_values.last.to_s,
:sustantive_score => ControlObjectiveItem.qualifications_values.last.to_s
}
],
:business_unit_type_ids => [business_unit_types(:consolidated_substantive).id.to_s]
}
}
end
end
assert_redirected_to edit_control_objective_item_url(
control_objective_items( :organization_security_4_4_item))
assert_not_nil assigns(:control_objective_item)
assert_equal 'Updated text',
assigns(:control_objective_item).control_objective_text
end
test 'destroy control_objective_item' do
login
assert_difference 'ControlObjectiveItem.count', -1 do
delete :destroy, :params => {
:id => control_objective_items(:organization_security_4_3_item_editable_without_findings).id
}
end
assert_redirected_to control_objective_items_url
end
test 'auto complete for business unit' do
login
get :auto_complete_for_business_unit, :params => {
:q => 'fifth'
}, :as => :json
assert_response :success
business_units = ActiveSupport::JSON.decode(@response.body)
assert_equal 0, business_units.size # Fifth is in another organization
get :auto_complete_for_business_unit, :params => {
:q => 'one'
}, :as => :json
assert_response :success
business_units = ActiveSupport::JSON.decode(@response.body)
assert_equal 1, business_units.size # One only
assert business_units.all? { |u| (u['label'] + u['informal']).match /one/i }
get :auto_complete_for_business_unit, :params => {
:q => 'business'
}, :as => :json
assert_response :success
business_units = ActiveSupport::JSON.decode(@response.body)
assert_equal 4, business_units.size # All in the organization (one, two, three and four)
assert business_units.all? { |u| (u['label'] + u['informal']).match /business/i }
end
test 'auto complete for business unit type' do
login
get :auto_complete_for_business_unit_type, :params => {
:q => 'noway'
}, :as => :json
assert_response :success
business_unit_types = ActiveSupport::JSON.decode(@response.body)
assert_equal 0, business_unit_types.size # Fifth is in another organization
get :auto_complete_for_business_unit_type, :params => {
:q => 'cycle'
}, :as => :json
assert_response :success
business_unit_types = ActiveSupport::JSON.decode(@response.body)
assert_equal 1, business_unit_types.size # One only
assert business_unit_types.all? { |u| u['label'].match /cycle/i }
end
end
|
Fortranm/BizHawk | waterbox/libsnes/bsnes/snes/chip/superfx/memory/memory.cpp | #ifdef SUPERFX_CPP
uint8 SuperFX::bus_read(unsigned addr) {
if((addr & 0xc00000) == 0x000000) { //$00-3f:0000-7fff, $00-3f:8000-ffff
while(!regs.scmr.ron && scheduler.sync != Scheduler::SynchronizeMode::All) {
add_clocks(6);
synchronize_cpu();
}
auto myaddr = (((addr & 0x3f0000) >> 1) | (addr & 0x7fff)) & rom_mask;
cdlInfo.set(eCDLog_AddrType_CARTROM, addr);
return cartridge.rom.read(myaddr);
}
if((addr & 0xe00000) == 0x400000) { //$40-5f:0000-ffff
while(!regs.scmr.ron && scheduler.sync != Scheduler::SynchronizeMode::All) {
add_clocks(6);
synchronize_cpu();
}
auto myaddr = addr & rom_mask;
cdlInfo.set(eCDLog_AddrType_CARTROM, myaddr);
return cartridge.rom.read(myaddr);
}
if((addr & 0xe00000) == 0x600000) { //$60-7f:0000-ffff
while(!regs.scmr.ran && scheduler.sync != Scheduler::SynchronizeMode::All) {
add_clocks(6);
synchronize_cpu();
}
return cartridge.ram.read(addr & ram_mask);
}
}
void SuperFX::bus_write(unsigned addr, uint8 data) {
if((addr & 0xe00000) == 0x600000) { //$60-7f:0000-ffff
while(!regs.scmr.ran && scheduler.sync != Scheduler::SynchronizeMode::All) {
add_clocks(6);
synchronize_cpu();
}
return cartridge.ram.write(addr & ram_mask, data);
}
}
uint8 SuperFX::op_read(uint16 addr) {
uint16 offset = addr - regs.cbr;
if(offset < 512) {
if(cache.valid[offset >> 4] == false) {
unsigned dp = offset & 0xfff0;
unsigned sp = (regs.pbr << 16) + ((regs.cbr + dp) & 0xfff0);
for(unsigned n = 0; n < 16; n++) {
add_clocks(memory_access_speed);
cache.buffer[dp++] = bus_read(sp++);
}
cache.valid[offset >> 4] = true;
} else {
add_clocks(cache_access_speed);
}
return cache.buffer[offset];
}
if(regs.pbr <= 0x5f) {
//$[00-5f]:[0000-ffff] ROM
rombuffer_sync();
add_clocks(memory_access_speed);
return bus_read((regs.pbr << 16) + addr);
} else {
//$[60-7f]:[0000-ffff] RAM
rambuffer_sync();
add_clocks(memory_access_speed);
return bus_read((regs.pbr << 16) + addr);
}
}
uint8 SuperFX::peekpipe() {
uint8 result = regs.pipeline;
regs.pipeline = op_read(regs.r[15]);
r15_modified = false;
return result;
}
uint8 SuperFX::pipe() {
uint8 result = regs.pipeline;
regs.pipeline = op_read(++regs.r[15]);
r15_modified = false;
return result;
}
void SuperFX::cache_flush() {
for(unsigned n = 0; n < 32; n++) cache.valid[n] = false;
}
uint8 SuperFX::cache_mmio_read(uint16 addr) {
addr = (addr + regs.cbr) & 511;
return cache.buffer[addr];
}
void SuperFX::cache_mmio_write(uint16 addr, uint8 data) {
addr = (addr + regs.cbr) & 511;
cache.buffer[addr] = data;
if((addr & 15) == 15) cache.valid[addr >> 4] = true;
}
void SuperFX::memory_reset() {
rom_mask = cartridge.rom.size() - 1;
ram_mask = cartridge.ram.size() - 1;
for(unsigned n = 0; n < 512; n++) cache.buffer[n] = 0x00;
for(unsigned n = 0; n < 32; n++) cache.valid[n] = false;
for(unsigned n = 0; n < 2; n++) {
pixelcache[n].offset = ~0;
pixelcache[n].bitpend = 0x00;
}
}
#endif
|
UltraProton/Placement-Prepration | C++/strings/splitstring.cpp | #include<bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
/* code */
//Taking the space separated input
string space_sep="";
string delimeter1=" ";
vector<int> result1;
getline(cin,space_sep);
//cout<<space_sep<<endl;
int pos=space_sep.find(delimeter1);
while(pos!=string::npos){
string curr="";
curr= space_sep.substr(0,pos);
//cout<<curr<<endl;
result1.emplace_back(stoi(curr));
space_sep.erase(0,pos+delimeter1.size());
pos=space_sep.find(delimeter1);
}
result1.emplace_back(stoi(space_sep));
for(auto x: result1){
cout<<x<<endl;
}
cout<<endl;
string comma_separated="";
string delimeter2=",";
vector<int> result2;
getline(cin,comma_separated);
pos=comma_separated.find(delimeter2);
while(pos!=string::npos){
string curr="";
curr=comma_separated.substr(0,pos);
result2.emplace_back(stoi(curr));
comma_separated.erase(0,pos+delimeter2.size());
pos= comma_separated.find(delimeter2);
}
result2.emplace_back(stoi(comma_separated));
for(auto x: result2){
cout<<x<<endl;
}
return 0;
}
|
Shinhwe/anu | packages/cli/templates/qunar/source/pages/demo/syntax/ifcom/index.js | <gh_stars>1-10
import React from '@react';
import Label from '@components/Label/index';
import './index.scss';
/* eslint no-console: 0 */
class P extends React.Component {
constructor() {
super();
this.state = {
condition1: true,
condition2: true
};
}
toggleCondition2() {
console.log('Condition2');
this.setState({
condition2: !this.state.condition2
});
}
toggleCondition1() {
console.log('Condition1');
this.setState({
condition1: !this.state.condition1
});
}
render() {
return (
<div class="anu-block">
<div>改动React源码的onBeforeRender相关部分</div>
<div>
{this.state.condition2 ? (
<Label onTap={this.toggleCondition2.bind(this)} class="btn">Inactive Condition2</Label>
) : (
<Label onTap={this.toggleCondition2.bind(this)} class="btn">Active Condition2</Label>
)}
</div>
</div>
);
}
}
export default P; |
peerct/Viewers | Packages/lesiontracker/client/components/confirmDeleteDialog/confirmDeleteDialog.js | function closeHandler() {
// Hide the lesion dialog
$("#confirmDeleteDialog").css('display', 'none');
// Remove the backdrop
$(".removableBackdrop").remove();
// Remove the callback from the template data
delete Template.confirmDeleteDialog.doneCallback;
}
showConfirmDialog = function(doneCallback, options) {
// Show the backdrop
options = options || {};
UI.renderWithData(Template.removableBackdrop, options, document.body);
// Make sure the context menu is closed when the user clicks away
$(".removableBackdrop").one('mousedown touchstart', function() {
closeHandler();
});
$("#confirmDeleteDialog").css('display', 'block');
if (doneCallback && typeof doneCallback === 'function') {
Template.confirmDeleteDialog.doneCallback = doneCallback;
}
};
var keys = {
ESC: 27,
ENTER: 13
};
Template.confirmDeleteDialog.events({
'click #cancel, click #close': function() {
closeHandler();
},
'click #confirm': function() {
var doneCallback = Template.confirmDeleteDialog.doneCallback;
if (doneCallback && typeof doneCallback === 'function') {
doneCallback();
}
closeHandler();
},
'keypress #confirmDeleteDialog': function(e) {
if (e.which === keys.ESC) {
closeHandler();
}
if (this.keyPressAllowed === false) {
return;
}
var doneCallback = Template.confirmDeleteDialog.doneCallback;
// If Enter is pressed, close the dialog
if (e.which === keys.ENTER) {
if (doneCallback && typeof doneCallback === 'function') {
doneCallback();
}
closeHandler();
}
}
}); |
HyperTars/NYC-Taxi-Analysis | Assignment1/old - hpc tested/hw1/Task3/src/mapper.py | #!/usr/bin/env python
import sys
import re
for line in sys.stdin:
# skip invalid
if len(line) <= 1 or 'medallion' in line:
continue
# extract data
data = line.strip()
data = re.split(',|\t', data)
key = data[0]
val = ','.join(data[1:])
# print
if 'MEDALLION' in line or 'CUR' in line:
print '%s\tlc,%s' % (key, val)
else:
print '%s\ttf,%s' % (key, val)
# Test Code
'''
cd ~/hw1/Task3
rm -rf VehicleJoinSamp.out
hfs -rm -r VehicleJoinSamp.out
hjs -D mapreduce.job.reduces=0 \
-file ~/hw1/Task3/src/ \
-mapper src/mapper.sh \
-input /user/wl2154/TripFareJoinSamp.txt /user/wl2154/licenses_samp.csv \
-output /user/wl2154/VehicleJoinSamp.out
hfs -get VehicleJoinSamp.out
hfs -getmerge VehicleJoinSamp.out VehicleJoinSamp.txt
cat VehicleJoinSamp.txt
'''
|
amilcar-capsus/UPT-Server-Extension | app-specific-code/src/main/java/org/oskari/example/st/SettingsMethod.java | <filename>app-specific-code/src/main/java/org/oskari/example/st/SettingsMethod.java
package org.oskari.example.st;
public class SettingsMethod {
public String method;
public Integer value;
public String label;
} |
MrShiposha/metaxxa | include/literal.h | <filename>include/literal.h
#ifndef METAXXA_LITERAL_H
#define METAXXA_LITERAL_H
namespace metaxxa
{
template <typename T, T LITERAL>
struct Literal
{
using Type = T;
static constexpr Type value = LITERAL;
};
}
#endif // METAXXA_LITERAL_H |
jaemin2682/BAEKJOON_ONLINE_JUDGE | 17294.cpp | <reponame>jaemin2682/BAEKJOON_ONLINE_JUDGE<filename>17294.cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
int dif = str[0]-str[1];
bool IsRight = true;
for(int i=0;i<str.size()-1;i++) {
if(str[i]-str[i+1] != dif) {
IsRight = false;
break;
}
}
if(IsRight) cout << "◝(⑅•ᴗ•⑅)◜..°♡ 뀌요미!!";
else cout << "흥칫뿡!! <( ̄ ﹌  ̄)>";
return 0;
}
/*
각 자릿수의 차가 일정하느냐 아니냐를 판단해야 한다.
스트링으로 받아서 각 자리수의 차를 비교해주면 되겠다. -> AC
*/ |
matjaz99/MyTestProjects | javase/src/main/java/si/matjazcerkvenik/test/javase/network/socket/EchoServer.java | package si.matjazcerkvenik.test.javase.network.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EchoServer {
/**
* Run this program and open terminal. Type:
* # telnet 127.0.0.1 4444
* Now you should be connected to java server.
* Enter some text. The server should respond.
*/
public static void main(String[] args) {
try {
// establish server socket
ServerSocket s = new ServerSocket(4444);
// wait for incoming connection
Socket incoming = s.accept();
try {
InputStream inps = incoming.getInputStream();
OutputStream outs = incoming.getOutputStream();
Scanner in = new Scanner(inps);
PrintWriter out = new PrintWriter(outs, true);
out.println("Hello from Java Server!");
boolean done = false;
while (!done && in.hasNextLine()) {
String line = in.nextLine();
out.println("Echo: "+ line);
if (line.trim().equalsIgnoreCase("BYE")) {
done = true;
}
}
} finally {
incoming.close();
}
} catch (IOException e) {
// TODO: handle exception
}
}
}
|
Gitman1989/chromium | chrome/browser/ui/views/tabs/dragged_tab_controller.cc | <gh_stars>1-10
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/tabs/dragged_tab_controller.h"
#include <math.h>
#include <set>
#include "app/animation.h"
#include "app/animation_delegate.h"
#include "app/slide_animation.h"
#include "app/resource_bundle.h"
#include "base/callback.h"
#include "base/i18n/rtl.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/tabs/base_tab.h"
#include "chrome/browser/views/tabs/base_tab_strip.h"
#include "chrome/browser/views/tabs/browser_tab_strip_controller.h"
#include "chrome/browser/views/tabs/dragged_tab_view.h"
#include "chrome/browser/views/tabs/native_view_photobooth.h"
#include "chrome/browser/views/tabs/side_tab.h"
#include "chrome/browser/views/tabs/side_tab_strip.h"
#include "chrome/browser/views/tabs/tab.h"
#include "chrome/browser/views/tabs/tab_strip.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "gfx/canvas_skia.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "views/event.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"
#include "views/window/window.h"
#if defined(OS_WIN)
#include "views/widget/widget_win.h"
#endif
#if defined(OS_LINUX)
#include <gdk/gdk.h> // NOLINT
#include <gdk/gdkkeysyms.h> // NOLINT
#endif
static const int kHorizontalMoveThreshold = 16; // Pixels.
// Distance in pixels the user must move the mouse before we consider moving
// an attached vertical tab.
static const int kVerticalMoveThreshold = 8;
// If non-null there is a drag underway.
static DraggedTabController* instance_;
namespace {
// Delay, in ms, during dragging before we bring a window to front.
const int kBringToFrontDelay = 750;
// Radius of the rect drawn by DockView.
const int kRoundedRectRadius = 4;
// Spacing between tab icons when DockView is showing a docking location that
// contains more than one tab.
const int kTabSpacing = 4;
// DockView is the view responsible for giving a visual indicator of where a
// dock is going to occur.
class DockView : public views::View {
public:
explicit DockView(DockInfo::Type type) : type_(type) {}
virtual gfx::Size GetPreferredSize() {
return gfx::Size(DockInfo::popup_width(), DockInfo::popup_height());
}
virtual void PaintBackground(gfx::Canvas* canvas) {
SkRect outer_rect = { SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(width()),
SkIntToScalar(height()) };
// Fill the background rect.
SkPaint paint;
paint.setColor(SkColorSetRGB(108, 108, 108));
paint.setStyle(SkPaint::kFill_Style);
canvas->AsCanvasSkia()->drawRoundRect(
outer_rect, SkIntToScalar(kRoundedRectRadius),
SkIntToScalar(kRoundedRectRadius), paint);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SkBitmap* high_icon = rb.GetBitmapNamed(IDR_DOCK_HIGH);
SkBitmap* wide_icon = rb.GetBitmapNamed(IDR_DOCK_WIDE);
canvas->Save();
bool rtl_ui = base::i18n::IsRTL();
if (rtl_ui) {
// Flip canvas to draw the mirrored tab images for RTL UI.
canvas->TranslateInt(width(), 0);
canvas->ScaleInt(-1, 1);
}
int x_of_active_tab = width() / 2 + kTabSpacing / 2;
int x_of_inactive_tab = width() / 2 - high_icon->width() - kTabSpacing / 2;
switch (type_) {
case DockInfo::LEFT_OF_WINDOW:
case DockInfo::LEFT_HALF:
if (!rtl_ui)
std::swap(x_of_active_tab, x_of_inactive_tab);
canvas->DrawBitmapInt(*high_icon, x_of_active_tab,
(height() - high_icon->height()) / 2);
if (type_ == DockInfo::LEFT_OF_WINDOW) {
DrawBitmapWithAlpha(canvas, *high_icon, x_of_inactive_tab,
(height() - high_icon->height()) / 2);
}
break;
case DockInfo::RIGHT_OF_WINDOW:
case DockInfo::RIGHT_HALF:
if (rtl_ui)
std::swap(x_of_active_tab, x_of_inactive_tab);
canvas->DrawBitmapInt(*high_icon, x_of_active_tab,
(height() - high_icon->height()) / 2);
if (type_ == DockInfo::RIGHT_OF_WINDOW) {
DrawBitmapWithAlpha(canvas, *high_icon, x_of_inactive_tab,
(height() - high_icon->height()) / 2);
}
break;
case DockInfo::TOP_OF_WINDOW:
canvas->DrawBitmapInt(*wide_icon, (width() - wide_icon->width()) / 2,
height() / 2 - high_icon->height());
break;
case DockInfo::MAXIMIZE: {
SkBitmap* max_icon = rb.GetBitmapNamed(IDR_DOCK_MAX);
canvas->DrawBitmapInt(*max_icon, (width() - max_icon->width()) / 2,
(height() - max_icon->height()) / 2);
break;
}
case DockInfo::BOTTOM_HALF:
case DockInfo::BOTTOM_OF_WINDOW:
canvas->DrawBitmapInt(*wide_icon, (width() - wide_icon->width()) / 2,
height() / 2 + kTabSpacing / 2);
if (type_ == DockInfo::BOTTOM_OF_WINDOW) {
DrawBitmapWithAlpha(canvas, *wide_icon,
(width() - wide_icon->width()) / 2,
height() / 2 - kTabSpacing / 2 - wide_icon->height());
}
break;
default:
NOTREACHED();
break;
}
canvas->Restore();
}
private:
void DrawBitmapWithAlpha(gfx::Canvas* canvas, const SkBitmap& image,
int x, int y) {
SkPaint paint;
paint.setAlpha(128);
canvas->DrawBitmapInt(image, x, y, paint);
}
DockInfo::Type type_;
DISALLOW_COPY_AND_ASSIGN(DockView);
};
gfx::Point ConvertScreenPointToTabStripPoint(BaseTabStrip* tabstrip,
const gfx::Point& screen_point) {
gfx::Point tabstrip_topleft;
views::View::ConvertPointToScreen(tabstrip, &tabstrip_topleft);
return gfx::Point(screen_point.x() - tabstrip_topleft.x(),
screen_point.y() - tabstrip_topleft.y());
}
// Returns the the x-coordinate of |point| if the type of tabstrip is horizontal
// otherwise returns the y-coordinate.
int MajorAxisValue(const gfx::Point& point, BaseTabStrip* tabstrip) {
return (tabstrip->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP) ?
point.x() : point.y();
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// DockDisplayer
// DockDisplayer is responsible for giving the user a visual indication of a
// possible dock position (as represented by DockInfo). DockDisplayer shows
// a window with a DockView in it. Two animations are used that correspond to
// the state of DockInfo::in_enable_area.
class DraggedTabController::DockDisplayer : public AnimationDelegate {
public:
DockDisplayer(DraggedTabController* controller,
const DockInfo& info)
: controller_(controller),
popup_(NULL),
popup_view_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(animation_(this)),
hidden_(false),
in_enable_area_(info.in_enable_area()) {
#if defined(OS_WIN)
views::WidgetWin* popup = new views::WidgetWin;
popup_ = popup;
popup->set_window_style(WS_POPUP);
popup->set_window_ex_style(WS_EX_LAYERED | WS_EX_TOOLWINDOW |
WS_EX_TOPMOST);
popup->SetOpacity(0x00);
popup->Init(NULL, info.GetPopupRect());
popup->SetContentsView(new DockView(info.type()));
if (info.in_enable_area())
animation_.Reset(1);
else
animation_.Show();
popup->SetWindowPos(HWND_TOP, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOMOVE | SWP_SHOWWINDOW);
#else
NOTIMPLEMENTED();
#endif
popup_view_ = popup_->GetNativeView();
}
~DockDisplayer() {
if (controller_)
controller_->DockDisplayerDestroyed(this);
}
// Updates the state based on |in_enable_area|.
void UpdateInEnabledArea(bool in_enable_area) {
if (in_enable_area != in_enable_area_) {
in_enable_area_ = in_enable_area;
UpdateLayeredAlpha();
}
}
// Resets the reference to the hosting DraggedTabController. This is invoked
// when the DraggedTabController is destoryed.
void clear_controller() { controller_ = NULL; }
// NativeView of the window we create.
gfx::NativeView popup_view() { return popup_view_; }
// Starts the hide animation. When the window is closed the
// DraggedTabController is notified by way of the DockDisplayerDestroyed
// method
void Hide() {
if (hidden_)
return;
if (!popup_) {
delete this;
return;
}
hidden_ = true;
animation_.Hide();
}
virtual void AnimationProgressed(const Animation* animation) {
UpdateLayeredAlpha();
}
virtual void AnimationEnded(const Animation* animation) {
if (!hidden_)
return;
#if defined(OS_WIN)
static_cast<views::WidgetWin*>(popup_)->Close();
#else
NOTIMPLEMENTED();
#endif
delete this;
}
virtual void UpdateLayeredAlpha() {
#if defined(OS_WIN)
double scale = in_enable_area_ ? 1 : .5;
static_cast<views::WidgetWin*>(popup_)->SetOpacity(
static_cast<BYTE>(animation_.GetCurrentValue() * scale * 255.0));
popup_->GetRootView()->SchedulePaint();
#else
NOTIMPLEMENTED();
#endif
}
private:
// DraggedTabController that created us.
DraggedTabController* controller_;
// Window we're showing.
views::Widget* popup_;
// NativeView of |popup_|. We cache this to avoid the possibility of
// invoking a method on popup_ after we close it.
gfx::NativeView popup_view_;
// Animation for when first made visible.
SlideAnimation animation_;
// Have we been hidden?
bool hidden_;
// Value of DockInfo::in_enable_area.
bool in_enable_area_;
};
///////////////////////////////////////////////////////////////////////////////
// DraggedTabController, public:
DraggedTabController::DraggedTabController(BaseTab* source_tab,
BaseTabStrip* source_tabstrip)
: dragged_contents_(NULL),
original_delegate_(NULL),
source_tabstrip_(source_tabstrip),
source_model_index_(source_tabstrip->GetModelIndexOfBaseTab(source_tab)),
attached_tabstrip_(NULL),
attached_tab_(NULL),
offset_to_width_ratio_(0),
old_focused_view_(NULL),
last_move_screen_loc_(0),
mini_(source_tab->data().mini),
pinned_(source_tabstrip->IsTabPinned(source_tab)),
started_drag_(false),
active_(true) {
instance_ = this;
SetDraggedContents(
GetModel(source_tabstrip_)->GetTabContentsAt(source_model_index_));
// Listen for Esc key presses.
MessageLoopForUI::current()->AddObserver(this);
}
DraggedTabController::~DraggedTabController() {
if (instance_ == this)
instance_ = NULL;
MessageLoopForUI::current()->RemoveObserver(this);
// Need to delete the view here manually _before_ we reset the dragged
// contents to NULL, otherwise if the view is animating to its destination
// bounds, it won't be able to clean up properly since its cleanup routine
// uses GetIndexForDraggedContents, which will be invalid.
view_.reset(NULL);
SetDraggedContents(NULL); // This removes our observer.
}
// static
bool DraggedTabController::IsAttachedTo(BaseTabStrip* tab_strip) {
return instance_ && instance_->active_ &&
instance_->attached_tabstrip_ == tab_strip;
}
void DraggedTabController::CaptureDragInfo(views::View* tab,
const gfx::Point& mouse_offset) {
if (tab->width() > 0) {
offset_to_width_ratio_ = static_cast<float>(mouse_offset.x()) /
static_cast<float>(tab->width());
}
start_screen_point_ = GetCursorScreenPoint();
mouse_offset_ = mouse_offset;
InitWindowCreatePoint();
}
void DraggedTabController::Drag() {
bring_to_front_timer_.Stop();
// Before we get to dragging anywhere, ensure that we consider ourselves
// attached to the source tabstrip.
if (!started_drag_ && CanStartDrag()) {
started_drag_ = true;
SaveFocus();
Attach(source_tabstrip_, gfx::Point());
}
if (started_drag_)
ContinueDragging();
}
void DraggedTabController::EndDrag(bool canceled) {
EndDragImpl(canceled ? CANCELED : NORMAL);
}
///////////////////////////////////////////////////////////////////////////////
// DraggedTabController, PageNavigator implementation:
void DraggedTabController::OpenURLFromTab(TabContents* source,
const GURL& url,
const GURL& referrer,
WindowOpenDisposition disposition,
PageTransition::Type transition) {
if (original_delegate_) {
if (disposition == CURRENT_TAB)
disposition = NEW_WINDOW;
original_delegate_->OpenURLFromTab(source, url, referrer,
disposition, transition);
}
}
///////////////////////////////////////////////////////////////////////////////
// DraggedTabController, TabContentsDelegate implementation:
void DraggedTabController::NavigationStateChanged(const TabContents* source,
unsigned changed_flags) {
if (view_.get())
view_->Update();
}
void DraggedTabController::AddNewContents(TabContents* source,
TabContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture) {
DCHECK(disposition != CURRENT_TAB);
// Theoretically could be called while dragging if the page tries to
// spawn a window. Route this message back to the browser in most cases.
if (original_delegate_) {
original_delegate_->AddNewContents(source, new_contents, disposition,
initial_pos, user_gesture);
}
}
void DraggedTabController::ActivateContents(TabContents* contents) {
// Ignored.
}
void DraggedTabController::DeactivateContents(TabContents* contents) {
// Ignored.
}
void DraggedTabController::LoadingStateChanged(TabContents* source) {
// It would be nice to respond to this message by changing the
// screen shot in the dragged tab.
if (view_.get())
view_->Update();
}
void DraggedTabController::CloseContents(TabContents* source) {
// Theoretically could be called by a window. Should be ignored
// because window.close() is ignored (usually, even though this
// method gets called.)
}
void DraggedTabController::MoveContents(TabContents* source,
const gfx::Rect& pos) {
// Theoretically could be called by a web page trying to move its
// own window. Should be ignored since we're moving the window...
}
void DraggedTabController::ToolbarSizeChanged(TabContents* source,
bool finished) {
// Dragged tabs don't care about this.
}
void DraggedTabController::URLStarredChanged(TabContents* source,
bool starred) {
// Ignored.
}
void DraggedTabController::UpdateTargetURL(TabContents* source,
const GURL& url) {
// Ignored.
}
///////////////////////////////////////////////////////////////////////////////
// DraggedTabController, NotificationObserver implementation:
void DraggedTabController::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);
DCHECK(Source<TabContents>(source).ptr() ==
dragged_contents_->tab_contents());
EndDragImpl(TAB_DESTROYED);
}
///////////////////////////////////////////////////////////////////////////////
// DraggedTabController, MessageLoop::Observer implementation:
#if defined(OS_WIN)
void DraggedTabController::WillProcessMessage(const MSG& msg) {
}
void DraggedTabController::DidProcessMessage(const MSG& msg) {
// If the user presses ESC during a drag, we need to abort and revert things
// to the way they were. This is the most reliable way to do this since no
// single view or window reliably receives events throughout all the various
// kinds of tab dragging.
if (msg.message == WM_KEYDOWN && msg.wParam == VK_ESCAPE)
EndDrag(true);
}
#else
void DraggedTabController::WillProcessEvent(GdkEvent* event) {
}
void DraggedTabController::DidProcessEvent(GdkEvent* event) {
if (event->type == GDK_KEY_PRESS &&
reinterpret_cast<GdkEventKey*>(event)->keyval == GDK_Escape) {
EndDrag(true);
}
}
#endif
///////////////////////////////////////////////////////////////////////////////
// DraggedTabController, private:
void DraggedTabController::InitWindowCreatePoint() {
// window_create_point_ is only used in CompleteDrag() (through
// GetWindowCreatePoint() to get the start point of the docked window) when
// the attached_tabstrip_ is NULL and all the window's related bound
// information are obtained from source_tabstrip_. So, we need to get the
// first_tab based on source_tabstrip_, not attached_tabstrip_. Otherwise,
// the window_create_point_ is not in the correct coordinate system. Please
// refer to http://crbug.com/6223 comment #15 for detailed information.
views::View* first_tab = source_tabstrip_->base_tab_at_tab_index(0);
views::View::ConvertPointToWidget(first_tab, &first_source_tab_point_);
UpdateWindowCreatePoint();
}
void DraggedTabController::UpdateWindowCreatePoint() {
// See comments in InitWindowCreatePoint for details on this.
window_create_point_ = first_source_tab_point_;
window_create_point_.Offset(mouse_offset_.x(), mouse_offset_.y());
}
gfx::Point DraggedTabController::GetWindowCreatePoint() const {
gfx::Point cursor_point = GetCursorScreenPoint();
if (dock_info_.type() != DockInfo::NONE) {
// If we're going to dock, we need to return the exact coordinate,
// otherwise we may attempt to maximize on the wrong monitor.
return cursor_point;
}
return gfx::Point(cursor_point.x() - window_create_point_.x(),
cursor_point.y() - window_create_point_.y());
}
void DraggedTabController::UpdateDockInfo(const gfx::Point& screen_point) {
// Update the DockInfo for the current mouse coordinates.
DockInfo dock_info = GetDockInfoAtPoint(screen_point);
if (source_tabstrip_->type() == BaseTabStrip::VERTICAL_TAB_STRIP &&
((dock_info.type() == DockInfo::LEFT_OF_WINDOW &&
!base::i18n::IsRTL()) ||
(dock_info.type() == DockInfo::RIGHT_OF_WINDOW &&
base::i18n::IsRTL()))) {
// For side tabs it's way to easy to trigger to docking along the left/right
// edge, so we disable it.
dock_info = DockInfo();
}
if (!dock_info.equals(dock_info_)) {
// DockInfo for current position differs.
if (dock_info_.type() != DockInfo::NONE &&
!dock_controllers_.empty()) {
// Hide old visual indicator.
dock_controllers_.back()->Hide();
}
dock_info_ = dock_info;
if (dock_info_.type() != DockInfo::NONE) {
// Show new docking position.
DockDisplayer* controller = new DockDisplayer(this, dock_info_);
if (controller->popup_view()) {
dock_controllers_.push_back(controller);
dock_windows_.insert(controller->popup_view());
} else {
delete controller;
}
}
} else if (dock_info_.type() != DockInfo::NONE &&
!dock_controllers_.empty()) {
// Current dock position is the same as last, update the controller's
// in_enable_area state as it may have changed.
dock_controllers_.back()->UpdateInEnabledArea(dock_info_.in_enable_area());
}
}
void DraggedTabController::SetDraggedContents(
TabContentsWrapper* new_contents) {
if (dragged_contents_) {
registrar_.Remove(this,
NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(dragged_contents_->tab_contents()));
if (original_delegate_)
dragged_contents_->set_delegate(original_delegate_);
}
original_delegate_ = NULL;
dragged_contents_ = new_contents;
if (dragged_contents_) {
registrar_.Add(this,
NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(dragged_contents_->tab_contents()));
// We need to be the delegate so we receive messages about stuff,
// otherwise our dragged_contents() may be replaced and subsequently
// collected/destroyed while the drag is in process, leading to
// nasty crashes.
original_delegate_ = dragged_contents_->delegate();
dragged_contents_->set_delegate(this);
}
}
void DraggedTabController::SaveFocus() {
if (!old_focused_view_) {
old_focused_view_ = source_tabstrip_->GetRootView()->GetFocusedView();
source_tabstrip_->GetRootView()->FocusView(source_tabstrip_);
}
}
void DraggedTabController::RestoreFocus() {
if (old_focused_view_ && attached_tabstrip_ == source_tabstrip_)
old_focused_view_->GetRootView()->FocusView(old_focused_view_);
old_focused_view_ = NULL;
}
bool DraggedTabController::CanStartDrag() const {
// Determine if the mouse has moved beyond a minimum elasticity distance in
// any direction from the starting point.
static const int kMinimumDragDistance = 10;
gfx::Point screen_point = GetCursorScreenPoint();
int x_offset = abs(screen_point.x() - start_screen_point_.x());
int y_offset = abs(screen_point.y() - start_screen_point_.y());
return sqrt(pow(static_cast<float>(x_offset), 2) +
pow(static_cast<float>(y_offset), 2)) > kMinimumDragDistance;
}
void DraggedTabController::ContinueDragging() {
// Note that the coordinates given to us by |drag_event| are basically
// useless, since they're in source_tab_ coordinates. On the surface, you'd
// think we could just convert them to screen coordinates, however in the
// situation where we're dragging the last tab in a window when multiple
// windows are open, the coordinates of |source_tab_| are way off in
// hyperspace since the window was moved there instead of being closed so
// that we'd keep receiving events. And our ConvertPointToScreen methods
// aren't really multi-screen aware. So really it's just safer to get the
// actual position of the mouse cursor directly from Windows here, which is
// guaranteed to be correct regardless of monitor config.
gfx::Point screen_point = GetCursorScreenPoint();
#if defined(OS_CHROMEOS)
// We don't allow detaching in chrome os.
BaseTabStrip* target_tabstrip = source_tabstrip_;
#else
// Determine whether or not we have dragged over a compatible TabStrip in
// another browser window. If we have, we should attach to it and start
// dragging within it.
BaseTabStrip* target_tabstrip = GetTabStripForPoint(screen_point);
#endif
if (target_tabstrip != attached_tabstrip_) {
// Make sure we're fully detached from whatever TabStrip we're attached to
// (if any).
if (attached_tabstrip_)
Detach();
if (target_tabstrip)
Attach(target_tabstrip, screen_point);
}
if (!target_tabstrip) {
bring_to_front_timer_.Start(
base::TimeDelta::FromMilliseconds(kBringToFrontDelay), this,
&DraggedTabController::BringWindowUnderMouseToFront);
}
UpdateDockInfo(screen_point);
if (attached_tabstrip_)
MoveAttachedTab(screen_point);
else
MoveDetachedTab(screen_point);
}
void DraggedTabController::MoveAttachedTab(const gfx::Point& screen_point) {
DCHECK(attached_tabstrip_);
DCHECK(!view_.get());
gfx::Point dragged_view_point = GetAttachedTabDragPoint(screen_point);
TabStripModel* attached_model = GetModel(attached_tabstrip_);
int from_index = attached_model->GetIndexOfTabContents(dragged_contents_);
int threshold = kVerticalMoveThreshold;
if (attached_tabstrip_->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP) {
TabStrip* tab_strip = static_cast<TabStrip*>(attached_tabstrip_);
// Determine the horizontal move threshold. This is dependent on the width
// of tabs. The smaller the tabs compared to the standard size, the smaller
// the threshold.
double unselected, selected;
tab_strip->GetCurrentTabWidths(&unselected, &selected);
double ratio = unselected / Tab::GetStandardSize().width();
threshold = static_cast<int>(ratio * kHorizontalMoveThreshold);
}
// Update the model, moving the TabContents from one index to another. Do this
// only if we have moved a minimum distance since the last reorder (to prevent
// jitter).
if (abs(MajorAxisValue(screen_point, attached_tabstrip_) -
last_move_screen_loc_) > threshold) {
gfx::Point dragged_view_screen_point(dragged_view_point);
views::View::ConvertPointToScreen(attached_tabstrip_,
&dragged_view_screen_point);
gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_screen_point);
int to_index = GetInsertionIndexForDraggedBounds(bounds, true);
to_index = NormalizeIndexToAttachedTabStrip(to_index);
if (from_index != to_index) {
last_move_screen_loc_ = MajorAxisValue(screen_point, attached_tabstrip_);
attached_model->MoveTabContentsAt(from_index, to_index, true);
}
}
attached_tab_->SchedulePaint();
attached_tab_->SetX(dragged_view_point.x());
attached_tab_->SetX(
attached_tabstrip_->MirroredLeftPointForRect(attached_tab_->bounds()));
attached_tab_->SetY(dragged_view_point.y());
attached_tab_->SchedulePaint();
}
void DraggedTabController::MoveDetachedTab(const gfx::Point& screen_point) {
DCHECK(!attached_tabstrip_);
DCHECK(view_.get());
int x = screen_point.x() - mouse_offset_.x();
int y = screen_point.y() - mouse_offset_.y();
// Move the View. There are no changes to the model if we're detached.
view_->MoveTo(gfx::Point(x, y));
}
DockInfo DraggedTabController::GetDockInfoAtPoint(
const gfx::Point& screen_point) {
if (attached_tabstrip_) {
// If the mouse is over a tab strip, don't offer a dock position.
return DockInfo();
}
if (dock_info_.IsValidForPoint(screen_point)) {
// It's possible any given screen coordinate has multiple docking
// positions. Check the current info first to avoid having the docking
// position bounce around.
return dock_info_;
}
gfx::NativeView dragged_hwnd = view_->GetWidget()->GetNativeView();
dock_windows_.insert(dragged_hwnd);
DockInfo info = DockInfo::GetDockInfoAtPoint(screen_point, dock_windows_);
dock_windows_.erase(dragged_hwnd);
return info;
}
BaseTabStrip* DraggedTabController::GetTabStripForPoint(
const gfx::Point& screen_point) {
gfx::NativeView dragged_view = NULL;
if (view_.get()) {
dragged_view = view_->GetWidget()->GetNativeView();
dock_windows_.insert(dragged_view);
}
gfx::NativeWindow local_window =
DockInfo::GetLocalProcessWindowAtPoint(screen_point, dock_windows_);
if (dragged_view)
dock_windows_.erase(dragged_view);
if (!local_window)
return NULL;
BrowserView* browser =
BrowserView::GetBrowserViewForNativeWindow(local_window);
// We don't allow drops on windows that don't have tabstrips.
if (!browser ||
!browser->browser()->SupportsWindowFeature(Browser::FEATURE_TABSTRIP))
return NULL;
BaseTabStrip* other_tabstrip = browser->tabstrip();
if (!other_tabstrip->controller()->IsCompatibleWith(source_tabstrip_))
return NULL;
return GetTabStripIfItContains(other_tabstrip, screen_point);
}
BaseTabStrip* DraggedTabController::GetTabStripIfItContains(
BaseTabStrip* tabstrip, const gfx::Point& screen_point) const {
static const int kVerticalDetachMagnetism = 15;
static const int kHorizontalDetachMagnetism = 15;
// Make sure the specified screen point is actually within the bounds of the
// specified tabstrip...
gfx::Rect tabstrip_bounds = GetViewScreenBounds(tabstrip);
if (tabstrip->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP) {
if (screen_point.x() < tabstrip_bounds.right() &&
screen_point.x() >= tabstrip_bounds.x()) {
// TODO(beng): make this be relative to the start position of the mouse
// for the source TabStrip.
int upper_threshold = tabstrip_bounds.bottom() + kVerticalDetachMagnetism;
int lower_threshold = tabstrip_bounds.y() - kVerticalDetachMagnetism;
if (screen_point.y() >= lower_threshold &&
screen_point.y() <= upper_threshold) {
return tabstrip;
}
}
} else {
if (screen_point.y() < tabstrip_bounds.bottom() &&
screen_point.y() >= tabstrip_bounds.y()) {
int upper_threshold = tabstrip_bounds.right() +
kHorizontalDetachMagnetism;
int lower_threshold = tabstrip_bounds.x() - kHorizontalDetachMagnetism;
if (screen_point.x() >= lower_threshold &&
screen_point.x() <= upper_threshold) {
return tabstrip;
}
}
}
return NULL;
}
void DraggedTabController::Attach(BaseTabStrip* attached_tabstrip,
const gfx::Point& screen_point) {
DCHECK(!attached_tabstrip_); // We should already have detached by the time
// we get here.
DCHECK(!attached_tab_); // Similarly there should be no attached tab.
attached_tabstrip_ = attached_tabstrip;
// We don't need the photo-booth while we're attached.
photobooth_.reset(NULL);
// And we don't need the dragged view.
view_.reset();
BaseTab* tab = GetTabMatchingDraggedContents(attached_tabstrip_);
if (!tab) {
// There is no Tab in |attached_tabstrip| that corresponds to the dragged
// TabContents. We must now create one.
// Remove ourselves as the delegate now that the dragged TabContents is
// being inserted back into a Browser.
dragged_contents_->set_delegate(NULL);
original_delegate_ = NULL;
// Return the TabContents' to normalcy.
dragged_contents_->tab_contents()->set_capturing_contents(false);
// Inserting counts as a move. We don't want the tabs to jitter when the
// user moves the tab immediately after attaching it.
last_move_screen_loc_ = MajorAxisValue(screen_point, attached_tabstrip);
// Figure out where to insert the tab based on the bounds of the dragged
// representation and the ideal bounds of the other Tabs already in the
// strip. ("ideal bounds" are stable even if the Tabs' actual bounds are
// changing due to animation).
gfx::Rect bounds = GetDraggedViewTabStripBounds(screen_point);
int index = GetInsertionIndexForDraggedBounds(bounds, false);
attached_tabstrip_->set_attaching_dragged_tab(true);
GetModel(attached_tabstrip_)->InsertTabContentsAt(
index, dragged_contents_,
TabStripModel::ADD_SELECTED |
(pinned_ ? TabStripModel::ADD_PINNED : 0));
attached_tabstrip_->set_attaching_dragged_tab(false);
tab = GetTabMatchingDraggedContents(attached_tabstrip_);
}
DCHECK(tab); // We should now have a tab.
attached_tab_ = tab;
attached_tabstrip_->StartedDraggingTab(tab);
if (attached_tabstrip_->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP) {
// The size of the dragged tab may have changed. Adjust the x offset so that
// ratio of mouse_offset_ to original width is maintained.
mouse_offset_.set_x(static_cast<int>(offset_to_width_ratio_ *
static_cast<int>(tab->width())));
}
// Move the corresponding window to the front.
attached_tabstrip_->GetWindow()->Activate();
}
void DraggedTabController::Detach() {
// Prevent the TabContents' HWND from being hidden by any of the model
// operations performed during the drag.
dragged_contents_->tab_contents()->set_capturing_contents(true);
// Update the Model.
TabRendererData tab_data = attached_tab_->data();
TabStripModel* attached_model = GetModel(attached_tabstrip_);
int index = attached_model->GetIndexOfTabContents(dragged_contents_);
DCHECK(index != -1);
// Hide the tab so that the user doesn't see it animate closed.
attached_tab_->SetVisible(false);
int attached_tab_width = attached_tab_->width();
attached_model->DetachTabContentsAt(index);
// Detaching may end up deleting the tab, drop references to it.
attached_tab_ = NULL;
// If we've removed the last Tab from the TabStrip, hide the frame now.
if (attached_model->empty())
HideFrame();
// Set up the photo booth to start capturing the contents of the dragged
// TabContents.
if (!photobooth_.get()) {
photobooth_.reset(NativeViewPhotobooth::Create(
dragged_contents_->tab_contents()->GetNativeView()));
}
// Create the dragged view.
EnsureDraggedView(tab_data);
view_->SetTabWidthAndUpdate(attached_tab_width, photobooth_.get());
// Detaching resets the delegate, but we still want to be the delegate.
dragged_contents_->set_delegate(this);
attached_tabstrip_ = NULL;
}
int DraggedTabController::GetInsertionIndexForDraggedBounds(
const gfx::Rect& dragged_bounds,
bool is_tab_attached) const {
int right_tab_x = 0;
int bottom_tab_y = 0;
// If the UI layout of the tab strip is right-to-left, we need to mirror the
// bounds of the dragged tab before performing the drag/drop related
// calculations. We mirror the dragged bounds because we determine the
// position of each tab on the tab strip by calling GetBounds() (without the
// mirroring transformation flag) which effectively means that even though
// the tabs are rendered from right to left, the code performs the
// calculation as if the tabs are laid out from left to right. Mirroring the
// dragged bounds adjusts the coordinates of the tab we are dragging so that
// it uses the same orientation used by the tabs on the tab strip.
gfx::Rect adjusted_bounds(dragged_bounds);
adjusted_bounds.set_x(
attached_tabstrip_->MirroredLeftPointForRect(adjusted_bounds));
int index = -1;
for (int i = 0; i < attached_tabstrip_->tab_count(); ++i) {
const gfx::Rect& ideal_bounds = attached_tabstrip_->ideal_bounds(i);
if (attached_tabstrip_->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP) {
gfx::Rect left_half = ideal_bounds;
left_half.set_width(left_half.width() / 2);
gfx::Rect right_half = ideal_bounds;
right_half.set_width(ideal_bounds.width() - left_half.width());
right_half.set_x(left_half.right());
right_tab_x = right_half.right();
if (adjusted_bounds.x() >= right_half.x() &&
adjusted_bounds.x() < right_half.right()) {
index = i + 1;
break;
} else if (adjusted_bounds.x() >= left_half.x() &&
adjusted_bounds.x() < left_half.right()) {
index = i;
break;
}
} else {
// Vertical tab strip.
int max_y = ideal_bounds.bottom();
int mid_y = ideal_bounds.y() + ideal_bounds.height() / 2;
bottom_tab_y = max_y;
if (adjusted_bounds.y() < mid_y) {
index = i;
break;
} else if (adjusted_bounds.y() >= mid_y && adjusted_bounds.y() < max_y) {
index = i + 1;
break;
}
}
}
if (index == -1) {
if ((attached_tabstrip_->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP &&
adjusted_bounds.right() > right_tab_x) ||
(attached_tabstrip_->type() == BaseTabStrip::VERTICAL_TAB_STRIP &&
adjusted_bounds.y() >= bottom_tab_y)) {
index = GetModel(attached_tabstrip_)->count();
} else {
index = 0;
}
}
index = GetModel(attached_tabstrip_)->ConstrainInsertionIndex(index, mini_);
if (is_tab_attached && mini_ &&
index == GetModel(attached_tabstrip_)->IndexOfFirstNonMiniTab()) {
index--;
}
return index;
}
gfx::Rect DraggedTabController::GetDraggedViewTabStripBounds(
const gfx::Point& screen_point) {
gfx::Point client_point =
ConvertScreenPointToTabStripPoint(attached_tabstrip_, screen_point);
// attached_tab_ is NULL when inserting into a new tabstrip.
if (attached_tab_) {
return gfx::Rect(client_point.x(), client_point.y(),
attached_tab_->width(), attached_tab_->height());
}
if (attached_tabstrip_->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP) {
double sel_width, unselected_width;
static_cast<TabStrip*>(attached_tabstrip_)->GetCurrentTabWidths(
&sel_width, &unselected_width);
return gfx::Rect(client_point.x(), client_point.y(),
static_cast<int>(sel_width),
Tab::GetStandardSize().height());
}
return gfx::Rect(client_point.x(), client_point.y(),
attached_tabstrip_->width(),
SideTab::GetPreferredHeight());
}
gfx::Point DraggedTabController::GetAttachedTabDragPoint(
const gfx::Point& screen_point) {
DCHECK(attached_tabstrip_); // The tab must be attached.
int x = screen_point.x() - mouse_offset_.x();
int y = screen_point.y() - mouse_offset_.y();
gfx::Point tab_loc(x, y);
views::View::ConvertPointToView(NULL, attached_tabstrip_, &tab_loc);
x = tab_loc.x();
y = tab_loc.y();
const gfx::Size& tab_size = attached_tab_->bounds().size();
if (attached_tabstrip_->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP) {
int max_x = attached_tabstrip_->bounds().right() - tab_size.width();
x = std::min(std::max(x, 0), max_x);
y = 0;
} else {
x = SideTabStrip::kTabStripInset;
int max_y = attached_tabstrip_->bounds().bottom() - tab_size.height();
y = std::min(std::max(y, SideTabStrip::kTabStripInset), max_y);
}
return gfx::Point(x, y);
}
BaseTab* DraggedTabController::GetTabMatchingDraggedContents(
BaseTabStrip* tabstrip) const {
int model_index =
GetModel(tabstrip)->GetIndexOfTabContents(dragged_contents_);
return model_index == TabStripModel::kNoTab ?
NULL : tabstrip->GetBaseTabAtModelIndex(model_index);
}
void DraggedTabController::EndDragImpl(EndDragType type) {
// WARNING: this may be invoked multiple times. In particular, if deletion
// occurs after a delay (as it does when the tab is released in the original
// tab strip) and the navigation controller/tab contents is deleted before
// the animation finishes, this is invoked twice. The second time through
// type == TAB_DESTROYED.
active_ = false;
bring_to_front_timer_.Stop();
// Hide the current dock controllers.
for (size_t i = 0; i < dock_controllers_.size(); ++i) {
// Be sure and clear the controller first, that way if Hide ends up
// deleting the controller it won't call us back.
dock_controllers_[i]->clear_controller();
dock_controllers_[i]->Hide();
}
dock_controllers_.clear();
dock_windows_.clear();
if (type != TAB_DESTROYED) {
// We only finish up the drag if we were actually dragging. If start_drag_
// is false, the user just clicked and released and didn't move the mouse
// enough to trigger a drag.
if (started_drag_) {
RestoreFocus();
if (type == CANCELED)
RevertDrag();
else
CompleteDrag();
}
if (dragged_contents_ && dragged_contents_->delegate() == this)
dragged_contents_->set_delegate(original_delegate_);
} else {
// If we get here it means the NavigationController is going down. Don't
// attempt to do any cleanup other than resetting the delegate (if we're
// still the delegate).
if (dragged_contents_ && dragged_contents_->delegate() == this)
dragged_contents_->set_delegate(NULL);
dragged_contents_ = NULL;
}
// The delegate of the dragged contents should have been reset. Unset the
// original delegate so that we don't attempt to reset the delegate when
// deleted.
DCHECK(!dragged_contents_ || dragged_contents_->delegate() != this);
original_delegate_ = NULL;
source_tabstrip_->DestroyDragController();
}
void DraggedTabController::RevertDrag() {
DCHECK(started_drag_);
// We save this here because code below will modify |attached_tabstrip_|.
bool restore_frame = attached_tabstrip_ != source_tabstrip_;
if (attached_tabstrip_) {
int index = GetModel(attached_tabstrip_)->GetIndexOfTabContents(
dragged_contents_);
if (attached_tabstrip_ != source_tabstrip_) {
// The Tab was inserted into another TabStrip. We need to put it back
// into the original one.
GetModel(attached_tabstrip_)->DetachTabContentsAt(index);
// TODO(beng): (Cleanup) seems like we should use Attach() for this
// somehow.
attached_tabstrip_ = source_tabstrip_;
GetModel(source_tabstrip_)->InsertTabContentsAt(
source_model_index_, dragged_contents_,
TabStripModel::ADD_SELECTED |
(pinned_ ? TabStripModel::ADD_PINNED : 0));
} else {
// The Tab was moved within the TabStrip where the drag was initiated.
// Move it back to the starting location.
GetModel(source_tabstrip_)->MoveTabContentsAt(index, source_model_index_,
true);
source_tabstrip_->StoppedDraggingTab(attached_tab_);
}
} else {
// TODO(beng): (Cleanup) seems like we should use Attach() for this
// somehow.
attached_tabstrip_ = source_tabstrip_;
// The Tab was detached from the TabStrip where the drag began, and has not
// been attached to any other TabStrip. We need to put it back into the
// source TabStrip.
GetModel(source_tabstrip_)->InsertTabContentsAt(
source_model_index_, dragged_contents_,
TabStripModel::ADD_SELECTED |
(pinned_ ? TabStripModel::ADD_PINNED : 0));
}
// If we're not attached to any TabStrip, or attached to some other TabStrip,
// we need to restore the bounds of the original TabStrip's frame, in case
// it has been hidden.
if (restore_frame) {
if (!restore_bounds_.IsEmpty()) {
#if defined(OS_WIN)
HWND frame_hwnd = source_tabstrip_->GetWidget()->GetNativeView();
MoveWindow(frame_hwnd, restore_bounds_.x(), restore_bounds_.y(),
restore_bounds_.width(), restore_bounds_.height(), TRUE);
#else
NOTIMPLEMENTED();
#endif
}
}
}
void DraggedTabController::CompleteDrag() {
DCHECK(started_drag_);
if (attached_tabstrip_) {
attached_tabstrip_->StoppedDraggingTab(attached_tab_);
} else {
if (dock_info_.type() != DockInfo::NONE) {
Profile* profile = GetModel(source_tabstrip_)->profile();
switch (dock_info_.type()) {
case DockInfo::LEFT_OF_WINDOW:
UserMetrics::RecordAction(UserMetricsAction("DockingWindow_Left"),
profile);
break;
case DockInfo::RIGHT_OF_WINDOW:
UserMetrics::RecordAction(UserMetricsAction("DockingWindow_Right"),
profile);
break;
case DockInfo::BOTTOM_OF_WINDOW:
UserMetrics::RecordAction(UserMetricsAction("DockingWindow_Bottom"),
profile);
break;
case DockInfo::TOP_OF_WINDOW:
UserMetrics::RecordAction(UserMetricsAction("DockingWindow_Top"),
profile);
break;
case DockInfo::MAXIMIZE:
UserMetrics::RecordAction(UserMetricsAction("DockingWindow_Maximize"),
profile);
break;
case DockInfo::LEFT_HALF:
UserMetrics::RecordAction(UserMetricsAction("DockingWindow_LeftHalf"),
profile);
break;
case DockInfo::RIGHT_HALF:
UserMetrics::RecordAction(
UserMetricsAction("DockingWindow_RightHalf"),
profile);
break;
case DockInfo::BOTTOM_HALF:
UserMetrics::RecordAction(
UserMetricsAction("DockingWindow_BottomHalf"),
profile);
break;
default:
NOTREACHED();
break;
}
}
// Compel the model to construct a new window for the detached TabContents.
views::Window* window = source_tabstrip_->GetWindow();
gfx::Rect window_bounds(window->GetNormalBounds());
window_bounds.set_origin(GetWindowCreatePoint());
// When modifying the following if statement, please make sure not to
// introduce issue listed in http://crbug.com/6223 comment #11.
bool rtl_ui = base::i18n::IsRTL();
bool has_dock_position = (dock_info_.type() != DockInfo::NONE);
if (rtl_ui && has_dock_position) {
// Mirror X axis so the docked tab is aligned using the mouse click as
// the top-right corner.
window_bounds.set_x(window_bounds.x() - window_bounds.width());
}
Browser* new_browser =
GetModel(source_tabstrip_)->delegate()->CreateNewStripWithContents(
dragged_contents_, window_bounds, dock_info_, window->IsMaximized());
TabStripModel* new_model = new_browser->tabstrip_model();
new_model->SetTabPinned(new_model->GetIndexOfTabContents(dragged_contents_),
pinned_);
new_browser->window()->Show();
}
CleanUpHiddenFrame();
}
void DraggedTabController::EnsureDraggedView(const TabRendererData& data) {
if (!view_.get()) {
gfx::Rect tab_bounds;
dragged_contents_->tab_contents()->GetContainerBounds(&tab_bounds);
BaseTab* renderer = source_tabstrip_->CreateTabForDragging();
renderer->SetData(data);
// DraggedTabView takes ownership of renderer.
view_.reset(new DraggedTabView(renderer, mouse_offset_,
tab_bounds.size(),
Tab::GetMinimumSelectedSize()));
}
}
gfx::Point DraggedTabController::GetCursorScreenPoint() const {
#if defined(OS_WIN)
DWORD pos = GetMessagePos();
return gfx::Point(pos);
#else
gint x, y;
gdk_display_get_pointer(gdk_display_get_default(), NULL, &x, &y, NULL);
return gfx::Point(x, y);
#endif
}
gfx::Rect DraggedTabController::GetViewScreenBounds(views::View* view) const {
gfx::Point view_topleft;
views::View::ConvertPointToScreen(view, &view_topleft);
gfx::Rect view_screen_bounds = view->GetLocalBounds(true);
view_screen_bounds.Offset(view_topleft.x(), view_topleft.y());
return view_screen_bounds;
}
int DraggedTabController::NormalizeIndexToAttachedTabStrip(int index) const {
DCHECK(attached_tabstrip_) << "Can only be called when attached!";
TabStripModel* attached_model = GetModel(attached_tabstrip_);
if (index >= attached_model->count())
return attached_model->count() - 1;
if (index == TabStripModel::kNoTab)
return 0;
return index;
}
void DraggedTabController::HideFrame() {
#if defined(OS_WIN)
// We don't actually hide the window, rather we just move it way off-screen.
// If we actually hide it, we stop receiving drag events.
HWND frame_hwnd = source_tabstrip_->GetWidget()->GetNativeView();
RECT wr;
GetWindowRect(frame_hwnd, &wr);
MoveWindow(frame_hwnd, 0xFFFF, 0xFFFF, wr.right - wr.left,
wr.bottom - wr.top, TRUE);
// We also save the bounds of the window prior to it being moved, so that if
// the drag session is aborted we can restore them.
restore_bounds_ = gfx::Rect(wr);
#else
NOTIMPLEMENTED();
#endif
}
void DraggedTabController::CleanUpHiddenFrame() {
// If the model we started dragging from is now empty, we must ask the
// delegate to close the frame.
if (GetModel(source_tabstrip_)->empty())
GetModel(source_tabstrip_)->delegate()->CloseFrameAfterDragSession();
}
void DraggedTabController::DockDisplayerDestroyed(
DockDisplayer* controller) {
DockWindows::iterator dock_i =
dock_windows_.find(controller->popup_view());
if (dock_i != dock_windows_.end())
dock_windows_.erase(dock_i);
else
NOTREACHED();
std::vector<DockDisplayer*>::iterator i =
std::find(dock_controllers_.begin(), dock_controllers_.end(),
controller);
if (i != dock_controllers_.end())
dock_controllers_.erase(i);
else
NOTREACHED();
}
void DraggedTabController::BringWindowUnderMouseToFront() {
// If we're going to dock to another window, bring it to the front.
gfx::NativeWindow window = dock_info_.window();
if (!window) {
gfx::NativeView dragged_view = view_->GetWidget()->GetNativeView();
dock_windows_.insert(dragged_view);
window = DockInfo::GetLocalProcessWindowAtPoint(GetCursorScreenPoint(),
dock_windows_);
dock_windows_.erase(dragged_view);
}
if (window) {
#if defined(OS_WIN)
// Move the window to the front.
SetWindowPos(window, HWND_TOP, 0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
// The previous call made the window appear on top of the dragged window,
// move the dragged window to the front.
SetWindowPos(view_->GetWidget()->GetNativeView(), HWND_TOP, 0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
#else
NOTIMPLEMENTED();
#endif
}
}
TabStripModel* DraggedTabController::GetModel(BaseTabStrip* tabstrip) const {
return static_cast<BrowserTabStripController*>(tabstrip->controller())->
model();
}
|
scrocquesel/java-operator-sdk | operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/RetryExecution.java | package io.javaoperatorsdk.operator.processing.retry;
import java.util.Optional;
import io.javaoperatorsdk.operator.api.reconciler.RetryInfo;
public interface RetryExecution extends RetryInfo {
/**
* @return the time to wait until the next execution in milliseconds
*/
Optional<Long> nextDelay();
}
|
fengjixuchui/napoca | napoca/kernel/cpuops.c | <filename>napoca/kernel/cpuops.c
/*
* Copyright (c) 2020 Bitdefender
* SPDX-License-Identifier: Apache-2.0
*/
/** @file cpuops.c
* @brief CPUOPS - macro wrappers and prototypes for intrinsics and plain assembler CPU operations
*
*/
#include "napoca.h"
#include "kernel/kernel.h"
CX_UINT16
CpuGetBootIndexForLocalApicId(
_In_ CX_UINT32 LapicId
)
{
CX_UINT16 cpuIndex;
CX_UINT16 i;
cpuIndex = 0xFFFF;
// locate local APIC ID in gBootInfo to get AP index
for (i = 0; i < gBootInfo->CpuCount; i++)
{
if (LapicId == gBootInfo->CpuMap[i].Id)
{
cpuIndex = i;
break;
}
}
if (0xFFFF == cpuIndex)
{
// it should not happen, but it would be critical
HvPrint("[CPU %d] CRITICAL: local APIC id of AP not found in gBootInfo[], halt\n", LapicId);
HvHalt();
return 0; // this function isn't expecting DbgEnterDebugger to return back the control
}
return cpuIndex;
}
// turn of compiler optimizations
#pragma optimize("", off)
// Neither this function, nor the function it calls does IPC processing, so no need to block IPCs
void
CpuSaveFloatingArea(
_In_ VCPU* Vcpu
)
{
PCPU *cpu = HvGetCurrentCpu();
if (Vcpu->RestoreExtState)
{
// The state was already saved, do not contaminate it
return;
}
// disable emulation for floating point operations
__writecr0(__readcr0() & ~CR0_EM);
if (cpu->UseXsave)
{
// save the guest's XCR0
Vcpu->ArchRegs.XCR0 = __xgetbv(0);
// set XCR0 to the host value, to force saving a complete FX state
__xsetbv(0, cpu->Xcr0AvailMask);
}
CpuSaveFloatingState(Vcpu->ExtState);
Vcpu->RestoreExtState = CX_TRUE; // mark that we need to restore the fx state when we re-enter the guest
FpuSseInit();
_mm_setcsr(cpu->HostMxcsr);
}
// turn back on compiler optimizations
#pragma optimize("", on)
// turn of compiler optimizations
#pragma optimize("", off)
void
CpuRestoreFloatingArea(
_In_ VCPU* Vcpu
)
{
if (Vcpu->RestoreExtState)
{
CpuRestoreFloatingState(Vcpu->ExtState);
if (HvGetCurrentCpu()->UseXsave)
{
// restore the guest's XCR0
__xsetbv(0, Vcpu->ArchRegs.XCR0 | 1ULL);
}
Vcpu->RestoreExtState = CX_FALSE;
// also, from now on, do not allow any execution of floating point instructions,
// and request exception to be generated on such attempt
__writecr0(__readcr0() | CR0_EM);
}
}
// turn back on compiler optimizations
#pragma optimize("", on)
///
/// @brief Invalidate cached mappings of address translation based on VPID, routine implemented in assembly.
///
/// @param[in] Type The type of the invalidation
/// @param[in] LinearAddress The linear address of which translation is invalidated
/// @param[in] Vpid The actual VPID for which the invalidation happens
///
/// @returns CX_STATUS_SUCCESS - in case of success
/// @returns ERROR_STATUS - in case the INVVPID failed
///
CX_STATUS
CpuVmxInvVpid_(
_In_ CX_UINT64 Type,
_In_ CX_VOID *LinearAddress,
_In_ CX_UINT64 Vpid
);
CX_STATUS
CpuVmxInvVpid(
_In_ CX_UINT64 Type,
_In_ CX_VOID *LinearAddress,
_In_ CX_UINT64 Vpid
)
{
CX_STATUS status = CX_STATUS_SUCCESS;
VCPU* vcpu = HvGetCurrentVcpu();
static CX_UINT64 invalidationCount = 0;
if (!vcpu) return CX_STATUS_INVALID_INTERNAL_STATE;
if ((VmxIsInvVpidSupported()) && (vcpu->VmcsConfig.ProcExecCtrl2 & VMCSFLAG_PROCEXEC2_ENABLE_VPID) != 0)
{
switch (Type)
{
case 0:
status = VmxIsInvVpidAddressInvalidationSupported() ? CX_STATUS_SUCCESS : CX_STATUS_OPERATION_NOT_SUPPORTED;
break;
case 1:
status = VmxIsInvVpidSingleContextInvalidationSupported() ? CX_STATUS_SUCCESS : CX_STATUS_OPERATION_NOT_SUPPORTED;
break;
case 2:
status = VmxIsInvVpidAllContextInvalidationSupported() ? CX_STATUS_SUCCESS : CX_STATUS_OPERATION_NOT_SUPPORTED;
break;
case 3:
status = VmxIsInvVpidAllContextRetGlobalsInvalidationSupported() ? CX_STATUS_SUCCESS : CX_STATUS_OPERATION_NOT_SUPPORTED;
break;
default:
status = CX_STATUS_OPERATION_NOT_SUPPORTED;
break;
}
if (CX_SUCCESS(status))
{
status = CpuVmxInvVpid_(Type, LinearAddress, Vpid);
if (!CX_SUCCESS(status)) LOG_FUNC_FAIL("CpuVmxInvVpid_", status);
}
else
{
ERROR("INVVPID instruction not supported! Type: %p, LinearAddress: %p, Vpid: %p, EptVpidMsr: %p, ProcExecCtrl2: 0x%x\n",
Type, LinearAddress, Vpid, gVirtFeatures.EptVpidFeatures.Raw, vcpu->VmcsConfig.ProcExecCtrl2);
}
}
else
{
invalidationCount++;
if ((invalidationCount % 1000000) == 0)
{
ERROR("INVVPID instruction support: %d VPID support activated in VMCS: %d! Perform FULL cache invalidation! Total invalidations: %p\n",
(CX_UINT32)VmxIsInvVpidSupported(),
(CX_UINT32)((vcpu->VmcsConfig.ProcExecCtrl2) & VMCSFLAG_PROCEXEC2_ENABLE_VPID),
invalidationCount
);
}
// invalidate cache by re-writing CR3
__writecr3(__readcr3());
}
return status;
}
///
/// @brief Invalidate cached EPT mappings(TLB) with INVEPT instruction, routine implemented in assembly.
///
/// @param[in] Type The type of the invalidation (single context or all context)
/// @param[in] InvEptDesc An INVEPT_DESCRIPTOR structure containing the Ept for which the Gpa is invalidated.
///
/// @returns CX_STATUS_SUCCESS - in case of success
/// @returns ERROR_STATUS - in case the INVEPT failed
///
CX_STATUS
CpuVmxInvEptAsm(
_In_ CX_UINT64 Type,
_In_ INVEPT_DESCRIPTOR *InvEptDesc
);
CX_STATUS
CpuVmxInvEpt(
_In_ INVEPT_TYPE Type,
_In_ CX_UINT64 Eptp,
_In_ CX_UINT64 Address
)
{
INVEPT_DESCRIPTOR desc;
desc.Eptp = Eptp;
desc.Gpa = Address;
assert(desc.Gpa == 0);
CX_STATUS status = CpuVmxInvEptAsm(Type, &desc);
#ifdef DEBUG
if (!CX_SUCCESS(status))
{
ERROR("Failed to invalidate ept! Type: 0x%02x eptp %p address %p\n", Type, Eptp, Address);
}
#endif
return status;
}
CX_UINT32
CpuComputeExtendedStateSize(
_In_ CX_UINT64 FeatureMask
)
{
int regs[4] = { 0 };
CX_UINT32 size = 512 + 64;
CX_UINT32 bitPos = 0;
// Get the supported features bit mask.
__cpuidex(regs, 0xD, 0x0);
// Clear out mandatory bits - XCR0_X87 and XCR0_SSE. Also, clear out any invalid/unsupported bit.
FeatureMask &= ~(XCR0_X87 | XCR0_SSE) & (((CX_UINT64)regs[3] << 32) | (CX_UINT64)regs[0]);
while (0 != HvBitScanForwardU64(&bitPos, FeatureMask))
{
__cpuidex(regs, 0xD, (int)bitPos);
if ((CX_UINT32)regs[0] + (CX_UINT32)regs[1] > size) size = (CX_UINT32)regs[0] + (CX_UINT32)regs[1];
HvBitTestAndResetU64(&FeatureMask, bitPos);
}
return size;
}
/// @brief Contains the masks applied on CPUID leafs for the guest for hiding different features
static
CPUID_STATE gCpuIdReserved =
{
11, // TotalLeafCount
{ //InEax InEbx, OutEax, OutEbx, OutEcx, OutEdx
// standard
{ 1, CPUID_ECX_ANY, CPUID_01_EAX_FLAG_RESERVED, CPUID_RESERVE_NONE, CPUID_01_ECX_RESERVED, CPUID_01_EDX_RESERVED },
{ 3, CPUID_ECX_ANY, CPUID_03_EAX_RESERVED, CPUID_03_EBX_RESERVED, CPUID_03_ECX_RESERVED, CPUID_03_EDX_RESERVED },
{ 4, CPUID_ECX_ANY, CPUID_04_EAX_RESERVED, CPUID_RESERVE_NONE, CPUID_RESERVE_NONE, CPUID_04_EDX_RESERVED },
{ 6, CPUID_ECX_ANY, CPUID_06_EAX_RESERVED, CPUID_06_EBX_RESERVED, CPUID_06_ECX_RESERVED, CPUID_RESERVE_NONE },
{ 7, CPUID_ECX_ANY, CPUID_07_00_EAX_RESERVED, CPUID_07_00_EBX_RESERVED, CPUID_07_00_ECX_RESERVED, CPUID_07_00_EDX_RESERVED },
{ 8, CPUID_ECX_ANY, CPUID_08_EAX_RESEVED, CPUID_08_EBX_RESEVED, CPUID_08_ECX_RESEVED, CPUID_08_EDX_RESEVED },
{ 9, CPUID_ECX_ANY, CPUID_09_EAX_RESEVED, CPUID_09_EBX_RESEVED, CPUID_09_ECX_RESEVED, CPUID_09_EDX_RESEVED },
{ 0xA, CPUID_ECX_ANY, CPUID_0A_EAX_RESEVED, CPUID_0A_EBX_RESEVED, CPUID_0A_ECX_RESEVED, CPUID_0A_EDX_RESEVED },
{ 0xD, 1, CPUID_0D_01_EAX_RESERVED, CPUID_RESERVE_NONE, CPUID_RESERVE_NONE, CPUID_RESERVE_NONE },
// extended
{ 0x80000001, CPUID_ECX_ANY, CPUID_RESERVE_NONE, CPUID_RESERVE_NONE, CPUID_80000001_ECX_RESERVED, CPUID_80000001_EDX_RESERVED },
{ 0x80000007, CPUID_ECX_ANY, CPUID_RESERVE_NONE, CPUID_RESERVE_NONE, CPUID_RESERVE_NONE, CPUID_80000007_EDX_RESERVED },
}
};
///
/// @brief Searches a certain CPUID instruction leaf in the reserved leaves array, based on EAX and ECX values.
///
/// @param[in] InEax The value of the EAX, the primary leaf number
/// @param[in] InEcx The value of the ECX, the secondary leaf number (CPUID_ECX_ANY in case it doesn't matter)
///
/// @returns CPUID_LEAF* - The found CPUID leaf amongst the reserved ones, if it was found
/// @returns CX_NULL - if not found
///
static
CPUID_LEAF*
_FindCpuidLeaf(
_In_ CX_UINT32 InEax,
_In_ CX_UINT32 InEcx
)
{
for (CX_UINT32 cpuidIdx = 0; cpuidIdx < gCpuIdReserved.TotalLeafCount; cpuidIdx++)
{
// eax filtering
if (InEax == gCpuIdReserved.Leaf[cpuidIdx].EaxIn)
{
if ((gCpuIdReserved.Leaf[cpuidIdx].EcxIn == CPUID_ECX_ANY) || (gCpuIdReserved.Leaf[cpuidIdx].EcxIn == InEcx))
{
return &gCpuIdReserved.Leaf[cpuidIdx];
}
}
}
return CX_NULL;
}
///
/// @brief Applies a reserved CPUID leafs mask on the values of the registers returned by the actual CPUID instruction
///
/// @param[in] CpuidLeaf The reserved CPUID leaf, containing all the reserved bits for all 4 registers
/// @param[in, out] Eax The address in memory where the value returned for EAX from the CPUID is stored
/// @param[in, out] Ebx The address in memory where the value returned for EBX from the CPUID is stored
/// @param[in, out] Ecx The address in memory where the value returned for ECX from the CPUID is stored
/// @param[in, out] Edx The address in memory where the value returned for EDX from the CPUID is stored
///
__forceinline
static
void
_CpuidApplyMaskOnRegisters(
_In_ const CPUID_LEAF* CpuidLeaf,
_Inout_ CX_UINT32* Eax,
_Inout_ CX_UINT32* Ebx,
_Inout_ CX_UINT32* Ecx,
_Inout_ CX_UINT32* Edx
)
{
*Eax &= (~CpuidLeaf->EaxOut);
*Ebx &= (~CpuidLeaf->EbxOut);
*Ecx &= (~CpuidLeaf->EcxOut);
*Edx &= (~CpuidLeaf->EdxOut);
}
void
CpuidChangePrimaryGuestExposedFeatures(
_In_ CX_UINT32 InEax,
_In_ CX_UINT32 InEcx,
_In_ CX_UINT8 RegisterIndex,
_In_ CX_UINT32 FlagsToChange,
_In_ CX_BOOL Expose
)
{
CPUID_LEAF* cpuidLeaf = _FindCpuidLeaf(InEax, InEcx);
if (RegisterIndex >= ARRAYSIZE(cpuidLeaf->Registers))
{
WARNING("Received CpuidChangePrimaryGuestExposedFeatures for invalid register index %u\n", RegisterIndex);
return;
}
if (Expose) cpuidLeaf->Registers[RegisterIndex] &= ~FlagsToChange;
else cpuidLeaf->Registers[RegisterIndex] |= FlagsToChange;
}
void
CpuidApplyForPrimaryGuestQuery(
_In_ CX_UINT32 InEax,
_In_ CX_UINT32 InEcx,
_Inout_ CX_UINT32* Eax,
_Inout_ CX_UINT32* Ebx,
_Inout_ CX_UINT32* Ecx,
_Inout_ CX_UINT32* Edx
)
{
CX_UINT32 finalEax =
(
(InEax > gHypervisorGlobalData.CpuData.MaxExtendedCpuidInputValue) ||
((InEax > gHypervisorGlobalData.CpuData.MaxBasicCpuidInputValue) && (InEax < CPUID_START_OF_EXTENDED_RANGE)))
? gHypervisorGlobalData.CpuData.MaxBasicCpuidInputValue
: InEax;
CPUID_LEAF* cpuidLeaf = _FindCpuidLeaf(
finalEax,
InEcx);
if (cpuidLeaf != CX_NULL) _CpuidApplyMaskOnRegisters(cpuidLeaf, Eax, Ebx, Ecx, Edx);
}
void
CpuidCollectMaxLeafValues(
_Out_ CX_UINT32* MaxBasic,
_Out_ CX_UINT32* MaxExtended
)
{
int cpuidInfo[4];
__cpuid(cpuidInfo, CPUID_BASIC_CPUID_INFORMATION);
*MaxBasic = cpuidInfo[0];
__cpuid(cpuidInfo, CPUID_EXTENDED_CPUID_INFORMATION);
*MaxExtended = cpuidInfo[0];
}
///
/// @brief Verifies support of the NXE(execute-disable) feature by CPUID and activates it in the IA32_EFER_MSR if available.
///
/// @returns TRUE if NXE is supported and was successfully activated, FALSE otherwise
///
CX_BOOL
LdActivateNxe(
void
);
static volatile CX_UINT8 _NxActive = 1; ///< Stores the state of the NXE feature
CX_STATUS
CpuActivateNxe(
CX_VOID
)
{
CX_BOOL activated = LdActivateNxe();
CxInterlockedAnd8(&_NxActive, !!activated);
return activated ? CX_STATUS_SUCCESS : CX_STATUS_OPERATION_NOT_SUPPORTED;
}
CX_BOOL
CpuIsXdUsed(
CX_VOID
)
{
return gBootInfo? (0 != gBootInfo->CpuMap[0].ExtendedIntelFeatures.Edx.NX) : (_NxActive != 0);
}
CX_UINT8 gCpuPhysicalAddressWidth = 0; ///< Max physical address width reported by the CPU
CX_UINT8 gCpuVirtualAddressWidth = 0; ///< Max virtual address width reported by the CPU
CX_UINT64 gCpuMaxPhysicalAddress = 0xFFFFFFFFFFFFFFFFULL; ///< mask to be used to store the PHYSICAL ADDRESS MASK of the host CPUs, pre-inited to max CX_UINT64
CX_VOID
CpuInitAddressWidthData(
CX_VOID
)
{
CPUID_REGS cpuidRegs = { 0 };
__cpuid((int*)&cpuidRegs, 0x80000008);
gCpuPhysicalAddressWidth = cpuidRegs.Eax & 0xff;
gCpuVirtualAddressWidth = (cpuidRegs.Eax >> 8) & 0xff;
gCpuMaxPhysicalAddress = FIELD_MASK(gCpuPhysicalAddressWidth - 1);
}
#pragma optimize("", off)
void
CpuSaveFloatingState(
_In_ CX_VOID *SaveArea
)
{
if (HvGetCurrentCpu()->UseXsaveopt) _xsaveopt64(SaveArea, (CX_UINT64)-1LL);
else if (HvGetCurrentCpu()->UseXsave) _xsave64(SaveArea, (CX_UINT64)-1LL);
else _fxsave64(SaveArea);
}
#pragma optimize("", on)
#pragma optimize("", off)
void
CpuRestoreFloatingState(
_In_ CX_VOID *SaveArea
)
{
if (HvGetCurrentCpu()->UseXsave) _xrstor64(SaveArea, (CX_UINT64)-1LL);
else _fxrstor64(SaveArea);
}
#pragma optimize("", on)
static CX_BOOL gIsIa32PatSupported = 0; ///< Stores the state of the PAT support
CX_VOID
CpuInitIa32Pat(
CX_VOID
)
{
static CX_ONCE_INIT0 patSupportKnown = 0;
if (CxInterlockedBeginOnce(&patSupportKnown))
{
if (!gBootInfo)
{
CPUID_REGS cpuidRegs;
__cpuid((int *)&cpuidRegs, 1);
gIsIa32PatSupported = !!(cpuidRegs.Edx & CPUID_01_EDX_FLAG_PAT);
}
else gIsIa32PatSupported = !!gBootInfo->CpuMap[0].IntelFeatures.Edx.PAT;
CxInterlockedEndOnce(&patSupportKnown);
}
}
CX_STATUS
CpuGetIa32Pat(
_Out_ CX_UINT64 *Pat
)
{
if (gIsIa32PatSupported)
{
HVA_PAT pat;
pat.Raw = __readmsr(MSR_IA32_PAT);
*Pat = pat.Raw;
return CX_STATUS_SUCCESS;
}
return CX_STATUS_DATA_NOT_FOUND;
}
CX_STATUS
CpuCpuidPrimaryGuest(
_In_ const VCPU* Vcpu,
_In_ CX_UINT32 InEax,
_In_ CX_UINT32 InEcx,
_Out_ CX_UINT32 *Eax,
_Out_ CX_UINT32 *Ebx,
_Out_ CX_UINT32 *Ecx,
_Out_ CX_UINT32 *Edx)
{
int a[4];
if (Vcpu == CX_NULL) return CX_STATUS_INVALID_PARAMETER_1;
if (Eax == CX_NULL) return CX_STATUS_INVALID_PARAMETER_4;
if (Ebx == CX_NULL) return CX_STATUS_INVALID_PARAMETER_5;
if (Ecx == CX_NULL) return CX_STATUS_INVALID_PARAMETER_6;
if (Edx == CX_NULL) return CX_STATUS_INVALID_PARAMETER_7;
// bare metal cpuid
__cpuidex(a, InEax, InEcx);
*Eax = (CX_UINT32)a[0];
*Ebx = (CX_UINT32)a[1];
*Ecx = (CX_UINT32)a[2];
*Edx = (CX_UINT32)a[3];
// disable features that we do not want to be available to this guest
if (InEax == 0x01)
{
// From Intel SDM, CPUID Leaf 1, ECX.27:
// "A value of 1 indicates that the OS has set CR4.OSXSAVE[bit 18] to enable the XSAVE feature set."
// We must make sure that we don't return the host state for this bit, otherwise we may cause all kind of funky
// effects inside the guest: we need to make sure that the guests' CR4 has OSXSAVE bit set before setting it.
// Otherwise, the guest will think that OSXSAVE feature has been activated inside CR4 and it will start
// to execute all kind of AVX instructions that will trigger faults.
CX_UINT32 flagsToRemove = (Vcpu->ArchRegs.CR4 & CR4_OSXSAVE) ? 0 : CPUID_01_ECX_FLAG_OSXSAVE;
*Ecx &= ~(flagsToRemove);
if (CfgFeaturesVirtualizationEnlightEnabled) *Ecx |= CPUID_01_ECX_FLAG_HYPERVISOR_PRESENT;
if (CfgFeaturesHidePhysicalX2Apic) *Ecx &= (~CPUID_01_ECX_FLAG_X2APIC);
}
else if ((CfgFeaturesNmiPerformanceCounterTicksPerSecond) && (InEax == 0xA))
{
*Eax = *Eax & (~0xFFFF);
}
else if (InEax == 7 && InEcx == 0)
{
// remove Intel PT if CPU does not support it in non-root mode
if (!gVirtFeatures.VmxMisc.IntelPTInVMX)
{
*Ebx &= (~CPUID_07_00_EBX_FLAG_INTEL_PROC_TRACE);
}
}
// mask all that we do not know and what we do not support
CpuidApplyForPrimaryGuestQuery(
InEax,
InEcx,
Eax,
Ebx,
Ecx,
Edx);
return CX_STATUS_SUCCESS;
}
CX_STATUS
CpuIsXsetbvCallValid(
_In_ const VCPU* Vcpu,
_In_ CX_UINT32 Index,
_In_ CX_UINT64 NewXcrValue
)
{
if (Vcpu == CX_NULL) return CX_STATUS_INVALID_PARAMETER_1;
// #GP(0)
// If the current privilege level is not 0 => solved by VT-x (we have exit only if CPL is 0)
// If an invalid XCR is specified in ECX.
if (Index != 0)
{
LOG("Index is not zero %u\n", Index);
return STATUS_INJECT_GP;
}
// If the value in EDX:EAX sets bits that are reserved in the XCR specified by ECX.
if ((NewXcrValue & Vcpu->Pcpu->Xcr0AvailMask) != (NewXcrValue))
{
LOG("NewCrValue is %p, while Xcr0AvailMask is %p\n", NewXcrValue, Vcpu->Pcpu->Xcr0AvailMask);
return STATUS_INJECT_GP;
}
// If an attempt is made to clear bit 0 of XCR0.
if (!(NewXcrValue & XCR0_X87))
{
LOG("Guest is attempting to clear bit 0 of XCR0, value is %p\n", NewXcrValue);
return STATUS_INJECT_GP;
}
// If an attempt is made to set XCR0[2:1] to 10b
if ((NewXcrValue & (XCR0_SSE | XCR0_YMM_HI128)) == XCR0_YMM_HI128)
{
LOG("NewCRValue will set XCR0[2:1] to 10b, value is %p\n", NewXcrValue);
return STATUS_INJECT_GP;
}
// #UD
// If CPUID.01H:ECX.XSAVE[bit 26] = 0.
CX_UINT32 eax, ebx, ecx, edx;
CX_STATUS status = CpuCpuidPrimaryGuest(Vcpu, 1, 0, &eax, &ebx, &ecx, &edx);
if ((!CX_SUCCESS(status)) || (!(ecx & CPUID_01_ECX_FLAG_XSAVE)))
{
LOG("XSAVE is not set in CPUID, ecx value is 0x%X\n", ecx);
return STATUS_INJECT_GP;
}
// If CR4.OSXSAVE[bit 18] = 0.
if (!(Vcpu->ArchRegs.CR4 & CR4_OSXSAVE)) return STATUS_INJECT_UD;
// If the LOCK prefix is used. => solved by VT-x (automatically causes #UD before VM exit for XSETBV)
return CX_STATUS_SUCCESS;
}
CX_BOOL
CpuIsKnownMsr(
_In_ CX_UINT32 Msr
)
{
return (
((Msr > 0x00000000) && (Msr < 0x00001FFF)) // low part
|| ((Msr > 0xC0000000 && Msr < 0xC0001FFF)) // high part
);
}
|
ckamtsikis/cmssw | SimDataFormats/CaloTest/interface/HcalTestHistoClass.h | #ifndef SimDataFormats_HcalTestHistoClass_H
#define SimDataFormats_HcalTestHistoClass_H
///////////////////////////////////////////////////////////////////////////////
// File: HcalTestHistoClass.h
// Histogram handling class for analysis in HcalTest
///////////////////////////////////////////////////////////////////////////////
#include "SimDataFormats/CaloHit/interface/CaloHit.h"
#include <string>
#include <vector>
#include <memory>
class HcalTestHistoClass {
public:
HcalTestHistoClass(int i) {}
explicit HcalTestHistoClass() {}
virtual ~HcalTestHistoClass() {}
void setCounters();
void fillLayers(double el[], double ho, double hbhe, double muxy[]);
void fillHits(std::vector<CaloHit>&);
void fillQie(int id,
double esimtot,
double eqietot,
int nGroup,
const std::vector<double>& longs,
const std::vector<double>& longq,
int nTower,
const std::vector<double>& latphi,
const std::vector<double>& latfs,
const std::vector<double>& latfq);
struct Layer {
Layer() {}
float e;
float muDist;
};
struct Hit {
Hit() {}
int layer;
int id;
float eta;
float phi;
float e;
float t;
float jitter;
};
struct QIE {
QIE() {}
float sim;
float qie;
int id;
std::vector<float> lats, latq;
std::vector<float> lngs, lngq;
std::vector<int> tow;
};
private:
const static int nLayersMAX = 20;
int nLayers;
std::vector<Layer> layers;
float eHO, eHBHE;
int nHits;
std::vector<Hit> hits;
int nQIE, nTowerQIE, nGroupQIE;
std::vector<QIE> qie;
};
#endif
|
KiboSoftware/kibo.sdk.java | auth/src/main/java/com/kibocommerce/sdk/auth/model/MozuAppDevContractsApplicationCapabilityItemRequest.java | <filename>auth/src/main/java/com/kibocommerce/sdk/auth/model/MozuAppDevContractsApplicationCapabilityItemRequest.java
/*
* Kibo AppDev Service
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: v1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.kibocommerce.sdk.auth.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* MozuAppDevContractsApplicationCapabilityItemRequest
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-09-26T13:42:29.731930-05:00[America/Chicago]")
public class MozuAppDevContractsApplicationCapabilityItemRequest {
public static final String SERIALIZED_NAME_PACKAGE_ID = "packageId";
@SerializedName(SERIALIZED_NAME_PACKAGE_ID)
private Integer packageId;
public static final String SERIALIZED_NAME_IS_IMPLEMENTED = "isImplemented";
@SerializedName(SERIALIZED_NAME_IS_IMPLEMENTED)
private Boolean isImplemented;
public static final String SERIALIZED_NAME_CAPABILITY_TYPE_ID = "capabilityTypeId";
@SerializedName(SERIALIZED_NAME_CAPABILITY_TYPE_ID)
private Integer capabilityTypeId;
public static final String SERIALIZED_NAME_CAPABILITY_TYPE_NAME = "capabilityTypeName";
@SerializedName(SERIALIZED_NAME_CAPABILITY_TYPE_NAME)
private String capabilityTypeName;
public MozuAppDevContractsApplicationCapabilityItemRequest packageId(Integer packageId) {
this.packageId = packageId;
return this;
}
/**
* Get packageId
* @return packageId
**/
@ApiModelProperty(value = "")
public Integer getPackageId() {
return packageId;
}
public void setPackageId(Integer packageId) {
this.packageId = packageId;
}
public MozuAppDevContractsApplicationCapabilityItemRequest isImplemented(Boolean isImplemented) {
this.isImplemented = isImplemented;
return this;
}
/**
* Get isImplemented
* @return isImplemented
**/
@ApiModelProperty(value = "")
public Boolean getIsImplemented() {
return isImplemented;
}
public void setIsImplemented(Boolean isImplemented) {
this.isImplemented = isImplemented;
}
public MozuAppDevContractsApplicationCapabilityItemRequest capabilityTypeId(Integer capabilityTypeId) {
this.capabilityTypeId = capabilityTypeId;
return this;
}
/**
* Get capabilityTypeId
* @return capabilityTypeId
**/
@ApiModelProperty(value = "")
public Integer getCapabilityTypeId() {
return capabilityTypeId;
}
public void setCapabilityTypeId(Integer capabilityTypeId) {
this.capabilityTypeId = capabilityTypeId;
}
public MozuAppDevContractsApplicationCapabilityItemRequest capabilityTypeName(String capabilityTypeName) {
this.capabilityTypeName = capabilityTypeName;
return this;
}
/**
* Get capabilityTypeName
* @return capabilityTypeName
**/
@ApiModelProperty(value = "")
public String getCapabilityTypeName() {
return capabilityTypeName;
}
public void setCapabilityTypeName(String capabilityTypeName) {
this.capabilityTypeName = capabilityTypeName;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MozuAppDevContractsApplicationCapabilityItemRequest mozuAppDevContractsApplicationCapabilityItemRequest = (MozuAppDevContractsApplicationCapabilityItemRequest) o;
return Objects.equals(this.packageId, mozuAppDevContractsApplicationCapabilityItemRequest.packageId) &&
Objects.equals(this.isImplemented, mozuAppDevContractsApplicationCapabilityItemRequest.isImplemented) &&
Objects.equals(this.capabilityTypeId, mozuAppDevContractsApplicationCapabilityItemRequest.capabilityTypeId) &&
Objects.equals(this.capabilityTypeName, mozuAppDevContractsApplicationCapabilityItemRequest.capabilityTypeName);
}
@Override
public int hashCode() {
return Objects.hash(packageId, isImplemented, capabilityTypeId, capabilityTypeName);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class MozuAppDevContractsApplicationCapabilityItemRequest {\n");
sb.append(" packageId: ").append(toIndentedString(packageId)).append("\n");
sb.append(" isImplemented: ").append(toIndentedString(isImplemented)).append("\n");
sb.append(" capabilityTypeId: ").append(toIndentedString(capabilityTypeId)).append("\n");
sb.append(" capabilityTypeName: ").append(toIndentedString(capabilityTypeName)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
mikheyrojo/spring-xml-to-java-converter | src/test/resources/pro/akvel/spring/converter/xml/expected/BeanWithPrimary.java | <reponame>mikheyrojo/spring-xml-to-java-converter<gh_stars>0
package pro.akvel.spring.converter.generator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* Generated Java based configuration
*
*/
@Configuration
public class BeanWithPrimary {
@Bean("BeanWithPrimary")
@Primary
public pro.akvel.spring.converter.testbean.BeanWithPrimary BeanWithPrimary() {
return new pro.akvel.spring.converter.testbean.BeanWithPrimary();
}
}
|
iplweb/django-bpp | src/bpp/migrations/0259_auto_20210421_2323.py | # Generated by Django 3.0.11 on 2021-04-21 21:23
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("pbn_api", "0008_auto_20210406_0530"),
("bpp", "0258_auto_20210407_2320"),
]
operations = [
migrations.RemoveField(
model_name="jezyk",
name="skrot_dla_pbn",
),
migrations.AddField(
model_name="jezyk",
name="pbn_uid",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="pbn_api.Language",
),
),
migrations.AlterField(
model_name="autor",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="jednostka",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="patent",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="praca_doktorska",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="praca_habilitacyjna",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="uczelnia",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="wydawnictwo_ciagle",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="wydawnictwo_zwarte",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
migrations.AlterField(
model_name="wydzial",
name="pbn_id",
field=models.IntegerField(
blank=True,
db_index=True,
help_text="[Pole o znaczeniu historycznym] Identyfikator w systemie Polskiej Bibliografii Naukowej (PBN)",
null=True,
unique=True,
verbose_name="[Przestarzałe] Identyfikator PBN",
),
),
]
|
ytuan996/smart-admin | smart-admin-service/smart-admin-api/src/main/java/com/gangquan360/smartadmin/module/position/domain/dto/PositionUpdateDTO.java | package com.gangquan360.smartadmin.module.position.domain.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 岗位
*
* @author zzr
*/
@Data
public class PositionUpdateDTO extends PositionAddDTO {
@ApiModelProperty("主键")
private Long id;
}
|
akashsuper2000/codechef-archive | MAXREM.py | n = int(input())
a = [int(j) for j in input().split()]
m1,m2 = 0,0
for i in a:
if(i>m1):
m2 = m1
m1 = i
print(m2)
|
AlexRogalskiy/Duino | libraries/Mitov/MitovEmbedded_Adafruit_NeoPixel/MitovEmbedded_Adafruit_NeoPixel.h | <filename>libraries/Mitov/MitovEmbedded_Adafruit_NeoPixel/MitovEmbedded_Adafruit_NeoPixel.h
/*--------------------------------------------------------------------
This file is part of the Adafruit NeoPixel library.
NeoPixel 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.
NeoPixel 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 NeoPixel. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------*/
#ifndef ADAFRUIT_NEOPIXEL_H
#define ADAFRUIT_NEOPIXEL_H
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#include <pins_arduino.h>
#endif
// The order of primary colors in the NeoPixel data stream can vary
// among device types, manufacturers and even different revisions of
// the same item. The third parameter to the MitovEmbedded_Adafruit_NeoPixel
// constructor encodes the per-pixel byte offsets of the red, green
// and blue primaries (plus white, if present) in the data stream --
// the following #defines provide an easier-to-use named version for
// each permutation. e.g. NEO_GRB indicates a NeoPixel-compatible
// device expecting three bytes per pixel, with the first byte
// containing the green value, second containing red and third
// containing blue. The in-memory representation of a chain of
// NeoPixels is the same as the data-stream order; no re-ordering of
// bytes is required when issuing data to the chain.
// Bits 5,4 of this value are the offset (0-3) from the first byte of
// a pixel to the location of the red color byte. Bits 3,2 are the
// green offset and 1,0 are the blue offset. If it is an RGBW-type
// device (supporting a white primary in addition to R,G,B), bits 7,6
// are the offset to the white byte...otherwise, bits 7,6 are set to
// the same value as 5,4 (red) to indicate an RGB (not RGBW) device.
// i.e. binary representation:
// 0bWWRRGGBB for RGBW devices
// 0bRRRRGGBB for RGB
// RGB NeoPixel permutations; white and red offsets are always same
// Offset: W R G B
#define NEO_RGB ((0 << 6) | (0 << 4) | (1 << 2) | (2))
#define NEO_RBG ((0 << 6) | (0 << 4) | (2 << 2) | (1))
#define NEO_GRB ((1 << 6) | (1 << 4) | (0 << 2) | (2))
#define NEO_GBR ((2 << 6) | (2 << 4) | (0 << 2) | (1))
#define NEO_BRG ((1 << 6) | (1 << 4) | (2 << 2) | (0))
#define NEO_BGR ((2 << 6) | (2 << 4) | (1 << 2) | (0))
// RGBW NeoPixel permutations; all 4 offsets are distinct
// Offset: W R G B
#define NEO_WRGB ((0 << 6) | (1 << 4) | (2 << 2) | (3))
#define NEO_WRBG ((0 << 6) | (1 << 4) | (3 << 2) | (2))
#define NEO_WGRB ((0 << 6) | (2 << 4) | (1 << 2) | (3))
#define NEO_WGBR ((0 << 6) | (3 << 4) | (1 << 2) | (2))
#define NEO_WBRG ((0 << 6) | (2 << 4) | (3 << 2) | (1))
#define NEO_WBGR ((0 << 6) | (3 << 4) | (2 << 2) | (1))
#define NEO_RWGB ((1 << 6) | (0 << 4) | (2 << 2) | (3))
#define NEO_RWBG ((1 << 6) | (0 << 4) | (3 << 2) | (2))
#define NEO_RGWB ((2 << 6) | (0 << 4) | (1 << 2) | (3))
#define NEO_RGBW ((3 << 6) | (0 << 4) | (1 << 2) | (2))
#define NEO_RBWG ((2 << 6) | (0 << 4) | (3 << 2) | (1))
#define NEO_RBGW ((3 << 6) | (0 << 4) | (2 << 2) | (1))
#define NEO_GWRB ((1 << 6) | (2 << 4) | (0 << 2) | (3))
#define NEO_GWBR ((1 << 6) | (3 << 4) | (0 << 2) | (2))
#define NEO_GRWB ((2 << 6) | (1 << 4) | (0 << 2) | (3))
#define NEO_GRBW ((3 << 6) | (1 << 4) | (0 << 2) | (2))
#define NEO_GBWR ((2 << 6) | (3 << 4) | (0 << 2) | (1))
#define NEO_GBRW ((3 << 6) | (2 << 4) | (0 << 2) | (1))
#define NEO_BWRG ((1 << 6) | (2 << 4) | (3 << 2) | (0))
#define NEO_BWGR ((1 << 6) | (3 << 4) | (2 << 2) | (0))
#define NEO_BRWG ((2 << 6) | (1 << 4) | (3 << 2) | (0))
#define NEO_BRGW ((3 << 6) | (1 << 4) | (2 << 2) | (0))
#define NEO_BGWR ((2 << 6) | (3 << 4) | (1 << 2) | (0))
#define NEO_BGRW ((3 << 6) | (2 << 4) | (1 << 2) | (0))
// Add NEO_KHZ400 to the color order value to indicate a 400 KHz
// device. All but the earliest v1 NeoPixels expect an 800 KHz data
// stream, this is the default if unspecified. Because flash space
// is very limited on ATtiny devices (e.g. Trinket, Gemma), v1
// NeoPixels aren't handled by default on those chips, though it can
// be enabled by removing the ifndef/endif below -- but code will be
// bigger. Conversely, can disable the NEO_KHZ400 line on other MCUs
// to remove v1 support and save a little space.
#define NEO_KHZ800 0x0000 // 800 KHz datastream
#ifndef __AVR_ATtiny85__
#define NEO_KHZ400 0x0100 // 400 KHz datastream
#endif
// If 400 KHz support is enabled, the third parameter to the constructor
// requires a 16-bit value (in order to select 400 vs 800 KHz speed).
// If only 800 KHz is enabled (as is default on ATtiny), an 8-bit value
// is sufficient to encode pixel color order, saving some space.
#ifdef NEO_KHZ400
typedef uint16_t neoPixelType;
#else
typedef uint8_t neoPixelType;
#endif
class MitovEmbedded_Adafruit_NeoPixel {
public:
// Constructor: number of LEDs, pin number, LED type
MitovEmbedded_Adafruit_NeoPixel(uint16_t n, uint8_t p=6, neoPixelType t=NEO_GRB + NEO_KHZ800);
MitovEmbedded_Adafruit_NeoPixel(void);
~MitovEmbedded_Adafruit_NeoPixel();
void
begin(void),
show(void),
setPin(uint8_t p),
setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b),
setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w),
setPixelColor(uint16_t n, uint32_t c),
setBrightness(uint8_t),
clear(),
updateLength(uint16_t n),
updateType(neoPixelType t);
uint8_t
*getPixels(void) const,
getBrightness(void) const;
uint16_t
numPixels(void) const;
static uint32_t
Color(uint8_t r, uint8_t g, uint8_t b),
Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w);
uint32_t
getPixelColor(uint16_t n) const;
inline bool
canShow(void) { return (micros() - endTime) >= 50L; }
private:
boolean
#ifdef NEO_KHZ400 // If 400 KHz NeoPixel support enabled...
is800KHz, // ...true if 800 KHz pixels
#endif
begun; // true if begin() previously called
uint16_t
numLEDs, // Number of RGB LEDs in strip
numBytes; // Size of 'pixels' buffer below (3 or 4 bytes/pixel)
int8_t
pin; // Output pin number (-1 if not yet set)
uint8_t
brightness,
*pixels, // Holds LED color values (3 or 4 bytes each)
rOffset, // Index of red byte within each 3- or 4-byte pixel
gOffset, // Index of green byte
bOffset, // Index of blue byte
wOffset; // Index of white byte (same as rOffset if no white)
uint32_t
endTime; // Latch timing reference
#ifdef __AVR__
volatile uint8_t
*port; // Output PORT register
uint8_t
pinMask; // Output PORT bitmask
#endif
};
// Constructor when length, pin and type are known at compile-time:
MitovEmbedded_Adafruit_NeoPixel::MitovEmbedded_Adafruit_NeoPixel(uint16_t n, uint8_t p, neoPixelType t) :
begun(false), brightness(0), pixels(nullptr), endTime(0)
{
updateType(t);
updateLength(n);
setPin(p);
}
// via <NAME>/neophob: empty constructor is used when strand length
// isn't known at compile-time; situations where program config might be
// read from internal flash memory or an SD card, or arrive via serial
// command. If using this constructor, MUST follow up with updateType(),
// updateLength(), etc. to establish the strand type, length and pin number!
MitovEmbedded_Adafruit_NeoPixel::MitovEmbedded_Adafruit_NeoPixel() :
#ifdef NEO_KHZ400
is800KHz(true),
#endif
begun(false), numLEDs(0), numBytes(0), pin(-1), brightness(0), pixels(nullptr),
rOffset(1), gOffset(0), bOffset(2), wOffset(1), endTime(0)
{
}
MitovEmbedded_Adafruit_NeoPixel::~MitovEmbedded_Adafruit_NeoPixel() {
if(pixels) free(pixels);
if(pin >= 0) pinMode(pin, INPUT);
}
void MitovEmbedded_Adafruit_NeoPixel::begin(void) {
if(pin >= 0) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
begun = true;
}
void MitovEmbedded_Adafruit_NeoPixel::updateLength(uint16_t n) {
if(pixels) free(pixels); // Free existing data (if any)
// Allocate new data -- note: ALL PIXELS ARE CLEARED
numBytes = n * ((wOffset == rOffset) ? 3 : 4);
if((pixels = (uint8_t *)malloc(numBytes))) {
memset(pixels, 0, numBytes);
numLEDs = n;
} else {
numLEDs = numBytes = 0;
}
}
void MitovEmbedded_Adafruit_NeoPixel::updateType(neoPixelType t) {
boolean oldThreeBytesPerPixel = (wOffset == rOffset); // false if RGBW
wOffset = (t >> 6) & 0b11; // See notes in header file
rOffset = (t >> 4) & 0b11; // regarding R/G/B/W offsets
gOffset = (t >> 2) & 0b11;
bOffset = t & 0b11;
#ifdef NEO_KHZ400
is800KHz = (t < 256); // 400 KHz flag is 1<<8
#endif
// If bytes-per-pixel has changed (and pixel data was previously
// allocated), re-allocate to new size. Will clear any data.
if(pixels) {
boolean newThreeBytesPerPixel = (wOffset == rOffset);
if(newThreeBytesPerPixel != oldThreeBytesPerPixel) updateLength(numLEDs);
}
}
#if defined(ESP8266) || defined(ESP32)
#ifdef ESP8266
#include <eagle_soc.h>
#endif
static uint32_t _getCycleCount(void) __attribute__((always_inline));
static inline uint32_t _getCycleCount(void) {
uint32_t ccount;
__asm__ __volatile__("rsr %0,ccount":"=a" (ccount));
return ccount;
}
#ifdef ESP8266
extern "C" void ICACHE_RAM_ATTR espShow(
uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) {
#else
extern "C" void espShow(
uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) {
#endif
#define CYCLES_800_T0H (F_CPU / 2500000) // 0.4us
#define CYCLES_800_T1H (F_CPU / 1250000) // 0.8us
#define CYCLES_800 (F_CPU / 800000) // 1.25us per bit
#define CYCLES_400_T0H (F_CPU / 2000000) // 0.5uS
#define CYCLES_400_T1H (F_CPU / 833333) // 1.2us
#define CYCLES_400 (F_CPU / 400000) // 2.5us per bit
uint8_t *p, *end, pix, mask;
uint32_t t, time0, time1, period, c, startTime, pinMask;
pinMask = _BV(pin);
p = pixels;
end = p + numBytes;
pix = *p++;
mask = 0x80;
startTime = 0;
#ifdef NEO_KHZ400
if(is800KHz) {
#endif
time0 = CYCLES_800_T0H;
time1 = CYCLES_800_T1H;
period = CYCLES_800;
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
time0 = CYCLES_400_T0H;
time1 = CYCLES_400_T1H;
period = CYCLES_400;
}
#endif
for(t = time0;; t = time0) {
if(pix & mask) t = time1; // Bit high duration
while(((c = _getCycleCount()) - startTime) < period); // Wait for bit start
#ifdef ESP8266
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high
#else
gpio_set_level(gpio_num_t( pin ), HIGH);
#endif
startTime = c; // Save start time
while(((c = _getCycleCount()) - startTime) < t); // Wait high duration
#ifdef ESP8266
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low
#else
gpio_set_level(gpio_num_t( pin ), LOW);
#endif
if(!(mask >>= 1)) { // Next bit/byte
if(p >= end) break;
pix = *p++;
mask = 0x80;
}
}
while((_getCycleCount() - startTime) < period); // Wait for last bit
}
#endif // ESP8266
void MitovEmbedded_Adafruit_NeoPixel::show(void) {
if(!pixels) return;
// Data latch = 300+ microsecond pause in the output stream. Rather than
// put a delay at the end of the function, the ending time is noted and
// the function will simply hold off (if needed) on issuing the
// subsequent round of data until the latch time has elapsed. This
// allows the mainline code to start generating the next frame of data
// rather than stalling for the latch.
while(!canShow());
// endTime is a private member (rather than global var) so that mutliple
// instances on different pins can be quickly issued in succession (each
// instance doesn't delay the next).
// In order to make this code runtime-configurable to work with any pin,
// SBI/CBI instructions are eschewed in favor of full PORT writes via the
// OUT or ST instructions. It relies on two facts: that peripheral
// functions (such as PWM) take precedence on output pins, so our PORT-
// wide writes won't interfere, and that interrupts are globally disabled
// while data is being issued to the LEDs, so no other code will be
// accessing the PORT. The code takes an initial 'snapshot' of the PORT
// state, computes 'pin high' and 'pin low' values, and writes these back
// to the PORT register as needed.
// NRF52 may use PWM + DMA (if available), may not need to disable interrupt
#ifndef NRF52
noInterrupts(); // Need 100% focus on instruction timing
#endif
#ifdef __AVR__
// AVR MCUs -- ATmega & ATtiny (no XMEGA) ---------------------------------
volatile uint16_t
i = numBytes; // Loop counter
volatile uint8_t
*ptr = pixels, // Pointer to next byte
b = *ptr++, // Current byte value
hi, // PORT w/output bit set high
lo; // PORT w/output bit set low
// Hand-tuned assembly code issues data to the LED drivers at a specific
// rate. There's separate code for different CPU speeds (8, 12, 16 MHz)
// for both the WS2811 (400 KHz) and WS2812 (800 KHz) drivers. The
// datastream timing for the LED drivers allows a little wiggle room each
// way (listed in the datasheets), so the conditions for compiling each
// case are set up for a range of frequencies rather than just the exact
// 8, 12 or 16 MHz values, permitting use with some close-but-not-spot-on
// devices (e.g. 16.5 MHz DigiSpark). The ranges were arrived at based
// on the datasheet figures and have not been extensively tested outside
// the canonical 8/12/16 MHz speeds; there's no guarantee these will work
// close to the extremes (or possibly they could be pushed further).
// Keep in mind only one CPU speed case actually gets compiled; the
// resulting program isn't as massive as it might look from source here.
// 8 MHz(ish) AVR ---------------------------------------------------------
#if (F_CPU >= 7400000UL) && (F_CPU <= 9500000UL)
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
volatile uint8_t n1, n2 = 0; // First, next bits out
// Squeezing an 800 KHz stream out of an 8 MHz chip requires code
// specific to each PORT register. At present this is only written
// to work with pins on PORTD or PORTB, the most likely use case --
// this covers all the pins on the Adafruit Flora and the bulk of
// digital pins on the Arduino Pro 8 MHz (keep in mind, this code
// doesn't even get compiled for 16 MHz boards like the Uno, Mega,
// Leonardo, etc., so don't bother extending this out of hand).
// Additional PORTs could be added if you really need them, just
// duplicate the else and loop and change the PORT. Each add'l
// PORT will require about 150(ish) bytes of program space.
// 10 instruction clocks per bit: HHxxxxxLLL
// OUT instructions: ^ ^ ^ (T=0,2,7)
// PORTD OUTPUT ----------------------------------------------------
#if defined(PORTD)
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
if(port == &PORTD) {
#endif // defined(PORTB/C/F)
hi = PORTD | pinMask;
lo = PORTD & ~pinMask;
n1 = lo;
if(b & 0x80) n1 = hi;
// Dirty trick: RJMPs proceeding to the next instruction are used
// to delay two clock cycles in one instruction word (rather than
// using two NOPs). This was necessary in order to squeeze the
// loop down to exactly 64 words -- the maximum possible for a
// relative branch.
asm volatile(
"headD:" "\n\t" // Clk Pseudocode
// Bit 7:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo
"out %[port] , %[n1]" "\n\t" // 1 PORT = n1
"rjmp .+0" "\n\t" // 2 nop nop
"sbrc %[byte] , 6" "\n\t" // 1-2 if(b & 0x40)
"mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"rjmp .+0" "\n\t" // 2 nop nop
// Bit 6:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo
"out %[port] , %[n2]" "\n\t" // 1 PORT = n2
"rjmp .+0" "\n\t" // 2 nop nop
"sbrc %[byte] , 5" "\n\t" // 1-2 if(b & 0x20)
"mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"rjmp .+0" "\n\t" // 2 nop nop
// Bit 5:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo
"out %[port] , %[n1]" "\n\t" // 1 PORT = n1
"rjmp .+0" "\n\t" // 2 nop nop
"sbrc %[byte] , 4" "\n\t" // 1-2 if(b & 0x10)
"mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"rjmp .+0" "\n\t" // 2 nop nop
// Bit 4:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo
"out %[port] , %[n2]" "\n\t" // 1 PORT = n2
"rjmp .+0" "\n\t" // 2 nop nop
"sbrc %[byte] , 3" "\n\t" // 1-2 if(b & 0x08)
"mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"rjmp .+0" "\n\t" // 2 nop nop
// Bit 3:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo
"out %[port] , %[n1]" "\n\t" // 1 PORT = n1
"rjmp .+0" "\n\t" // 2 nop nop
"sbrc %[byte] , 2" "\n\t" // 1-2 if(b & 0x04)
"mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"rjmp .+0" "\n\t" // 2 nop nop
// Bit 2:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo
"out %[port] , %[n2]" "\n\t" // 1 PORT = n2
"rjmp .+0" "\n\t" // 2 nop nop
"sbrc %[byte] , 1" "\n\t" // 1-2 if(b & 0x02)
"mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"rjmp .+0" "\n\t" // 2 nop nop
// Bit 1:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo
"out %[port] , %[n1]" "\n\t" // 1 PORT = n1
"rjmp .+0" "\n\t" // 2 nop nop
"sbrc %[byte] , 0" "\n\t" // 1-2 if(b & 0x01)
"mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"sbiw %[count], 1" "\n\t" // 2 i-- (don't act on Z flag yet)
// Bit 0:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo
"out %[port] , %[n2]" "\n\t" // 1 PORT = n2
"ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++
"sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 0x80)
"mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo
"brne headD" "\n" // 2 while(i) (Z flag set above)
: [byte] "+r" (b),
[n1] "+r" (n1),
[n2] "+r" (n2),
[count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTD)),
[ptr] "e" (ptr),
[hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
} else // other PORT(s)
#endif // defined(PORTB/C/F)
#endif // defined(PORTD)
// PORTB OUTPUT ----------------------------------------------------
#if defined(PORTB)
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
if(port == &PORTB) {
#endif // defined(PORTD/C/F)
// Same as above, just switched to PORTB and stripped of comments.
hi = PORTB | pinMask;
lo = PORTB & ~pinMask;
n1 = lo;
if(b & 0x80) n1 = hi;
asm volatile(
"headB:" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 6" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 5" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 4" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 3" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 2" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 1" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 0" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"sbiw %[count], 1" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"ld %[byte] , %a[ptr]+" "\n\t"
"sbrc %[byte] , 7" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"brne headB" "\n"
: [byte] "+r" (b), [n1] "+r" (n1), [n2] "+r" (n2), [count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTB)), [ptr] "e" (ptr), [hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
}
#endif
#if defined(PORTC) || defined(PORTF)
else
#endif // defined(PORTC/F)
#endif // defined(PORTB)
// PORTC OUTPUT ----------------------------------------------------
#if defined(PORTC)
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
if(port == &PORTC) {
#endif // defined(PORTD/B/F)
// Same as above, just switched to PORTC and stripped of comments.
hi = PORTC | pinMask;
lo = PORTC & ~pinMask;
n1 = lo;
if(b & 0x80) n1 = hi;
asm volatile(
"headC:" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 6" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 5" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 4" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 3" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 2" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 1" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 0" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"sbiw %[count], 1" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"ld %[byte] , %a[ptr]+" "\n\t"
"sbrc %[byte] , 7" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"brne headC" "\n"
: [byte] "+r" (b), [n1] "+r" (n1), [n2] "+r" (n2), [count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTC)), [ptr] "e" (ptr), [hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
}
#endif // defined(PORTD/B/F)
#if defined(PORTF)
else
#endif
#endif // defined(PORTC)
// PORTF OUTPUT ----------------------------------------------------
#if defined(PORTF)
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
if(port == &PORTF) {
#endif // defined(PORTD/B/C)
hi = PORTF | pinMask;
lo = PORTF & ~pinMask;
n1 = lo;
if(b & 0x80) n1 = hi;
asm volatile(
"headF:" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 6" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 5" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 4" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 3" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 2" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 1" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"rjmp .+0" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n2] , %[lo]" "\n\t"
"out %[port] , %[n1]" "\n\t"
"rjmp .+0" "\n\t"
"sbrc %[byte] , 0" "\n\t"
"mov %[n2] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"sbiw %[count], 1" "\n\t"
"out %[port] , %[hi]" "\n\t"
"mov %[n1] , %[lo]" "\n\t"
"out %[port] , %[n2]" "\n\t"
"ld %[byte] , %a[ptr]+" "\n\t"
"sbrc %[byte] , 7" "\n\t"
"mov %[n1] , %[hi]" "\n\t"
"out %[port] , %[lo]" "\n\t"
"brne headF" "\n"
: [byte] "+r" (b), [n1] "+r" (n1), [n2] "+r" (n2), [count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTF)), [ptr] "e" (ptr), [hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
}
#endif // defined(PORTD/B/C)
#endif // defined(PORTF)
#ifdef NEO_KHZ400
} else { // end 800 KHz, do 400 KHz
// Timing is more relaxed; unrolling the inner loop for each bit is
// not necessary. Still using the peculiar RJMPs as 2X NOPs, not out
// of need but just to trim the code size down a little.
// This 400-KHz-datastream-on-8-MHz-CPU code is not quite identical
// to the 800-on-16 code later -- the hi/lo timing between WS2811 and
// WS2812 is not simply a 2:1 scale!
// 20 inst. clocks per bit: HHHHxxxxxxLLLLLLLLLL
// ST instructions: ^ ^ ^ (T=0,4,10)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile(
"head20:" "\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 128)
"mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 4)
"st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 6)
"mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 7)
"dec %[bit]" "\n\t" // 1 bit-- (T = 8)
"breq nextbyte20" "\n\t" // 1-2 if(bit == 0)
"rol %[byte]" "\n\t" // 1 b <<= 1 (T = 10)
"st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 12)
"rjmp .+0" "\n\t" // 2 nop nop (T = 14)
"rjmp .+0" "\n\t" // 2 nop nop (T = 16)
"rjmp .+0" "\n\t" // 2 nop nop (T = 18)
"rjmp head20" "\n\t" // 2 -> head20 (next bit out)
"nextbyte20:" "\n\t" // (T = 10)
"st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 12)
"nop" "\n\t" // 1 nop (T = 13)
"ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 14)
"ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 16)
"sbiw %[count], 1" "\n\t" // 2 i-- (T = 18)
"brne head20" "\n" // 2 if(i != 0) -> (next byte)
: [port] "+e" (port),
[byte] "+r" (b),
[bit] "+r" (bit),
[next] "+r" (next),
[count] "+w" (i)
: [hi] "r" (hi),
[lo] "r" (lo),
[ptr] "e" (ptr));
}
#endif // NEO_KHZ400
// 12 MHz(ish) AVR --------------------------------------------------------
#elif (F_CPU >= 11100000UL) && (F_CPU <= 14300000UL)
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
// In the 12 MHz case, an optimized 800 KHz datastream (no dead time
// between bytes) requires a PORT-specific loop similar to the 8 MHz
// code (but a little more relaxed in this case).
// 15 instruction clocks per bit: HHHHxxxxxxLLLLL
// OUT instructions: ^ ^ ^ (T=0,4,10)
volatile uint8_t next;
// PORTD OUTPUT ----------------------------------------------------
#if defined(PORTD)
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
if(port == &PORTD) {
#endif // defined(PORTB/C/F)
hi = PORTD | pinMask;
lo = PORTD & ~pinMask;
next = lo;
if(b & 0x80) next = hi;
// Don't "optimize" the OUT calls into the bitTime subroutine;
// we're exploiting the RCALL and RET as 3- and 4-cycle NOPs!
asm volatile(
"headD:" "\n\t" // (T = 0)
"out %[port], %[hi]" "\n\t" // (T = 1)
"rcall bitTimeD" "\n\t" // Bit 7 (T = 15)
"out %[port], %[hi]" "\n\t"
"rcall bitTimeD" "\n\t" // Bit 6
"out %[port], %[hi]" "\n\t"
"rcall bitTimeD" "\n\t" // Bit 5
"out %[port], %[hi]" "\n\t"
"rcall bitTimeD" "\n\t" // Bit 4
"out %[port], %[hi]" "\n\t"
"rcall bitTimeD" "\n\t" // Bit 3
"out %[port], %[hi]" "\n\t"
"rcall bitTimeD" "\n\t" // Bit 2
"out %[port], %[hi]" "\n\t"
"rcall bitTimeD" "\n\t" // Bit 1
// Bit 0:
"out %[port] , %[hi]" "\n\t" // 1 PORT = hi (T = 1)
"rjmp .+0" "\n\t" // 2 nop nop (T = 3)
"ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 5)
"out %[port] , %[next]" "\n\t" // 1 PORT = next (T = 6)
"mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 7)
"sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 0x80) (T = 8)
"mov %[next] , %[hi]" "\n\t" // 0-1 next = hi (T = 9)
"nop" "\n\t" // 1 (T = 10)
"out %[port] , %[lo]" "\n\t" // 1 PORT = lo (T = 11)
"sbiw %[count], 1" "\n\t" // 2 i-- (T = 13)
"brne headD" "\n\t" // 2 if(i != 0) -> (next byte)
"rjmp doneD" "\n\t"
"bitTimeD:" "\n\t" // nop nop nop (T = 4)
"out %[port], %[next]" "\n\t" // 1 PORT = next (T = 5)
"mov %[next], %[lo]" "\n\t" // 1 next = lo (T = 6)
"rol %[byte]" "\n\t" // 1 b <<= 1 (T = 7)
"sbrc %[byte], 7" "\n\t" // 1-2 if(b & 0x80) (T = 8)
"mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 9)
"nop" "\n\t" // 1 (T = 10)
"out %[port], %[lo]" "\n\t" // 1 PORT = lo (T = 11)
"ret" "\n\t" // 4 nop nop nop nop (T = 15)
"doneD:" "\n"
: [byte] "+r" (b),
[next] "+r" (next),
[count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTD)),
[ptr] "e" (ptr),
[hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
} else // other PORT(s)
#endif // defined(PORTB/C/F)
#endif // defined(PORTD)
// PORTB OUTPUT ----------------------------------------------------
#if defined(PORTB)
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
if(port == &PORTB) {
#endif // defined(PORTD/C/F)
hi = PORTB | pinMask;
lo = PORTB & ~pinMask;
next = lo;
if(b & 0x80) next = hi;
// Same as above, just set for PORTB & stripped of comments
asm volatile(
"headB:" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeB" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeB" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeB" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeB" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeB" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeB" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeB" "\n\t"
"out %[port] , %[hi]" "\n\t"
"rjmp .+0" "\n\t"
"ld %[byte] , %a[ptr]+" "\n\t"
"out %[port] , %[next]" "\n\t"
"mov %[next] , %[lo]" "\n\t"
"sbrc %[byte] , 7" "\n\t"
"mov %[next] , %[hi]" "\n\t"
"nop" "\n\t"
"out %[port] , %[lo]" "\n\t"
"sbiw %[count], 1" "\n\t"
"brne headB" "\n\t"
"rjmp doneB" "\n\t"
"bitTimeB:" "\n\t"
"out %[port], %[next]" "\n\t"
"mov %[next], %[lo]" "\n\t"
"rol %[byte]" "\n\t"
"sbrc %[byte], 7" "\n\t"
"mov %[next], %[hi]" "\n\t"
"nop" "\n\t"
"out %[port], %[lo]" "\n\t"
"ret" "\n\t"
"doneB:" "\n"
: [byte] "+r" (b), [next] "+r" (next), [count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTB)), [ptr] "e" (ptr), [hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
}
#endif
#if defined(PORTC) || defined(PORTF)
else
#endif // defined(PORTC/F)
#endif // defined(PORTB)
// PORTC OUTPUT ----------------------------------------------------
#if defined(PORTC)
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
if(port == &PORTC) {
#endif // defined(PORTD/B/F)
hi = PORTC | pinMask;
lo = PORTC & ~pinMask;
next = lo;
if(b & 0x80) next = hi;
// Same as above, just set for PORTC & stripped of comments
asm volatile(
"headC:" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port] , %[hi]" "\n\t"
"rjmp .+0" "\n\t"
"ld %[byte] , %a[ptr]+" "\n\t"
"out %[port] , %[next]" "\n\t"
"mov %[next] , %[lo]" "\n\t"
"sbrc %[byte] , 7" "\n\t"
"mov %[next] , %[hi]" "\n\t"
"nop" "\n\t"
"out %[port] , %[lo]" "\n\t"
"sbiw %[count], 1" "\n\t"
"brne headC" "\n\t"
"rjmp doneC" "\n\t"
"bitTimeC:" "\n\t"
"out %[port], %[next]" "\n\t"
"mov %[next], %[lo]" "\n\t"
"rol %[byte]" "\n\t"
"sbrc %[byte], 7" "\n\t"
"mov %[next], %[hi]" "\n\t"
"nop" "\n\t"
"out %[port], %[lo]" "\n\t"
"ret" "\n\t"
"doneC:" "\n"
: [byte] "+r" (b), [next] "+r" (next), [count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTC)), [ptr] "e" (ptr), [hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
}
#endif // defined(PORTD/B/F)
#if defined(PORTF)
else
#endif
#endif // defined(PORTC)
// PORTF OUTPUT ----------------------------------------------------
#if defined(PORTF)
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
if(port == &PORTF) {
#endif // defined(PORTD/B/C)
hi = PORTF | pinMask;
lo = PORTF & ~pinMask;
next = lo;
if(b & 0x80) next = hi;
// Same as above, just set for PORTF & stripped of comments
asm volatile(
"headF:" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port], %[hi]" "\n\t"
"rcall bitTimeC" "\n\t"
"out %[port] , %[hi]" "\n\t"
"rjmp .+0" "\n\t"
"ld %[byte] , %a[ptr]+" "\n\t"
"out %[port] , %[next]" "\n\t"
"mov %[next] , %[lo]" "\n\t"
"sbrc %[byte] , 7" "\n\t"
"mov %[next] , %[hi]" "\n\t"
"nop" "\n\t"
"out %[port] , %[lo]" "\n\t"
"sbiw %[count], 1" "\n\t"
"brne headF" "\n\t"
"rjmp doneC" "\n\t"
"bitTimeC:" "\n\t"
"out %[port], %[next]" "\n\t"
"mov %[next], %[lo]" "\n\t"
"rol %[byte]" "\n\t"
"sbrc %[byte], 7" "\n\t"
"mov %[next], %[hi]" "\n\t"
"nop" "\n\t"
"out %[port], %[lo]" "\n\t"
"ret" "\n\t"
"doneC:" "\n"
: [byte] "+r" (b), [next] "+r" (next), [count] "+w" (i)
: [port] "I" (_SFR_IO_ADDR(PORTF)), [ptr] "e" (ptr), [hi] "r" (hi),
[lo] "r" (lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
}
#endif // defined(PORTD/B/C)
#endif // defined(PORTF)
#ifdef NEO_KHZ400
} else { // 400 KHz
// 30 instruction clocks per bit: HHHHHHxxxxxxxxxLLLLLLLLLLLLLLL
// ST instructions: ^ ^ ^ (T=0,6,15)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile(
"head30:" "\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 128)
"mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 4)
"rjmp .+0" "\n\t" // 2 nop nop (T = 6)
"st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 8)
"rjmp .+0" "\n\t" // 2 nop nop (T = 10)
"rjmp .+0" "\n\t" // 2 nop nop (T = 12)
"rjmp .+0" "\n\t" // 2 nop nop (T = 14)
"nop" "\n\t" // 1 nop (T = 15)
"st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 17)
"rjmp .+0" "\n\t" // 2 nop nop (T = 19)
"dec %[bit]" "\n\t" // 1 bit-- (T = 20)
"breq nextbyte30" "\n\t" // 1-2 if(bit == 0)
"rol %[byte]" "\n\t" // 1 b <<= 1 (T = 22)
"rjmp .+0" "\n\t" // 2 nop nop (T = 24)
"rjmp .+0" "\n\t" // 2 nop nop (T = 26)
"rjmp .+0" "\n\t" // 2 nop nop (T = 28)
"rjmp head30" "\n\t" // 2 -> head30 (next bit out)
"nextbyte30:" "\n\t" // (T = 22)
"nop" "\n\t" // 1 nop (T = 23)
"ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 24)
"ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 26)
"sbiw %[count], 1" "\n\t" // 2 i-- (T = 28)
"brne head30" "\n" // 1-2 if(i != 0) -> (next byte)
: [port] "+e" (port),
[byte] "+r" (b),
[bit] "+r" (bit),
[next] "+r" (next),
[count] "+w" (i)
: [hi] "r" (hi),
[lo] "r" (lo),
[ptr] "e" (ptr));
}
#endif // NEO_KHZ400
// 16 MHz(ish) AVR --------------------------------------------------------
#elif (F_CPU >= 15400000UL) && (F_CPU <= 19000000L)
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
// WS2811 and WS2812 have different hi/lo duty cycles; this is
// similar but NOT an exact copy of the prior 400-on-8 code.
// 20 inst. clocks per bit: HHHHHxxxxxxxxLLLLLLL
// ST instructions: ^ ^ ^ (T=0,5,13)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile(
"head20:" "\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte], 7" "\n\t" // 1-2 if(b & 128)
"mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 4)
"dec %[bit]" "\n\t" // 1 bit-- (T = 5)
"st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 7)
"mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 8)
"breq nextbyte20" "\n\t" // 1-2 if(bit == 0) (from dec above)
"rol %[byte]" "\n\t" // 1 b <<= 1 (T = 10)
"rjmp .+0" "\n\t" // 2 nop nop (T = 12)
"nop" "\n\t" // 1 nop (T = 13)
"st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 15)
"nop" "\n\t" // 1 nop (T = 16)
"rjmp .+0" "\n\t" // 2 nop nop (T = 18)
"rjmp head20" "\n\t" // 2 -> head20 (next bit out)
"nextbyte20:" "\n\t" // (T = 10)
"ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 11)
"ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 13)
"st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 15)
"nop" "\n\t" // 1 nop (T = 16)
"sbiw %[count], 1" "\n\t" // 2 i-- (T = 18)
"brne head20" "\n" // 2 if(i != 0) -> (next byte)
: [port] "+e" (port),
[byte] "+r" (b),
[bit] "+r" (bit),
[next] "+r" (next),
[count] "+w" (i)
: [ptr] "e" (ptr),
[hi] "r" (hi),
[lo] "r" (lo));
#ifdef NEO_KHZ400
} else { // 400 KHz
// The 400 KHz clock on 16 MHz MCU is the most 'relaxed' version.
// 40 inst. clocks per bit: HHHHHHHHxxxxxxxxxxxxLLLLLLLLLLLLLLLLLLLL
// ST instructions: ^ ^ ^ (T=0,8,20)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile(
"head40:" "\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 128)
"mov %[next] , %[hi]" "\n\t" // 0-1 next = hi (T = 4)
"rjmp .+0" "\n\t" // 2 nop nop (T = 6)
"rjmp .+0" "\n\t" // 2 nop nop (T = 8)
"st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 10)
"rjmp .+0" "\n\t" // 2 nop nop (T = 12)
"rjmp .+0" "\n\t" // 2 nop nop (T = 14)
"rjmp .+0" "\n\t" // 2 nop nop (T = 16)
"rjmp .+0" "\n\t" // 2 nop nop (T = 18)
"rjmp .+0" "\n\t" // 2 nop nop (T = 20)
"st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 22)
"nop" "\n\t" // 1 nop (T = 23)
"mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 24)
"dec %[bit]" "\n\t" // 1 bit-- (T = 25)
"breq nextbyte40" "\n\t" // 1-2 if(bit == 0)
"rol %[byte]" "\n\t" // 1 b <<= 1 (T = 27)
"nop" "\n\t" // 1 nop (T = 28)
"rjmp .+0" "\n\t" // 2 nop nop (T = 30)
"rjmp .+0" "\n\t" // 2 nop nop (T = 32)
"rjmp .+0" "\n\t" // 2 nop nop (T = 34)
"rjmp .+0" "\n\t" // 2 nop nop (T = 36)
"rjmp .+0" "\n\t" // 2 nop nop (T = 38)
"rjmp head40" "\n\t" // 2 -> head40 (next bit out)
"nextbyte40:" "\n\t" // (T = 27)
"ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 28)
"ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 30)
"rjmp .+0" "\n\t" // 2 nop nop (T = 32)
"st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 34)
"rjmp .+0" "\n\t" // 2 nop nop (T = 36)
"sbiw %[count], 1" "\n\t" // 2 i-- (T = 38)
"brne head40" "\n" // 1-2 if(i != 0) -> (next byte)
: [port] "+e" (port),
[byte] "+r" (b),
[bit] "+r" (bit),
[next] "+r" (next),
[count] "+w" (i)
: [ptr] "e" (ptr),
[hi] "r" (hi),
[lo] "r" (lo));
}
#endif // NEO_KHZ400
#else
#error "CPU SPEED NOT SUPPORTED"
#endif // end F_CPU ifdefs on __AVR__
// END AVR ----------------------------------------------------------------
#elif defined(__arm__)
// ARM MCUs -- Teensy 3.0, 3.1, LC, Arduino Due ---------------------------
#if defined(TEENSYDUINO) && defined(KINETISK) // Teensy 3.0, 3.1, 3.2, 3.5, 3.6
#define CYCLES_800_T0H (F_CPU / 4000000)
#define CYCLES_800_T1H (F_CPU / 1250000)
#define CYCLES_800 (F_CPU / 800000)
#define CYCLES_400_T0H (F_CPU / 2000000)
#define CYCLES_400_T1H (F_CPU / 833333)
#define CYCLES_400 (F_CPU / 400000)
uint8_t *p = pixels,
*end = p + numBytes, pix, mask;
volatile uint8_t *set = portSetRegister(pin),
*clr = portClearRegister(pin);
uint32_t cyc;
ARM_DEMCR |= ARM_DEMCR_TRCENA;
ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
cyc = ARM_DWT_CYCCNT + CYCLES_800;
while(p < end) {
pix = *p++;
for(mask = 0x80; mask; mask >>= 1) {
while(ARM_DWT_CYCCNT - cyc < CYCLES_800);
cyc = ARM_DWT_CYCCNT;
*set = 1;
if(pix & mask) {
while(ARM_DWT_CYCCNT - cyc < CYCLES_800_T1H);
} else {
while(ARM_DWT_CYCCNT - cyc < CYCLES_800_T0H);
}
*clr = 1;
}
}
while(ARM_DWT_CYCCNT - cyc < CYCLES_800);
#ifdef NEO_KHZ400
} else { // 400 kHz bitstream
cyc = ARM_DWT_CYCCNT + CYCLES_400;
while(p < end) {
pix = *p++;
for(mask = 0x80; mask; mask >>= 1) {
while(ARM_DWT_CYCCNT - cyc < CYCLES_400);
cyc = ARM_DWT_CYCCNT;
*set = 1;
if(pix & mask) {
while(ARM_DWT_CYCCNT - cyc < CYCLES_400_T1H);
} else {
while(ARM_DWT_CYCCNT - cyc < CYCLES_400_T0H);
}
*clr = 1;
}
}
while(ARM_DWT_CYCCNT - cyc < CYCLES_400);
}
#endif // NEO_KHZ400
#elif defined(TEENSYDUINO) && defined(__MKL26Z64__) // Teensy-LC
#if F_CPU == 48000000
uint8_t *p = pixels,
pix, count, dly,
bitmask = digitalPinToBitMask(pin);
volatile uint8_t *reg = portSetRegister(pin);
uint32_t num = numBytes;
asm volatile(
"L%=_begin:" "\n\t"
"ldrb %[pix], [%[p], #0]" "\n\t"
"lsl %[pix], #24" "\n\t"
"movs %[count], #7" "\n\t"
"L%=_loop:" "\n\t"
"lsl %[pix], #1" "\n\t"
"bcs L%=_loop_one" "\n\t"
"L%=_loop_zero:"
"strb %[bitmask], [%[reg], #0]" "\n\t"
"movs %[dly], #4" "\n\t"
"L%=_loop_delay_T0H:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_loop_delay_T0H" "\n\t"
"strb %[bitmask], [%[reg], #4]" "\n\t"
"movs %[dly], #13" "\n\t"
"L%=_loop_delay_T0L:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_loop_delay_T0L" "\n\t"
"b L%=_next" "\n\t"
"L%=_loop_one:"
"strb %[bitmask], [%[reg], #0]" "\n\t"
"movs %[dly], #13" "\n\t"
"L%=_loop_delay_T1H:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_loop_delay_T1H" "\n\t"
"strb %[bitmask], [%[reg], #4]" "\n\t"
"movs %[dly], #4" "\n\t"
"L%=_loop_delay_T1L:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_loop_delay_T1L" "\n\t"
"nop" "\n\t"
"L%=_next:" "\n\t"
"sub %[count], #1" "\n\t"
"bne L%=_loop" "\n\t"
"lsl %[pix], #1" "\n\t"
"bcs L%=_last_one" "\n\t"
"L%=_last_zero:"
"strb %[bitmask], [%[reg], #0]" "\n\t"
"movs %[dly], #4" "\n\t"
"L%=_last_delay_T0H:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_last_delay_T0H" "\n\t"
"strb %[bitmask], [%[reg], #4]" "\n\t"
"movs %[dly], #10" "\n\t"
"L%=_last_delay_T0L:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_last_delay_T0L" "\n\t"
"b L%=_repeat" "\n\t"
"L%=_last_one:"
"strb %[bitmask], [%[reg], #0]" "\n\t"
"movs %[dly], #13" "\n\t"
"L%=_last_delay_T1H:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_last_delay_T1H" "\n\t"
"strb %[bitmask], [%[reg], #4]" "\n\t"
"movs %[dly], #1" "\n\t"
"L%=_last_delay_T1L:" "\n\t"
"sub %[dly], #1" "\n\t"
"bne L%=_last_delay_T1L" "\n\t"
"nop" "\n\t"
"L%=_repeat:" "\n\t"
"add %[p], #1" "\n\t"
"sub %[num], #1" "\n\t"
"bne L%=_begin" "\n\t"
"L%=_done:" "\n\t"
: [p] "+r" (p),
[pix] "=&r" (pix),
[count] "=&r" (count),
[dly] "=&r" (dly),
[num] "+r" (num)
: [bitmask] "r" (bitmask),
[reg] "r" (reg)
);
#else
#error "Sorry, only 48 MHz is supported, please set Tools > CPU Speed to 48 MHz"
#endif // F_CPU == 48000000
// Begin of support for NRF52832 based boards -------------------------
#elif defined(NRF52)
// [[[Begin of the Neopixel NRF52 EasyDMA implementation
// by the Hackerspace San Salvador]]]
// This technique uses the PWM peripheral on the NRF52. The PWM uses the
// EasyDMA feature included on the chip. This technique loads the duty
// cycle configuration for each cycle when the PWM is enabled. For this
// to work we need to store a 16 bit configuration for each bit of the
// RGB(W) values in the pixel buffer.
// Comparator values for the PWM were hand picked and are guaranteed to
// be 100% organic to preserve freshness and high accuracy. Current
// parameters are:
// * PWM Clock: 16Mhz
// * Minimum step time: 62.5ns
// * Time for zero in high (T0H): 0.31ms
// * Time for one in high (T1H): 0.75ms
// * Cycle time: 1.25us
// * Frequency: 800Khz
// For 400Khz we just double the calculated times.
// ---------- BEGIN Constants for the EasyDMA implementation -----------
// The PWM starts the duty cycle in LOW. To start with HIGH we
// need to set the 15th bit on each register.
// WS2812 (rev A) timing is 0.35 and 0.7us
//#define MAGIC_T0H 5UL | (0x8000) // 0.3125us
//#define MAGIC_T1H 12UL | (0x8000) // 0.75us
// WS2812B (rev B) timing is 0.4 and 0.8 us
#define MAGIC_T0H 6UL | (0x8000) // 0.375us
#define MAGIC_T1H 13UL | (0x8000) // 0.8125us
// WS2811 (400 khz) timing is 0.5 and 1.2
#define MAGIC_T0H_400KHz 8UL | (0x8000) // 0.5us
#define MAGIC_T1H_400KHz 19UL | (0x8000) // 1.1875us
// For 400Khz, we double value of CTOPVAL
#define CTOPVAL 20UL // 1.25us
#define CTOPVAL_400KHz 40UL // 2.5us
// ---------- END Constants for the EasyDMA implementation -------------
//
// If there is no device available an alternative cycle-counter
// implementation is tried.
// The nRF52832 runs with a fixed clock of 64Mhz. The alternative
// implementation is the same as the one used for the Teensy 3.0/1/2 but
// with the Nordic SDK HAL & registers syntax.
// The number of cycles was hand picked and is guaranteed to be 100%
// organic to preserve freshness and high accuracy.
// ---------- BEGIN Constants for cycle counter implementation ---------
#define CYCLES_800_T0H 18 // ~0.36 uS
#define CYCLES_800_T1H 41 // ~0.76 uS
#define CYCLES_800 71 // ~1.25 uS
#define CYCLES_400_T0H 26 // ~0.50 uS
#define CYCLES_400_T1H 70 // ~1.26 uS
#define CYCLES_400 156 // ~2.50 uS
// ---------- END of Constants for cycle counter implementation --------
// To support both the SoftDevice + Neopixels we use the EasyDMA
// feature from the NRF25. However this technique implies to
// generate a pattern and store it on the memory. The actual
// memory used in bytes corresponds to the following formula:
// totalMem = numBytes*8*2+(2*2)
// The two additional bytes at the end are needed to reset the
// sequence.
//
// If there is not enough memory, we will fall back to cycle counter
// using DWT
uint32_t pattern_size = numBytes*8*sizeof(uint16_t)+2*sizeof(uint16_t);
uint16_t* pixels_pattern = nullptr;
NRF_PWM_Type* pwm = nullptr;
// Try to find a free PWM device, which is not enabled
// and has no connected pins
NRF_PWM_Type* PWM[3] = {NRF_PWM0, NRF_PWM1, NRF_PWM2};
for(int device = 0; device<3; device++) {
if( (PWM[device]->ENABLE == 0) &&
(PWM[device]->PSEL.OUT[0] & PWM_PSEL_OUT_CONNECT_Msk) &&
(PWM[device]->PSEL.OUT[1] & PWM_PSEL_OUT_CONNECT_Msk) &&
(PWM[device]->PSEL.OUT[2] & PWM_PSEL_OUT_CONNECT_Msk) &&
(PWM[device]->PSEL.OUT[3] & PWM_PSEL_OUT_CONNECT_Msk)
) {
pwm = PWM[device];
break;
}
}
// only malloc if there is PWM device available
if ( pwm != nullptr ) {
#ifdef ARDUINO_FEATHER52 // use thread-safe malloc
pixels_pattern = (uint16_t *) rtos_malloc(pattern_size);
#else
pixels_pattern = (uint16_t *) malloc(pattern_size);
#endif
}
// Use the identified device to choose the implementation
// If a PWM device is available use DMA
if( (pixels_pattern != nullptr) && (pwm != nullptr) ) {
uint16_t pos = 0; // bit position
for(uint16_t n=0; n<numBytes; n++) {
uint8_t pix = pixels[n];
for(uint8_t mask=0x80, i=0; mask>0; mask >>= 1, i++) {
#ifdef NEO_KHZ400
if( !is800KHz ) {
pixels_pattern[pos] = (pix & mask) ? MAGIC_T1H_400KHz : MAGIC_T0H_400KHz;
}else
#endif
{
pixels_pattern[pos] = (pix & mask) ? MAGIC_T1H : MAGIC_T0H;
}
pos++;
}
}
// Zero padding to indicate the end of que sequence
pixels_pattern[++pos] = 0 | (0x8000); // Seq end
pixels_pattern[++pos] = 0 | (0x8000); // Seq end
// Set the wave mode to count UP
pwm->MODE = (PWM_MODE_UPDOWN_Up << PWM_MODE_UPDOWN_Pos);
// Set the PWM to use the 16MHz clock
pwm->PRESCALER = (PWM_PRESCALER_PRESCALER_DIV_1 << PWM_PRESCALER_PRESCALER_Pos);
// Setting of the maximum count
// but keeping it on 16Mhz allows for more granularity just
// in case someone wants to do more fine-tuning of the timing.
#ifdef NEO_KHZ400
if( !is800KHz ) {
pwm->COUNTERTOP = (CTOPVAL_400KHz << PWM_COUNTERTOP_COUNTERTOP_Pos);
}else
#endif
{
pwm->COUNTERTOP = (CTOPVAL << PWM_COUNTERTOP_COUNTERTOP_Pos);
}
// Disable loops, we want the sequence to repeat only once
pwm->LOOP = (PWM_LOOP_CNT_Disabled << PWM_LOOP_CNT_Pos);
// On the "Common" setting the PWM uses the same pattern for the
// for supported sequences. The pattern is stored on half-word
// of 16bits
pwm->DECODER = (PWM_DECODER_LOAD_Common << PWM_DECODER_LOAD_Pos) |
(PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos);
// Pointer to the memory storing the patter
pwm->SEQ[0].PTR = (uint32_t)(pixels_pattern) << PWM_SEQ_PTR_PTR_Pos;
// Calculation of the number of steps loaded from memory.
pwm->SEQ[0].CNT = (pattern_size/sizeof(uint16_t)) << PWM_SEQ_CNT_CNT_Pos;
// The following settings are ignored with the current config.
pwm->SEQ[0].REFRESH = 0;
pwm->SEQ[0].ENDDELAY = 0;
// The Neopixel implementation is a blocking algorithm. DMA
// allows for non-blocking operation. To "simulate" a blocking
// operation we enable the interruption for the end of sequence
// and block the execution thread until the event flag is set by
// the peripheral.
// pwm->INTEN |= (PWM_INTEN_SEQEND0_Enabled<<PWM_INTEN_SEQEND0_Pos);
// PSEL must be configured before enabling PWM
pwm->PSEL.OUT[0] = g_ADigitalPinMap[pin];
// Enable the PWM
pwm->ENABLE = 1;
// After all of this and many hours of reading the documentation
// we are ready to start the sequence...
pwm->EVENTS_SEQEND[0] = 0;
pwm->TASKS_SEQSTART[0] = 1;
// But we have to wait for the flag to be set.
while(!pwm->EVENTS_SEQEND[0])
{
#ifdef ARDUINO_FEATHER52
yield();
#endif
}
// Before leave we clear the flag for the event.
pwm->EVENTS_SEQEND[0] = 0;
// We need to disable the device and disconnect
// all the outputs before leave or the device will not
// be selected on the next call.
// TODO: Check if disabling the device causes performance issues.
pwm->ENABLE = 0;
pwm->PSEL.OUT[0] = 0xFFFFFFFFUL;
#ifdef ARDUINO_FEATHER52 // use thread-safe free
rtos_free(pixels_pattern);
#else
free(pixels_pattern);
#endif
}// End of DMA implementation
// ---------------------------------------------------------------------
else{
// Fall back to DWT
#ifdef ARDUINO_FEATHER52
// Bluefruit Feather 52 uses freeRTOS
// Critical Section is used since it does not block SoftDevice execution
taskENTER_CRITICAL();
#elif defined(NRF52_DISABLE_INT)
// If you are using the Bluetooth SoftDevice we advise you to not disable
// the interrupts. Disabling the interrupts even for short periods of time
// causes the SoftDevice to stop working.
// Disable the interrupts only in cases where you need high performance for
// the LEDs and if you are not using the EasyDMA feature.
__disable_irq();
#endif
uint32_t pinMask = 1UL << g_ADigitalPinMap[pin];
uint32_t CYCLES_X00 = CYCLES_800;
uint32_t CYCLES_X00_T1H = CYCLES_800_T1H;
uint32_t CYCLES_X00_T0H = CYCLES_800_T0H;
#ifdef NEO_KHZ400
if( !is800KHz )
{
CYCLES_X00 = CYCLES_400;
CYCLES_X00_T1H = CYCLES_400_T1H;
CYCLES_X00_T0H = CYCLES_400_T0H;
}
#endif
// Enable DWT in debug core
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
// Tries to re-send the frame if is interrupted by the SoftDevice.
while(1) {
uint8_t *p = pixels;
uint32_t cycStart = DWT->CYCCNT;
uint32_t cyc = 0;
for(uint16_t n=0; n<numBytes; n++) {
uint8_t pix = *p++;
for(uint8_t mask = 0x80; mask; mask >>= 1) {
while(DWT->CYCCNT - cyc < CYCLES_X00);
cyc = DWT->CYCCNT;
NRF_GPIO->OUTSET |= pinMask;
if(pix & mask) {
while(DWT->CYCCNT - cyc < CYCLES_X00_T1H);
} else {
while(DWT->CYCCNT - cyc < CYCLES_X00_T0H);
}
NRF_GPIO->OUTCLR |= pinMask;
}
}
while(DWT->CYCCNT - cyc < CYCLES_X00);
// If total time longer than 25%, resend the whole data.
// Since we are likely to be interrupted by SoftDevice
if ( (DWT->CYCCNT - cycStart) < ( 8*numBytes*((CYCLES_X00*5)/4) ) ) {
break;
}
// re-send need 300us delay
delayMicroseconds(300);
}
// Enable interrupts again
#ifdef ARDUINO_FEATHER52
taskEXIT_CRITICAL();
#elif defined(NRF52_DISABLE_INT)
__enable_irq();
#endif
}
// END of NRF52 implementation
#elif defined (__SAMD21E17A__) || defined(__SAMD21G18A__) || defined(__SAMD21E18A__) || defined(__SAMD21J18A__) // Arduino Zero, Gemma/Trinket M0, SODAQ Autonomo and others
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
uint8_t *ptr, *end, p, bitMask, portNum;
uint32_t pinMask;
portNum = g_APinDescription[pin].ulPort;
pinMask = 1ul << g_APinDescription[pin].ulPin;
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg),
*clr = &(PORT->Group[portNum].OUTCLR.reg);
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
for(;;) {
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;");
if(p & bitMask) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop;");
*clr = pinMask;
} else {
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop;");
}
if(bitMask >>= 1) {
asm("nop; nop; nop; nop; nop; nop; nop; nop; nop;");
} else {
if(ptr >= end) break;
p = *ptr++;
bitMask = 0x80;
}
}
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
for(;;) {
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop; nop; nop; nop;");
if(p & bitMask) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop;");
*clr = pinMask;
} else {
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop;");
}
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
if(bitMask >>= 1) {
asm("nop; nop; nop; nop; nop; nop; nop;");
} else {
if(ptr >= end) break;
p = *ptr++;
bitMask = 0x80;
}
}
}
#endif
#elif defined (__SAMD51__) // M4 @ 120mhz
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
uint8_t *ptr, *end, p, bitMask, portNum;
uint32_t pinMask;
portNum = g_APinDescription[pin].ulPort;
pinMask = 1ul << g_APinDescription[pin].ulPin;
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg),
*clr = &(PORT->Group[portNum].OUTCLR.reg);
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
for(;;) {
if(p & bitMask) { // ONE
// High 800ns
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
// Low 450ns
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop;");
} else { // ZERO
// High 400ns
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop;");
// Low 850ns
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
}
if(bitMask >>= 1) {
// Move on to the next pixel
asm("nop;");
} else {
if(ptr >= end) break;
p = *ptr++;
bitMask = 0x80;
}
}
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
// ToDo!
}
#endif
#elif defined (ARDUINO_STM32_FEATHER) // FEATHER WICED (120MHz)
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
uint8_t *ptr, *end, p, bitMask;
uint32_t pinMask;
pinMask = BIT(PIN_MAP[pin].gpio_bit);
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
volatile uint16_t *set = &(PIN_MAP[pin].gpio_device->regs->BSRRL);
volatile uint16_t *clr = &(PIN_MAP[pin].gpio_device->regs->BSRRH);
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
for(;;) {
if(p & bitMask) { // ONE
// High 800ns
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop;");
// Low 450ns
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop;");
} else { // ZERO
// High 400ns
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop;");
// Low 850ns
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop;");
}
if(bitMask >>= 1) {
// Move on to the next pixel
asm("nop;");
} else {
if(ptr >= end) break;
p = *ptr++;
bitMask = 0x80;
}
}
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
// ToDo!
}
#endif
#elif defined (NRF51)
uint8_t *p = pixels,
pix, count, mask;
int32_t num = numBytes;
unsigned int bitmask = ( 1 << g_ADigitalPinMap[pin] );
// https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/variants/BBCmicrobit/variant.cpp
volatile unsigned int *reg = (unsigned int *) (0x50000000UL + 0x508);
// https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/cores/nRF5/SDK/components/device/nrf51.h
// http://www.iot-programmer.com/index.php/books/27-micro-bit-iot-in-c/chapters-micro-bit-iot-in-c/47-micro-bit-iot-in-c-fast-memory-mapped-gpio?showall=1
// https://github.com/Microsoft/pxt-neopixel/blob/master/sendbuffer.asm
asm volatile(
// "cpsid i" ; disable irq
// b .start
"b L%=_start" "\n\t"
// .nextbit: ; C0
"L%=_nextbit:" "\n\t" //; C0
// str r1, [r3, #0] ; pin := hi C2
"strb %[bitmask], [%[reg], #0]" "\n\t" //; pin := hi C2
// tst r6, r0 ; C3
"tst %[mask], %[pix]" "\n\t"// ; C3
// bne .islate ; C4
"bne L%=_islate" "\n\t" //; C4
// str r1, [r2, #0] ; pin := lo C6
"strb %[bitmask], [%[reg], #4]" "\n\t" //; pin := lo C6
// .islate:
"L%=_islate:" "\n\t"
// lsrs r6, r6, #1 ; r6 >>= 1 C7
"lsr %[mask], %[mask], #1" "\n\t" //; r6 >>= 1 C7
// bne .justbit ; C8
"bne L%=_justbit" "\n\t" //; C8
// ; not just a bit - need new byte
// adds r4, #1 ; r4++ C9
"add %[p], #1" "\n\t" //; r4++ C9
// subs r5, #1 ; r5-- C10
"sub %[num], #1" "\n\t" //; r5-- C10
// bcc .stop ; if (r5<0) goto .stop C11
"bcc L%=_stop" "\n\t" //; if (r5<0) goto .stop C11
// .start:
"L%=_start:"
// movs r6, #0x80 ; reset mask C12
"movs %[mask], #0x80" "\n\t" //; reset mask C12
// nop ; C13
"nop" "\n\t" //; C13
// .common: ; C13
"L%=_common:" "\n\t" //; C13
// str r1, [r2, #0] ; pin := lo C15
"strb %[bitmask], [%[reg], #4]" "\n\t" //; pin := lo C15
// ; always re-load byte - it just fits with the cycles better this way
// ldrb r0, [r4, #0] ; r0 := *r4 C17
"ldrb %[pix], [%[p], #0]" "\n\t" //; r0 := *r4 C17
// b .nextbit ; C20
"b L%=_nextbit" "\n\t" //; C20
// .justbit: ; C10
"L%=_justbit:" "\n\t" //; C10
// ; no nops, branch taken is already 3 cycles
// b .common ; C13
"b L%=_common" "\n\t" //; C13
// .stop:
"L%=_stop:" "\n\t"
// str r1, [r2, #0] ; pin := lo
"strb %[bitmask], [%[reg], #4]" "\n\t" //; pin := lo
// cpsie i ; enable irq
: [p] "+r" (p),
[pix] "=&r" (pix),
[count] "=&r" (count),
[mask] "=&r" (mask),
[num] "+r" (num)
: [bitmask] "r" (bitmask),
[reg] "r" (reg)
);
#elif defined(__SAM3X8E__) // Arduino Due
#define SCALE VARIANT_MCK / 2UL / 1000000UL
#define INST (2UL * F_CPU / VARIANT_MCK)
#define TIME_800_0 ((int)(0.40 * SCALE + 0.5) - (5 * INST))
#define TIME_800_1 ((int)(0.80 * SCALE + 0.5) - (5 * INST))
#define PERIOD_800 ((int)(1.25 * SCALE + 0.5) - (5 * INST))
#define TIME_400_0 ((int)(0.50 * SCALE + 0.5) - (5 * INST))
#define TIME_400_1 ((int)(1.20 * SCALE + 0.5) - (5 * INST))
#define PERIOD_400 ((int)(2.50 * SCALE + 0.5) - (5 * INST))
int pinMask, time0, time1, period, t;
Pio *port;
volatile WoReg *portSet, *portClear, *timeValue, *timeReset;
uint8_t *p, *end, pix, mask;
pmc_set_writeprotect(false);
pmc_enable_periph_clk((uint32_t)TC3_IRQn);
TC_Configure(TC1, 0,
TC_CMR_WAVE | TC_CMR_WAVSEL_UP | TC_CMR_TCCLKS_TIMER_CLOCK1);
TC_Start(TC1, 0);
pinMask = g_APinDescription[pin].ulPin; // Don't 'optimize' these into
port = g_APinDescription[pin].pPort; // declarations above. Want to
portSet = &(port->PIO_SODR); // burn a few cycles after
portClear = &(port->PIO_CODR); // starting timer to minimize
timeValue = &(TC1->TC_CHANNEL[0].TC_CV); // the initial 'while'.
timeReset = &(TC1->TC_CHANNEL[0].TC_CCR);
p = pixels;
end = p + numBytes;
pix = *p++;
mask = 0x80;
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
time0 = TIME_800_0;
time1 = TIME_800_1;
period = PERIOD_800;
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
time0 = TIME_400_0;
time1 = TIME_400_1;
period = PERIOD_400;
}
#endif
for(t = time0;; t = time0) {
if(pix & mask) t = time1;
while(*timeValue < period);
*portSet = pinMask;
*timeReset = TC_CCR_CLKEN | TC_CCR_SWTRG;
while(*timeValue < t);
*portClear = pinMask;
if(!(mask >>= 1)) { // This 'inside-out' loop logic utilizes
if(p >= end) break; // idle time to minimize inter-byte delays.
pix = *p++;
mask = 0x80;
}
}
while(*timeValue < period); // Wait for last bit
TC_Stop(TC1, 0);
#endif // end Due
// END ARM ----------------------------------------------------------------
#elif defined(ESP8266) || defined(ESP32)
// ESP8266 ----------------------------------------------------------------
// ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution
espShow(pin, pixels, numBytes, is800KHz);
#elif defined(__ARDUINO_ARC__)
// Arduino 101 -----------------------------------------------------------
#define NOPx7 { __builtin_arc_nop(); \
__builtin_arc_nop(); __builtin_arc_nop(); \
__builtin_arc_nop(); __builtin_arc_nop(); \
__builtin_arc_nop(); __builtin_arc_nop(); }
PinDescription *pindesc = &g_APinDescription[pin];
register uint32_t loop = 8 * numBytes; // one loop to handle all bytes and all bits
register uint8_t *p = pixels;
register uint32_t currByte = (uint32_t) (*p);
register uint32_t currBit = 0x80 & currByte;
register uint32_t bitCounter = 0;
register uint32_t first = 1;
// The loop is unusual. Very first iteration puts all the way LOW to the wire -
// constant LOW does not affect NEOPIXEL, so there is no visible effect displayed.
// During that very first iteration CPU caches instructions in the loop.
// Because of the caching process, "CPU slows down". NEOPIXEL pulse is very time sensitive
// that's why we let the CPU cache first and we start regular pulse from 2nd iteration
if (pindesc->ulGPIOType == SS_GPIO) {
register uint32_t reg = pindesc->ulGPIOBase + SS_GPIO_SWPORTA_DR;
uint32_t reg_val = __builtin_arc_lr((volatile uint32_t)reg);
register uint32_t reg_bit_high = reg_val | (1 << pindesc->ulGPIOId);
register uint32_t reg_bit_low = reg_val & ~(1 << pindesc->ulGPIOId);
loop += 1; // include first, special iteration
while(loop--) {
if(!first) {
currByte <<= 1;
bitCounter++;
}
// 1 is >550ns high and >450ns low; 0 is 200..500ns high and >450ns low
__builtin_arc_sr(first ? reg_bit_low : reg_bit_high, (volatile uint32_t)reg);
if(currBit) { // ~400ns HIGH (740ns overall)
NOPx7
NOPx7
}
// ~340ns HIGH
NOPx7
__builtin_arc_nop();
// 820ns LOW; per spec, max allowed low here is 5000ns */
__builtin_arc_sr(reg_bit_low, (volatile uint32_t)reg);
NOPx7
NOPx7
if(bitCounter >= 8) {
bitCounter = 0;
currByte = (uint32_t) (*++p);
}
currBit = 0x80 & currByte;
first = 0;
}
} else if(pindesc->ulGPIOType == SOC_GPIO) {
register uint32_t reg = pindesc->ulGPIOBase + SOC_GPIO_SWPORTA_DR;
uint32_t reg_val = MMIO_REG_VAL(reg);
register uint32_t reg_bit_high = reg_val | (1 << pindesc->ulGPIOId);
register uint32_t reg_bit_low = reg_val & ~(1 << pindesc->ulGPIOId);
loop += 1; // include first, special iteration
while(loop--) {
if(!first) {
currByte <<= 1;
bitCounter++;
}
MMIO_REG_VAL(reg) = first ? reg_bit_low : reg_bit_high;
if(currBit) { // ~430ns HIGH (740ns overall)
NOPx7
NOPx7
__builtin_arc_nop();
}
// ~310ns HIGH
NOPx7
// 850ns LOW; per spec, max allowed low here is 5000ns */
MMIO_REG_VAL(reg) = reg_bit_low;
NOPx7
NOPx7
if(bitCounter >= 8) {
bitCounter = 0;
currByte = (uint32_t) (*++p);
}
currBit = 0x80 & currByte;
first = 0;
}
}
#else
#error Architecture not supported
#endif
// END ARCHITECTURE SELECT ------------------------------------------------
#ifndef NRF52
interrupts();
#endif
endTime = micros(); // Save EOD time for latch on next call
}
// Set the output pin number
void MitovEmbedded_Adafruit_NeoPixel::setPin(uint8_t p) {
if(begun && (pin >= 0)) pinMode(pin, INPUT);
pin = p;
if(begun) {
pinMode(p, OUTPUT);
digitalWrite(p, LOW);
}
#ifdef __AVR__
port = portOutputRegister(digitalPinToPort(p));
pinMask = digitalPinToBitMask(p);
#endif
}
// Set pixel color from separate R,G,B components:
void MitovEmbedded_Adafruit_NeoPixel::setPixelColor(
uint16_t n, uint8_t r, uint8_t g, uint8_t b) {
if(n < numLEDs) {
if(brightness) { // See notes in setBrightness()
r = (r * brightness) >> 8;
g = (g * brightness) >> 8;
b = (b * brightness) >> 8;
}
uint8_t *p;
if(wOffset == rOffset) { // Is an RGB-type strip
p = &pixels[n * 3]; // 3 bytes per pixel
} else { // Is a WRGB-type strip
p = &pixels[n * 4]; // 4 bytes per pixel
p[wOffset] = 0; // But only R,G,B passed -- set W to 0
}
p[rOffset] = r; // R,G,B always stored
p[gOffset] = g;
p[bOffset] = b;
}
}
void MitovEmbedded_Adafruit_NeoPixel::setPixelColor(
uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
if(n < numLEDs) {
if(brightness) { // See notes in setBrightness()
r = (r * brightness) >> 8;
g = (g * brightness) >> 8;
b = (b * brightness) >> 8;
w = (w * brightness) >> 8;
}
uint8_t *p;
if(wOffset == rOffset) { // Is an RGB-type strip
p = &pixels[n * 3]; // 3 bytes per pixel (ignore W)
} else { // Is a WRGB-type strip
p = &pixels[n * 4]; // 4 bytes per pixel
p[wOffset] = w; // Store W
}
p[rOffset] = r; // Store R,G,B
p[gOffset] = g;
p[bOffset] = b;
}
}
// Set pixel color from 'packed' 32-bit RGB color:
void MitovEmbedded_Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) {
if(n < numLEDs) {
uint8_t *p,
r = (uint8_t)(c >> 16),
g = (uint8_t)(c >> 8),
b = (uint8_t)c;
if(brightness) { // See notes in setBrightness()
r = (r * brightness) >> 8;
g = (g * brightness) >> 8;
b = (b * brightness) >> 8;
}
if(wOffset == rOffset) {
p = &pixels[n * 3];
} else {
p = &pixels[n * 4];
uint8_t w = (uint8_t)(c >> 24);
p[wOffset] = brightness ? ((w * brightness) >> 8) : w;
}
p[rOffset] = r;
p[gOffset] = g;
p[bOffset] = b;
}
}
// Convert separate R,G,B into packed 32-bit RGB color.
// Packed format is always RGB, regardless of LED strand color order.
uint32_t MitovEmbedded_Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
// Convert separate R,G,B,W into packed 32-bit WRGB color.
// Packed format is always WRGB, regardless of LED strand color order.
uint32_t MitovEmbedded_Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
// Query color from previously-set pixel (returns packed 32-bit RGB value)
uint32_t MitovEmbedded_Adafruit_NeoPixel::getPixelColor(uint16_t n) const {
if(n >= numLEDs) return 0; // Out of bounds, return no color.
uint8_t *p;
if(wOffset == rOffset) { // Is RGB-type device
p = &pixels[n * 3];
if(brightness) {
// Stored color was decimated by setBrightness(). Returned value
// attempts to scale back to an approximation of the original 24-bit
// value used when setting the pixel color, but there will always be
// some error -- those bits are simply gone. Issue is most
// pronounced at low brightness levels.
return (((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
(((uint32_t)(p[gOffset] << 8) / brightness) << 8) |
( (uint32_t)(p[bOffset] << 8) / brightness );
} else {
// No brightness adjustment has been made -- return 'raw' color
return ((uint32_t)p[rOffset] << 16) |
((uint32_t)p[gOffset] << 8) |
(uint32_t)p[bOffset];
}
} else { // Is RGBW-type device
p = &pixels[n * 4];
if(brightness) { // Return scaled color
return (((uint32_t)(p[wOffset] << 8) / brightness) << 24) |
(((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
(((uint32_t)(p[gOffset] << 8) / brightness) << 8) |
( (uint32_t)(p[bOffset] << 8) / brightness );
} else { // Return raw color
return ((uint32_t)p[wOffset] << 24) |
((uint32_t)p[rOffset] << 16) |
((uint32_t)p[gOffset] << 8) |
(uint32_t)p[bOffset];
}
}
}
// Returns pointer to pixels[] array. Pixel data is stored in device-
// native format and is not translated here. Application will need to be
// aware of specific pixel data format and handle colors appropriately.
uint8_t *MitovEmbedded_Adafruit_NeoPixel::getPixels(void) const {
return pixels;
}
uint16_t MitovEmbedded_Adafruit_NeoPixel::numPixels(void) const {
return numLEDs;
}
// Adjust output brightness; 0=darkest (off), 255=brightest. This does
// NOT immediately affect what's currently displayed on the LEDs. The
// next call to show() will refresh the LEDs at this level. However,
// this process is potentially "lossy," especially when increasing
// brightness. The tight timing in the WS2811/WS2812 code means there
// aren't enough free cycles to perform this scaling on the fly as data
// is issued. So we make a pass through the existing color data in RAM
// and scale it (subsequent graphics commands also work at this
// brightness level). If there's a significant step up in brightness,
// the limited number of steps (quantization) in the old data will be
// quite visible in the re-scaled version. For a non-destructive
// change, you'll need to re-render the full strip data. C'est la vie.
void MitovEmbedded_Adafruit_NeoPixel::setBrightness(uint8_t b) {
// Stored brightness value is different than what's passed.
// This simplifies the actual scaling math later, allowing a fast
// 8x8-bit multiply and taking the MSB. 'brightness' is a uint8_t,
// adding 1 here may (intentionally) roll over...so 0 = max brightness
// (color values are interpreted literally; no scaling), 1 = min
// brightness (off), 255 = just below max brightness.
uint8_t newBrightness = b + 1;
if(newBrightness != brightness) { // Compare against prior value
// Brightness has changed -- re-scale existing data in RAM
uint8_t c,
*ptr = pixels,
oldBrightness = brightness - 1; // De-wrap old brightness value
uint16_t scale;
if(oldBrightness == 0) scale = 0; // Avoid /0
else if(b == 255) scale = 65535 / oldBrightness;
else scale = (((uint16_t)newBrightness << 8) - 1) / oldBrightness;
for(uint16_t i=0; i<numBytes; i++) {
c = *ptr;
*ptr++ = (c * scale) >> 8;
}
brightness = newBrightness;
}
}
//Return the brightness value
uint8_t MitovEmbedded_Adafruit_NeoPixel::getBrightness(void) const {
return brightness - 1;
}
void MitovEmbedded_Adafruit_NeoPixel::clear() {
memset(pixels, 0, numBytes);
}
// This is a mash-up of the Due show() code + insights from <NAME>'s
// ESP8266 work for the NeoPixelBus library: github.com/Makuna/NeoPixelBus
// Needs to be a separate .c file to enforce ICACHE_RAM_ATTR execution.
#endif // ADAFRUIT_NEOPIXEL_H
|
hisptz/scorecard_app_widget | src/shared/Components/DeleteConfirmation/index.js | import i18n from "@dhis2/d2-i18n";
import {
Button,
ButtonStrip,
Modal,
ModalActions,
ModalContent,
ModalTitle,
} from "@dhis2/ui";
import PropTypes from "prop-types";
import React from "react";
export default function DeleteConfirmation({
onConfirm,
onCancel,
text,
component,
}) {
return (
<Modal dataTest="delete-confirm-modal" onClose={onCancel}>
<ModalTitle>Select Confirmation</ModalTitle>
<ModalContent>
{component
? component
: text
? text
: i18n.t("Are you sure you want to delete this entity?")}
</ModalContent>
<ModalActions>
<ButtonStrip>
<Button onClick={onCancel}>{i18n.t("Cancel")}</Button>
<Button dataTest={"delete-confirm-button"} primary onClick={onConfirm}>
{i18n.t("Select")}
</Button>
</ButtonStrip>
</ModalActions>
</Modal>
);
}
DeleteConfirmation.propTypes = {
onCancel: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
component: PropTypes.node,
text: PropTypes.string,
};
|
mathstuf/seacas | docs/html/search/variables_3.js | <filename>docs/html/search/variables_3.js
var searchData=
[
['fa_5fctr_5flist',['fa_ctr_list',['../ex__utils_8c.html#a0c729ddce310e92dfaaea97755db7205',1,'ex_utils.c']]],
['face_5fblk_5fid',['face_blk_id',['../structex__block__params.html#a339c7ea40dfbfd698f254231bde7b42f',1,'ex_block_params']]],
['face_5ftype',['face_type',['../structex__block__params.html#a17d10cd6db02e49656daa881d492680b',1,'ex_block_params']]],
['face_5fvar_5ftab',['face_var_tab',['../structex__var__params.html#a03d81111469cf13f994006f3844640bd',1,'ex_var_params']]],
['fam_5fctr_5flist',['fam_ctr_list',['../ex__utils_8c.html#acbd68227405088fdad1a25580a38c00c',1,'ex_utils.c']]],
['file_5fid',['file_id',['../structex__file__item.html#a02a56c94790f68bc622c56ec8224576d',1,'ex_file_item']]],
['file_5flist',['file_list',['../ex__conv_8c.html#a24d92cdd9e11962bd034e077ef1f78c2',1,'ex_conv.c']]],
['file_5ftype',['file_type',['../structex__file__item.html#a5b9a4911596a49205a98bcd452f21779',1,'ex_file_item']]],
['fs_5fctr_5flist',['fs_ctr_list',['../ex__utils_8c.html#a6a9492348daa4fc26d1b7e5d13819f64',1,'ex_utils.c']]],
['fset_5fvar_5ftab',['fset_var_tab',['../structex__var__params.html#aa27fc4c7d6b377bcab20b68279143f70',1,'ex_var_params']]]
];
|
timiditi/tp | src/main/java/seedu/address/model/tuition/ClassName.java | package seedu.address.model.tuition;
import static java.util.Objects.requireNonNull;
/**
* Represents the name of the tuition class.
*/
public class ClassName {
public final String name;
/**
* Constructor for Class Name.
*
* @param name The name of the class.
*/
public ClassName(String name) {
requireNonNull(name);
this.name = name;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof ClassName) {
return name.equals(((ClassName) other).name);
}
return false;
}
public String getName() {
return name;
}
}
|
pss521/springboot-penguin | src/main/resources/static/js/user/myExam.js | /**
* 模块JavaScript
*/
var myExamPage = {
data:{
pageNum: 0,
pageSize: 0,
totalPageNum: 0,
totalPageSize: 0,
grades: [],
},
init: function (pageNum, pageSize, totalPageNum, totalPageSize, grades) {
myExamPage.data.pageNum = pageNum;
myExamPage.data.pageSize = pageSize;
myExamPage.data.totalPageNum = totalPageNum;
myExamPage.data.totalPageSize = totalPageSize;
myExamPage.data.grades = grades;
//分页初始化
myExamPage.subPageMenuInit();
/**
TODO::代码规范,点击上传图片效果
*/
$(document)
.ready(function() {
$('.card .dimmer')
.dimmer({
on: 'hover'
})
;
})
;
},
firstPage: function () {
window.location.href = app.URL.myExamUrl() + '?page=1';
},
prevPage: function () {
window.location.href = app.URL.myExamUrl() + '?page=' + (pageNum-1);
},
targetPage: function (page) {
window.location.href = app.URL.myExamUrl() + '?page=' + page;
},
nextPage: function () {
window.location.href = app.URL.myExamUrl() + '?page=' + (pageNum+1);
},
lastPage: function () {
window.location.href = app.URL.myExamUrl() + '?page=' + myExamPage.data.totalPageNum;
},
subPageMenuInit: function(){
var subPageStr = '';
if (myExamPage.data.pageNum == 1) {
subPageStr += '<a class="item disabled">首页</a>';
subPageStr += '<a class="item disabled">上一页</a>';
} else {
subPageStr += '<a onclick="myExamPage.firstPage()" class="item">首页</a>';
subPageStr += '<a onclick="myExamPage.prevPage()" class="item">上一页</a>';
}
var startPage = (myExamPage.data.pageNum-4 > 0 ? myExamPage.data.pageNum-4 : 1);
var endPage = (startPage+7 > myExamPage.data.totalPageNum ? myExamPage.data.totalPageNum : startPage+7);
console.log('startPage = ' + startPage);
console.log('endPage = ' + endPage);
console.log('pageNum = ' + myExamPage.data.pageNum);
console.log('totalPageNum = ' + myExamPage.data.totalPageNum);
for (var i = startPage; i <= endPage; i++) {
if (i == myExamPage.data.pageNum) {
subPageStr += '<a onclick="myExamPage.targetPage('+i+')" class="active item">'+i+'</a>';
} else {
subPageStr += '<a onclick="myExamPage.targetPage('+i+')" class="item">'+i+'</a>'
}
}
if (myExamPage.data.pageNum == myExamPage.data.totalPageNum) {
subPageStr += '<a class="item disabled">下一页</a>';
subPageStr += '<a class="item disabled">末页</a>';
} else {
subPageStr += '<a onclick="myExamPage.nextPage()" class="item">下一页</a>';
subPageStr += '<a onclick="myExamPage.lastPage()" class="item">末页</a>';
}
$('#subPageMenu').html(subPageStr);
},
}; |
fabianormatias/poc-recomendacao-metodo-delphi-v1 | src/org/yooreeka/algos/taxis/evaluation/McNemarTest.java | /*
* ________________________________________________________________________________________
*
* Y O O R E E K A
* A library for data mining, machine learning, soft computing, and mathematical analysis
* ________________________________________________________________________________________
*
* The Yooreeka project started with the code of the book "Algorithms of the Intelligent Web "
* (Manning 2009). Although the term "Web" prevailed in the title, in essence, the algorithms
* are valuable in any software application.
*
* Copyright (c) 2007-2009 <NAME> & <NAME>
* Copyright (c) 2009-${year} Marmanis Group LLC and individual contributors as indicated by the @author tags.
*
* Certain library functions depend on other Open Source software libraries, which are covered
* by different license agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* Marmanis Group LLC 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.yooreeka.algos.taxis.evaluation;
public class McNemarTest extends Test {
private double chi2 = 0.0;
private ClassifierResults c1;
private ClassifierResults c2;
/*
* Using 'n??' notation. First '?' represents result for first classifier.
* Second '?' represents result for the second classifier. 0 -
* misclassification, 1 - correct classification.
*/
private int n11 = 0; // both classifiers were correct
private int n10 = 0; // first is correct, second incorrect
private int n01 = 0; // first incorrect, second correct
private int n00 = 0; // both incorrect
public McNemarTest(ClassifierResults c1, ClassifierResults c2) {
this.c1 = c1;
this.c2 = c2;
setStatisticSymbol("Chi^2");
// using level of significance 0.05, 1 degree of freedom:
// reject null hypothesis if chi2 > 3.841
setThreshold(3.841);
calculate();
}
@Override
protected void calculate() {
int n = c1.getN();
for (int i = 0; i < n; i++) {
if (c1.getResult(i) && c2.getResult(i)) {
n11++;
} else if (c1.getResult(i) && !c2.getResult(i)) {
n10++;
} else if (!c1.getResult(i) && c2.getResult(i)) {
n01++;
} else {
n00++;
}
}
double a = Math.abs(n01 - n10) - 1;
chi2 = a * a / (n01 + n10);
setStatisticValue(chi2);
}
@Override
public void evaluate() {
print("_____________________________________________________");
print("Evaluating classifiers " + c1.getClassifierId() + " and "
+ c2.getClassifierId() + ":");
print("_____________________________________________________");
print(c1.getClassifierId() + " accuracy: " + c1.getAccuracy());
print(c2.getClassifierId() + " accuracy: " + c2.getAccuracy());
print("N = " + c1.getN() + ", n00=" + n00 + ", n10=" + n10 + ", n01="
+ n01 + ", n11=" + n11);
print("_____________________________________________________");
print("Confidence Interval : 0.05");
print("Degrees of Freedom : 1");
print("Statistic threshold (Chi-square): 3.841");
printResult();
}
public int getN00() {
return n00;
}
public int getN10() {
return n10;
}
public int getN11() {
return n11;
}
}
|
kagemeka/atcoder-submissions | jp.atcoder/abc045/arc061_a/11775567.py | import sys
s = sys.stdin.readline().rstrip()
n = len(s)
def c(n):
return pow(2, max(0, n - 1))
def main():
res = 0
for l in range(n):
for r in range(l, n):
res += int(s[l : r + 1]) * c(l) * c(n - 1 - r)
print(res)
if __name__ == "__main__":
main()
|
feav/Progiciel-Facturation | public/scripts/table/ngGrid.js | 'use strict'
angular
.module('theme.tables-ng-grid', [])
.controller('TablesAdvancedController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.totalServerItems = 0;
$scope.pagingOptions = {
pageSizes: [25, 50, 100],
pageSize: 25,
currentPage: 1
};
$scope.setPagingData = function (data, page, pageSize) {
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.myData = pagedData;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('assets/demo/ng-data.json').success(function (largeLoad) {
data = largeLoad.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data, page, pageSize);
});
} else {
$http.get('assets/demo/ng-data.json').success(function (largeLoad) {
$scope.setPagingData(largeLoad, page, pageSize);
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.gridOptions = {
data: 'myData',
enablePaging: true,
showFooter: true,
totalServerItems: 'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions
};
}])
.controller('IndexController', ['$scope', '$http', function ($scope, $http) {
$scope.stats = null;
$http.get('statisticsForDashboard').success(function (resp) { $scope.stats = resp });
}])
.controller('RouteursController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(data){
$scope.routeurs = data.body;
$scope.totalServerItems = data.total;
$scope.totalCurrentPageItems = data.total_current_page;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('routeurs/paginate/'+pageSize+'/searchText/'+searchText+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('routeurs/paginate/'+pageSize+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.saveRouteur = function(data, id) {
$http.post('routeurs/update/'+id, data)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Routeur', 'Routeur modifié avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Routeur', 'Une erreur est survenue durant la mise à jour !', 'error');
});
};
$scope.removeRouteur = function(id) {
$http.post('routeurs/delete/'+id)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Routeur', 'Routeur supprimé avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Routeur', 'Une erreur est survenue durant la suppression !', 'error');
});
};
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
$scope.refreshTab = function () {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
}])
.controller('BasesController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.routeurs = [];
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(data){
$scope.bases = data.body;
$scope.totalServerItems = data.total;
$scope.totalCurrentPageItems = data.total_current_page;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('bases/paginate/'+pageSize+'/searchText/'+searchText+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('bases/paginate/'+pageSize+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$http.get('routeurs').success(function (resp) { $scope.routeurs = resp.body; });
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.saveBase = function(data, id) {
$http.post('bases/update/'+id, data)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Base', 'Base modifiée avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Base', 'Une erreur est survenue durant la mise à jour !', 'error');
});
};
$scope.removeBase = function(id) {
$http.post('bases/delete/'+id)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Base', 'Base supprimée avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Base', 'Une erreur est survenue durant la suppression !', 'error');
});
};
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
$scope.refreshTab = function () {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
}])
.controller('AnnonceursController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(data){
$scope.annonceurs = data.body;
$scope.totalServerItems = data.total;
$scope.totalCurrentPageItems = data.total_current_page;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('annonceurs/paginate/'+pageSize+'/searchText/'+searchText+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('annonceurs/paginate/'+pageSize+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.saveAnnonceur = function(data, id) {
$http.post('annonceurs/update/'+id, data)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Annonceur', 'Annonceur modifié avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Annonceur', 'Une erreur est survenue durant la mise à jour !', 'error');
});
};
$scope.removeAnnonceur = function(id) {
$http.post('annonceurs/delete/'+id)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Annonceur', 'Annonceur supprimé avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Annonceur', 'Une erreur est survenue durant la suppression !', 'error');
});
};
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
$scope.refreshTab = function () {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
}])
.controller('CampagnesController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.annonceurs = [];
$scope.totalCurrentPageItems = 0;
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(data){
$scope.campagnes = data.body;
$scope.totalServerItems = data.total;
$scope.totalCurrentPageItems = data.total_current_page;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('campagnes/paginate/'+pageSize+'/searchText/'+searchText+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('campagnes/paginate/'+pageSize+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$http.get('annonceurs').success(function (resp) { $scope.annonceurs = resp.body; });
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.saveCampagne = function(data, id) {
if(data.annonceur)
$http.post('campagnes/update/'+id, data)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Campagne', 'Campagne modifiée avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Campagne', 'Une erreur est survenue durant la mise à jour !', 'error');
});
};
$scope.removeCampagne = function(id) {
$http.post('campagnes/delete/'+id)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Campagne', 'Campagne supprimée avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Campagne', 'Une erreur est survenue durant la suppression !', 'error');
});
};
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
$scope.refreshTab = function () {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
};
}])
.controller('PlanningsController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.routeurs = [];
$scope.bases = [];
$scope.annonceurs = [];
$scope.campagnes = [];
$scope.campagnesPourPlanning = [];
$scope.basesPourPlanning = [];
$scope.annonceur = null;
$scope.campagne = null;
$scope.routeur = null;
$scope.base = null;
$scope.filter_data = {
filtre_date_debut : moment().startOf('year').format('D MMMM YYYY'),
filtre_date_fin : moment().endOf('month').format('D MMMM YYYY')
};
$scope.filtre_date_options = {
opens: 'right',
startDate: moment().startOf('year'),
endDate: moment().endOf('month'),
ranges: {
'Ce Jour': [moment(), moment()],
'Cette Semaine': [moment().startOf('week').add('days', 1), moment().endOf('week').add('days', 1)],
'Ce mois': [moment().startOf('month'), moment().endOf('month')]
},
format: 'DD/MM/YYYY'
};
$scope.annonceurChange = function(){
$http.get('campagnes/parAnnonceur/'+$scope.annonceur).success(function (rep) {
$scope.campagnesPourPlanning = rep.body
});
}
$scope.routeurChange = function(){
$http.get('bases/parRouteur/'+$scope.routeur).success(function (rep) {
$scope.basesPourPlanning = rep.body
});
}
$scope.validerFiltre = function (){
$scope.showLoader = true;
$http.post('plannings/applyFilter/'+$scope.pagingOptions.pageSize+'?page='+$scope.pagingOptions.currentPage, $scope.filter_data)
.success(function (resp) {
$scope.setPagingData(resp, $scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.notif('Plannings', 'Une erreur est survenue durant le filtrage !', 'error');
$scope.showLoader = false;
});
}
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(data){
$scope.plannings = data.body;
$scope.totalServerItems = data.total;
$scope.totalCurrentPageItems = data.total_current_page;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('plannings/paginate/'+pageSize+'/searchText/'+searchText+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
// $http.get('plannings/paginate/'+pageSize+'?page='+page)
// .success(function (resp) {
// $scope.setPagingData(resp);
// $scope.showLoader = false;
// })
// .error(function (res,status,err) {
// $scope.showLoader = false;
// });
$scope.validerFiltre();
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$http.get('routeurs').success(function (resp) { $scope.routeurs = resp.body; });
$http.get('bases').success(function (resp) { $scope.bases = resp.body; });
$http.get('annonceurs').success(function (resp) { $scope.annonceurs = resp.body; });
$http.get('campagnes').success(function (resp) { $scope.campagnes = resp.body; });
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.savePlanning = function(data, id) {
$http.post('plannings/update/'+id, data)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Planning', 'Planning modifié avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Planning', 'Une erreur est survenue durant la mise à jour !', 'error');
});
};
$scope.removePlanning = function(id) {
$http.post('plannings/delete/'+id)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Planning', 'Planning supprimé avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Planning', 'Une erreur est survenue durant la suppression !', 'error');
});
};
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
$scope.refreshTab = function () {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
}])
.controller('ResultatsController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.filter_data = {
filtre_routeur: null,
filtre_base: null,
filtre_annonceur: null,
filtre_campagne: null,
filtre_date_debut : moment().startOf('year').format('D MMMM YYYY'),
filtre_date_fin : moment().endOf('month').format('D MMMM YYYY')
};
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.routeurs = [];
$scope.bases = [];
$scope.annonceurs = [];
$scope.campagnes = [];
$scope.filtre_date_options = {
opens: 'right',
startDate: moment().startOf('year'),
endDate: moment().endOf('month')
};
$scope.annonceurChange = function(){
$http.get('campagnes/parAnnonceur/'+$scope.filter_data.filtre_annonceur).success(function (rep) {
$scope.campagnes = rep.body
});
}
$scope.routeurChange = function(){
$http.get('bases/parRouteur/'+$scope.filter_data.filtre_routeur).success(function (rep) {
$scope.bases = rep.body
});
}
$scope.validerFiltre = function (){
$scope.showLoader = true;
$http.post('resultats/applyFilter/'+$scope.pagingOptions.pageSize+'?page='+$scope.pagingOptions.currentPage, $scope.filter_data)
.success(function (resp) {
$scope.setPagingData(resp, $scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.notif('Résultat', 'Une erreur est survenue durant le filtrage !', 'error');
$scope.showLoader = false;
});
}
$scope.viderLesChamps = function (){
$scope.filter_data.filtre_routeur= null;
$scope.filter_data.filtre_base= null;
$scope.filter_data.filtre_annonceur= null;
$scope.filter_data.filtre_campagne= null;
}
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(data){
$scope.resultats = data.body;
$scope.totalServerItems = data.total;
$scope.totalCurrentPageItems = data.total_current_page;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('resultats/paginate/'+pageSize+'/searchText/'+searchText+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$scope.validerFiltre();
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$http.get('routeurs').success(function (resp) { $scope.routeurs = resp.body; });
//$http.get('bases').success(function (resp) { $scope.bases = resp.body; });
$http.get('annonceurs').success(function (resp) { $scope.annonceurs = resp.body; });
//$http.get('campagnes').success(function (resp) { $scope.campagnes = resp.body; });
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.saveResultat = function(data, id) {
$http.post('resultats/update/'+id, data)
.success(function (resp) {
$scope.validerFiltre();
$scope.notif('Résultat', 'Résultat modifié avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.validerFiltre();
$scope.notif('Résultat', 'Une erreur est survenue durant la mise à jour !', 'error');
});
};
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
}])
.controller('UsersController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.roles = [];
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(data){
$scope.users = data.body;
$scope.totalServerItems = data.total;
$scope.totalCurrentPageItems = data.total_current_page;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('users/paginate/'+pageSize+'/searchText/'+searchText+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('users/paginate/'+pageSize+'?page='+page)
.success(function (resp) {
$scope.setPagingData(resp);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$http.get('roles').success(function (resp) { $scope.roles = resp.body; });
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.saveUser = function(data, id) {
$http.post('users/update/'+id, data)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Utilisateur', 'Utilisateur modifié avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Utilisateur', 'Une erreur est survenue durant la mise à jour !', 'error');
});
};
$scope.removeUser = function(id) {
$http.post('users/delete/'+id)
.success(function (resp) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Utilisateur', 'Utilisateur supprimé avec succès !', 'success');
})
.error(function (res,status,err) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
$scope.notif('Utilisateur', 'Une erreur est survenue durant la suppression !', 'error');
});
};
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
$scope.refreshTab = function () {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
};
}])
.controller('StatsParAnnonceursController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.tab = [];
$scope.filter_data = {
filtre_date_debut : moment().subtract('days', 30).format('D MMMM YYYY'),
filtre_date_fin : moment().format('D MMMM YYYY')
};
$scope.filtre_date_options = {
opens: 'right',
startDate: moment().subtract('days', 30),
endDate: moment(),
ranges: {
'30 derniers jours': [moment().subtract('days', 30), moment()],
'60 derniers jours': [moment().subtract('days', 60), moment()],
'90 derniers jours': [moment().subtract('days', 90), moment()]
}
};
$scope.validerFiltre = function (){
$scope.showLoader = true;
$http.post('annonceurs/applyFilterForStatistics', $scope.filter_data)
.success(function (resp) {
$scope.setPagingData(resp, $scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize);
$scope.notif('Statistiques par Annonceurs', 'Filtrage effectué avec succès !', 'success');
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.notif('Statistiques par Annonceurs', 'Une erreur est survenue durant le filtrage !', 'error');
$scope.showLoader = false;
});
}
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(resp, page, pageSize){
var pagedData = resp.data.body.slice((page - 1) * pageSize, page * pageSize);
$scope.tab = pagedData;
$scope.totalServerItems = resp.data.body.length;
$scope.totalVolume = resp.totalVolume;
$scope.totalPA = resp.totalPA;
$scope.totalCA = resp.totalCA;
$scope.totalMarge = resp.totalMarge;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('annonceurs/forStatistics/searchText/'+searchText)
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('annonceurs/forStatistics/')
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
}])
.controller('StatsParBasesController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.tab = [];
$scope.filter_data = {
filtre_date_debut : moment().subtract('days', 30).format('D MMMM YYYY'),
filtre_date_fin : moment().format('D MMMM YYYY')
};
$scope.filtre_date_options = {
opens: 'right',
startDate: moment().subtract('days', 30),
endDate: moment(),
ranges: {
'30 derniers jours': [moment().subtract('days', 30), moment()],
'60 derniers jours': [moment().subtract('days', 60), moment()],
'90 derniers jours': [moment().subtract('days', 90), moment()]
}
};
$scope.validerFiltre = function (){
$scope.showLoader = true;
$http.post('bases/applyFilterForStatistics', $scope.filter_data)
.success(function (resp) {
$scope.setPagingData(resp, $scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize);
$scope.notif('Statistiques par Bases', 'Filtrage effectué avec succès !', 'success');
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.notif('Statistiques par Bases', 'Une erreur est survenue durant le filtrage !', 'error');
$scope.showLoader = false;
});
}
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(resp, page, pageSize){
var pagedData = resp.data.body.slice((page - 1) * pageSize, page * pageSize);
$scope.tab = pagedData;
$scope.totalServerItems = resp.data.body.length;
$scope.totalVolume = resp.totalVolume;
$scope.totalPA = resp.totalPA;
$scope.totalCA = resp.totalCA;
$scope.totalMarge = resp.totalMarge;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('bases/forStatistics/searchText/'+searchText)
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('bases/forStatistics/')
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
}])
.controller('StatsParRouteursController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.tab = [];
$scope.filter_data = {
filtre_date_debut : moment().subtract('days', 30).format('D MMMM YYYY'),
filtre_date_fin : moment().format('D MMMM YYYY')
};
$scope.filtre_date_options = {
opens: 'right',
startDate: moment().subtract('days', 30),
endDate: moment(),
ranges: {
'30 derniers jours': [moment().subtract('days', 30), moment()],
'60 derniers jours': [moment().subtract('days', 60), moment()],
'90 derniers jours': [moment().subtract('days', 90), moment()]
}
};
$scope.validerFiltre = function (){
$scope.showLoader = true;
$http.post('routeurs/applyFilterForStatistics', $scope.filter_data)
.success(function (resp) {
$scope.setPagingData(resp, $scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize);
$scope.notif('Statistiques par Routeurs', 'Filtrage effectué avec succès !', 'success');
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
$scope.notif('Statistiques par Routeurs', 'Une erreur est survenue durant le filtrage !', 'error');
});
}
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(resp, page, pageSize){
var pagedData = resp.data.body.slice((page - 1) * pageSize, page * pageSize);
$scope.tab = pagedData;
$scope.totalServerItems = resp.data.body.length;
$scope.totalVolume = resp.totalVolume;
$scope.totalPA = resp.totalPA;
$scope.totalCA = resp.totalCA;
$scope.totalMarge = resp.totalMarge;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('routeurs/forStatistics/searchText/'+searchText)
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('routeurs/forStatistics/')
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
}])
.controller('StatsParCampagnesController', ['$scope', '$filter', '$http', 'pinesNotifications', function ($scope, $filter, $http, pinesNotifications) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.showLoader = false;
$scope.totalServerItems = 0;
$scope.totalCurrentPageItems = 0;
$scope.tab = [];
$scope.totalVolume = 0;
$scope.totalPA = 0;
$scope.totalCA = 0;
$scope.totalMarge = 0;
$scope.filter_data = {
filtre_date_debut : moment().subtract('days', 30).format('D MMMM YYYY'),
filtre_date_fin : moment().format('D MMMM YYYY')
};
$scope.filtre_date_options = {
opens: 'right',
startDate: moment().subtract('days', 30),
endDate: moment(),
ranges: {
'30 derniers jours': [moment().subtract('days', 30), moment()],
'60 derniers jours': [moment().subtract('days', 60), moment()],
'90 derniers jours': [moment().subtract('days', 90), moment()]
}
};
$scope.validerFiltre = function (){
$scope.showLoader = true;
$http.post('campagnes/applyFilterForStatistics', $scope.filter_data)
.success(function (resp) {
$scope.setPagingData(resp, $scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize);
$scope.notif('Statistiques par Campagnes', 'Filtrage effectué avec succès !', 'success');
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
$scope.notif('Statistiques par Campagnes', 'Une erreur est survenue durant le filtrage !', 'error');
});
}
$scope.pagingOptions = {
pageSizes: [15, 25, 50, 100],
pageSize: 15,
currentPage: 1,
maxSize: 5
};
$scope.setPagingData = function(resp, page, pageSize){
var pagedData = resp.data.body.slice((page - 1) * pageSize, page * pageSize);
$scope.tab = pagedData;
$scope.totalServerItems = resp.data.body.length;
$scope.totalVolume = resp.totalVolume;
$scope.totalPA = resp.totalPA;
$scope.totalCA = resp.totalCA;
$scope.totalMarge = resp.totalMarge;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.pageSizeChange = function(){
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
$scope.showLoader = true;
setTimeout(function () {
if (searchText) {
$http.post('campagnes/forStatistics/searchText/'+searchText, $scope.filter_data)
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
} else {
$http.get('campagnes/forStatistics/')
.success(function (resp) {
$scope.setPagingData(resp, page, pageSize);
$scope.showLoader = false;
})
.error(function (res,status,err) {
$scope.showLoader = false;
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.notif = function (titre, message, type) {
pinesNotifications.notify({
title: titre,
text: message,
type: type
});
};
}]) |
BenStorey/Jimbo | Jimbo/Jimbo/graphics/renderer.hpp |
#ifndef JIMBO_GRAPHICS_RENDERER_HPP
#define JIMBO_GRAPHICS_RENDERER_HPP
/////////////////////////////////////////////////////////
// Renderer.h
//
// <NAME>
//
// More of a placeholder right now. The void* is obviously not ideal, but I don't want to build
// a whole lot of subclasses to implement a Renderer interface just now. We're always a GLFWwindow* so can cast to it
//
/////////////////////////////////////////////////////////
namespace jimbo
{
class Renderer
{
public:
Renderer(void* window) : window_(window) {}
void startRenderFrame();
void endRenderFrame();
private:
void* window_;
};
}
#endif // JIMBO_GRAPHICS_RENDERER_HPP |
rsdoherty/azure-sdk-for-python | sdk/servicebus/azure-servicebus/tests/perf_tests/T1_legacy_tests/send_message_batch.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from ._test_base import _SendTest
from azure_devtools.perfstress_tests import get_random_bytes
from azure.servicebus import BatchMessage
class LegacySendMessageBatchTest(_SendTest):
def __init__(self, arguments):
super().__init__(arguments)
self.data = get_random_bytes(self.args.message_size)
def run_sync(self):
messages = (self.data for _ in range(self.args.num_messages))
batch = BatchMessage(messages)
self.sender.send(batch)
async def run_async(self):
messages = (self.data for _ in range(self.args.num_messages))
batch = BatchMessage(messages)
await self.async_sender.send(batch)
|
Shidesu/NovelRT | include/NovelRT/Graphics/GraphicsPipelineInput.h | // Copyright © <NAME> and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root
// for more information.
#ifndef NOVELRT_GRAPHICS_GRAPHICSPIPELINEINPUT_H
#define NOVELRT_GRAPHICS_GRAPHICSPIPELINEINPUT_H
#ifndef NOVELRT_GRAPHICS_H
#error NovelRT does not support including types explicitly by default. Please include Graphics.h instead for the Graphics namespace subset.
#endif
namespace NovelRT::Graphics
{
class GraphicsPipelineInput
{
private:
std::vector<GraphicsPipelineInputElement> _elements;
public:
explicit GraphicsPipelineInput(gsl::span<const GraphicsPipelineInputElement> elements) noexcept;
[[nodiscard]] gsl::span<const GraphicsPipelineInputElement> GetElements() const noexcept;
};
}
#endif // !NOVELRT_GRAPHICS_GRAPHICSPIPELINEINPUT_H
|
claymodel/bigcloud | badaClientSDK/inc/ImageDownloader.h | #ifndef IMAGEDOWNLOADER_H_
#define IMAGEDOWNLOADER_H_
#include "FriendsForm.h"
#include <FNet.h>
#include <FBase.h>
#include <FMedia.h>
class ImageDownloader :
public Osp::Net::Http::IHttpTransactionEventListener
{
public:
int SaveFile (Osp::Base::ByteBuffer* content);
public:
ImageDownloader();
~ImageDownloader();
public:
void SendRequestGet(Osp::Base::String requestUrl);
// IHttpTransactionEventListener
void OnTransactionReadyToRead(Osp::Net::Http::HttpSession& httpSession, Osp::Net::Http::HttpTransaction& httpTransaction, int availableBodyLen);
void OnTransactionAborted(Osp::Net::Http::HttpSession& httpSession, Osp::Net::Http::HttpTransaction& httpTransaction, result r);
void OnTransactionReadyToWrite(Osp::Net::Http::HttpSession& httpSession, Osp::Net::Http::HttpTransaction& httpTransaction, int recommendedChunkSize);
void OnTransactionHeaderCompleted(Osp::Net::Http::HttpSession& httpSession, Osp::Net::Http::HttpTransaction& httpTransaction, int headerLen, bool rs);
void OnTransactionCompleted(Osp::Net::Http::HttpSession& httpSession, Osp::Net::Http::HttpTransaction& httpTransaction);
void OnTransactionCertVerificationRequiredN(Osp::Net::Http::HttpSession& httpSession, Osp::Net::Http::HttpTransaction& httpTransaction, Osp::Base::String* pCert);
private:
Osp::Net::Http::HttpSession* __pSession;
Osp::Base::ByteBuffer* __pBuffer;
};
#endif /* IMAGEDOWNLOADER_H_ */
|
0xDECEA5ED/solitaire-player | src/test/java/com/secondthorn/solitaireplayer/players/pyramid/PyramidPlayerTest.java | <reponame>0xDECEA5ED/solitaire-player
package com.secondthorn.solitaireplayer.players.pyramid;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PyramidPlayerTest {
@Test
void cardsToString() {
String[] args = {"Board"};
PyramidPlayer player = new PyramidPlayer(args);
List<String> cards = new ArrayList<>();
for (char suit : "cdhs".toCharArray()) {
for (char rank : "A23456789TJQK".toCharArray()) {
cards.add("" + rank + suit);
}
}
String expectedString =
" Ac\n" +
" 2c 3c\n" +
" 4c 5c 6c\n" +
" 7c 8c 9c Tc\n" +
" Jc Qc Kc Ad 2d\n" +
" 3d 4d 5d 6d 7d 8d\n" +
"9d Td Jd Qd Kd Ah 2h\n" +
"3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh As 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks";
assertEquals(expectedString, player.cardsToString(cards));
}
}
|
RobberPhex/one-java-agent | one-java-agent-plugin/src/main/java/com/alibaba/oneagent/utils/JarUtils.java | <filename>one-java-agent-plugin/src/main/java/com/alibaba/oneagent/utils/JarUtils.java
package com.alibaba.oneagent.utils;
import java.io.File;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
*
* @author hengyunabc 2020-07-31
*
*/
public class JarUtils {
public static Attributes read(File jarFile) throws IOException {
JarFile jar = null;
Attributes attributes = null;
try {
jar = new JarFile(jarFile);
Manifest manifest = jar.getManifest();
attributes = manifest.getMainAttributes();
} finally {
IOUtils.close(jar);
}
return attributes;
}
}
|
1iyiwei/texture | src/code/Library/RandomShuffleSequencer.hpp | <gh_stars>10-100
/*
RandomShuffleSequencer.hpp
visit pixels in a random shuffled order
<NAME>
August 24, 2014
*/
#ifndef _RANDOM_SHUFFLE_SEQUENCER_HPP
#define _RANDOM_SHUFFLE_SEQUENCER_HPP
#include "Sequencer.hpp"
class RandomShuffleSequencer : public Sequencer
{
public:
RandomShuffleSequencer(void);
virtual bool Reset(const Texture & target);
virtual bool Next(Position & answer);
private:
vector<Position> _positions;
unsigned int _current_position;
};
#endif
|
410919244/wechat | src/main/java/me/hao0/wechat/model/card/Consume.java | package me.hao0.wechat.model.card;
import lombok.Data;
/**
* 核销Code接口
* @author zJun
* @date 2018年7月27日 上午11:39:52
*/
@Data
public class Consume {
/** 卡券ID。创建卡券时use_custom_code填写true时必填。非自定义Code不必填写。 */
private String card_id;
/** 需核销的Code码。 */
private String code;
}
|
mi1980/projecthadoop3 | udacity/cs101-intro-cs/code/lesson2/print_nums.py | <reponame>mi1980/projecthadoop3
# Define a procedure, print_numbers, that takes
# as input a positive whole number, and prints
# out all the whole numbers from 1 to the input
# number.
# Make sure your procedure prints "upwards", so
# from 1 up to the input number.
def print_numbers(n):
i = 1
while (i <= n):
print i
i += 1
print_numbers(3)
#>>> 1
#>>> 2
#>>> 3 |
ibabkov/let_it_code | problems/array/merge_sorted_array_88/index.js | <reponame>ibabkov/let_it_code
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
export const merge = function(nums1, p1, nums2, p2) {
if (p1 === '0') return nums2;
if (p2 === '0') return nums1;
p1 = p1 - 1;
p2 = p2 - 1;
while (p1 >= 0 || p2 >= 0) {
if (p1 < 0 || nums2[p2] >= nums1[p1]) {
nums1[p1 + p2 + 1] = nums2[p2--];
} else {
nums1[p1 + p2 + 1] = nums1[p1--];
}
}
return nums1;
}; |
quasarbright/quasarbright.github.io | python/imageProcessing/textDither.py | <filename>python/imageProcessing/textDither.py
'''Render an image as text with unicode shade characters
Uses Floyd-Steinberg dithering on a grayscale version of the image
'''
import numpy as np
from PIL import Image
from resize import resize
palette = [' ', '░', '▒', '▓', '█']
paletteSize = len(palette)
def findClosestColor(color: int, paletteSize: int = 5) -> int:
'''color in range [0, 1)
Rounds to the nearest 1/paletteSize
'''
color *= paletteSize
color = color // 1
color = color / paletteSize
return color
def dither(arr: np.ndarray) -> np.ndarray:
'''dithers image into a more discrete array with "lower bit depth"
Args:
arr (numpy.ndarray): image in range [0, 256)
shape (height, width)
Returns:
numpy.ndarray: dithered image in range [0, 1)
shape (height, width)
'''
# normalize image to [0, 1)
arr = np.copy(arr)
arr = arr / 256
height, width = arr.shape[:2]
for r in range(height):
for c in range(width):
oldPixel = arr[r, c]
newPixel = findClosestColor(oldPixel)
arr[r, c] = newPixel
error = oldPixel - newPixel
right = c < width - 1
down = r < height - 1
left = c > 0
if right:
arr[r, c+1] += error * 7/16
if right and down:
arr[r+1, c+1] += error * 1/16
if down:
arr[r+1, c] += error * 5/16
if left and down:
arr[r+1, c-1] += error * 1/16
return arr
def ditherToText(arr: np.ndarray) -> list:
'''takes dithered image array in range 0-1
and converts it to text
Args:
arr (numpy.ndarray): dithered array in range [0, 1)
shape (height, width)
should be "low bit depth", only having values corresponding to elements in the dither palette
Returns:
list: list of strings
Each string is a row of the image
'''
height, width = arr.shape[:2]
# map from grayscale value to palette item
pixelToPalette = {i / paletteSize: palette[i] for i in range(paletteSize)}
pixelToPalette[1] = palette[-1]
strings = []
for r in range(height):
row = ''
for c in range(width):
pixel = arr[r, c]
newValue = pixelToPalette[pixel]
row += newValue
strings.append(row)
return strings
def main(imgPath):
img = resize(imgPath, (100, 100))
img = img.convert('L')
arr = np.asarray(img)
dithered = dither(arr)
lines = ditherToText(dithered)
output = '\n'.join(lines)
print(output)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write(output)
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print('must supply image path')
sys.exit(1)
imgPath = sys.argv[1]
main(imgPath)
|
connect-israel/stratum-coordinator | test/streams/test.js | const path = require('path')
const kefir = require('kefir')
const jsonfile = require('jsonfile')
const uuid = require('uuid')
const _ = require('lodash')
const BlockCollection = require(path.join(__dirname, '../../model/bitcoin/block')).Collection
const TemplateToBlock = require(path.join(__dirname, '../../lib/raw-block-to-template'))
const TemplateToBlock$ = require(path.join(__dirname, '../../lib/master-template-stream'))
const expect = require('chai').expect
const Job = require(path.join(__dirname, '../../model/stratum/job')).Model
const UserModel = require(path.join(__dirname, '../../model/user')).Model
const Submission = require(path.join(__dirname, '../../model/stratum/submission')).Model
const GetDifficulty$ = require(path.join(__dirname, '../../view/stratum-session/report-new-difficulty-stream'))
const workerTemplate$ = require(path.join(__dirname, '../../lib/worker-template-stream'))
const reportJob$ = require(path.join(__dirname, '../../view/stratum-session/report-job-stream'))
const Block = require(path.join(__dirname, '../../model/bitcoin/block')).Model
const Session = require(path.join(__dirname, '../../model/stratum/session')).Model
const config = {
coinbase_message: '/ConnectBTC - Home for Miners/',
deposit_address: 'mxbnAXF76MNbChErLzYBFpAuzpReixrmyt',
block_version: '536870914'
}
const COIN_TYPE = 'btc'
const miningCoinService = {
getMiningCoin: async () => COIN_TYPE
}
const templateToBlock = TemplateToBlock(config)
let getBlock$ = (blocks, time = 0) => {
return kefir.sequentially(time, blocks.map((blockTemplate) => blockTemplate.request))
}
let blocksToWorkerTemplate$ = function (block$) {
return workerTemplate$(TemplateToBlock$(block$, Object.assign(config, {version: config.block_version}))
.map(function (startumTemplate) {
let template = startumTemplate.template
return {
'type': 'template_new',
'target': template.get('target'),
'create': template.get('create').getTime(),
'version': template.get('version'),
'previous_hash': template.get('previous_hash'),
'height': template.get('height'),
'id': template.id,
'coinbase': template.get('transaction').at(0).toHexString(),
'merkle_tree': template.getMerkleTree()
}
})
)
}
describe('Converting Raw Bitcoin block to full template for master', function () {
const blockTemplates = jsonfile.readFileSync(path.join(__dirname, '/blockTemplatesMaster.json'))
let testTemplate = function (resultTemplate, referenceTemplate) {
expect(resultTemplate.previous_hash).to.deep.equal(referenceTemplate.previous_hash)
expect(resultTemplate.height).to.deep.equal(referenceTemplate.height)
expect(resultTemplate.version).to.deep.equal(referenceTemplate.version)
expect(resultTemplate.target).to.deep.equal(referenceTemplate.target)
expect(resultTemplate.nonce).to.deep.equal(referenceTemplate.nonce)
if (referenceTemplate['default_witness_commitment']) {
expect(resultTemplate['default_witness_commitment']).to.equal(referenceTemplate['default_witness_commitment'])
}
}
let test$ = function (block$, result, done) {
TemplateToBlock$(block$, Object.assign(config, {version: config.block_version}))
.last()
.onValue((startumTemplate) => {
expect(startumTemplate.template.getMerkleRoot()).to.deep.equal(result.merkleroot)
expect(startumTemplate.newHeight).to.deep.equal(result.newHeight)
testTemplate(startumTemplate.template.attributes, result)
done()
})
}
it('should create a stratum block from getBlockTemplate for single address', function (done) {
blockTemplates.forEach(function (blockTemplate) {
let template = templateToBlock(_.assign(blockTemplate.request, {id: uuid.v4()}))
let result = blockTemplate.result
expect(template.getMerkleRoot()).to.deep.equal(result.merkleroot)
testTemplate(template.attributes, result)
})
done()
})
it('should create a stratum block from getBlockTemplate for multiSig address', function (done) {
let config = {
coinbase_message: '/ConnectBTC - Home for Miners/',
deposit_address: '3MnhAAGr1uwBioDtqikxXkXGA9QuXgoi3m',
block_version: '4'
}
let templateToBlock = TemplateToBlock(config)
const blockTemplates = jsonfile.readFileSync(path.join(__dirname, '/blockTemplatesMasterMultiSig.json'))
blockTemplates.forEach(function (blockTemplate) {
blockTemplate.request.transactions.forEach(tx => {
if (!tx.txid) tx.txid = tx.hash
})
let template = templateToBlock(_.assign(blockTemplate.request, {id: uuid.v4()}))
let result = blockTemplate.result
expect(template.getMerkleRoot()).to.deep.equal(result.merkleroot)
testTemplate(template.attributes, result)
})
done()
})
it('should create a stratum block from a single template $', function (done) {
let block$ = getBlock$([blockTemplates[0]])
let result = blockTemplates[0].result
test$(block$, result, done)
})
it('should create a stratum block from a $ of ascending blocks', function (done) {
let block$ = getBlock$([blockTemplates[0], blockTemplates[1], blockTemplates[2], blockTemplates[3]])
let result = blockTemplates[3].result
test$(block$, result, done)
})
it('should not create a stratum block when new block height is lower', function (done) {
let block$ = getBlock$([blockTemplates[1], blockTemplates[0]])
let result = blockTemplates[1].result
test$(block$, result, done)
})
it('should create a stratum block once the block height goes back up', function (done) {
let block$ = getBlock$([blockTemplates[1], blockTemplates[0], blockTemplates[2]])
let result = blockTemplates[2].result
test$(block$, result, done)
})
it('should create a stratum block with new height', function (done) {
let block$ = getBlock$([blockTemplates[0], blockTemplates[1], blockTemplates[2]])
let result = blockTemplates[2].result
test$(block$, result, done)
})
it('should create a stratum block that is not a new height when height dosn\'t change', function (done) {
let block$ = getBlock$([blockTemplates[1], blockTemplates[1], blockTemplates[1]])
let result = blockTemplates[1].result
result.newHeight = false
test$(block$, result, done)
})
it('should create a stratum block that is not a new height after going up and down', function (done) {
let block$ = getBlock$([blockTemplates[1], blockTemplates[2], blockTemplates[1], blockTemplates[2]])
let result = blockTemplates[2].result
result.newHeight = false
test$(block$, result, done)
})
})
describe('Converting Bitcoin block to worker template', function () {
const blockTemplates = jsonfile.readFileSync(path.join(__dirname, '/blockTemplatesMaster.json'))
let test$ = function (block$, expected, done) {
let i = 0
blocksToWorkerTemplate$(block$)
.onValue(function (value) {
expect(value.method).to.deep.equal(expected[i])
i++
})
.onEnd(function () {
done()
})
}
it('should return a reset method for single block', function (done) {
let expected = ['reset']
let block$ = getBlock$([blockTemplates[0]])
test$(block$, expected, done)
})
it('should return a reset method for ascending blocks', function (done) {
let expected = ['reset', 'reset', 'reset', 'reset']
let block$ = getBlock$([blockTemplates[0], blockTemplates[1], blockTemplates[2], blockTemplates[3]])
test$(block$, expected, done)
})
it('should add blocks without reset when repeating blocks', function (done) {
let expected = ['reset', 'add', 'add', 'add']
let block$ = getBlock$([blockTemplates[0], blockTemplates[0], blockTemplates[0], blockTemplates[0]])
test$(block$, expected, done)
})
it('should return a reset/add depending if repeating or not', function (done) {
let expected = ['reset', 'add', 'reset', 'add', 'add', 'reset']
let block$ = getBlock$([blockTemplates[0], blockTemplates[0], blockTemplates[1], blockTemplates[1], blockTemplates[1], blockTemplates[2]])
test$(block$, expected, done)
})
})
describe('Converting Template to Stratum Protocol', function () {
const stratumSubmissionsResults = jsonfile.readFileSync(path.join(__dirname, '/stratumSubmissionsResults.json'))
const blockTemplates = jsonfile.readFileSync(path.join(__dirname, '/blockTemplatesMaster.json'))
let test$ = function (blockTemplates, expectedArray, done) {
let block$ = getBlock$(blockTemplates, 50)
let template$ = blocksToWorkerTemplate$(block$)
.map((workerTemplate) => {
let {template, method} = workerTemplate
method === 'reset' && (template = template[0])
let block = new Block(template)
block.blockHeaderToHexString(block.getMerkleRoot())
let job = new Job({template: block, difficulty: 65000})
return {model: job, type: method}
})
let count = 0
reportJob$(template$)
.onValue(function (response) {
let expected = expectedArray[count]
count++
expect(response.id).to.be.null // eslint-disable-line
expect(response.method).to.deep.equal(expected.method)
response.method === 'mining.notify' && response.params.shift()
expect(response.params).to.deep.equal(expected.params)
})
.onError(err => done(err))
.onEnd(function (response) {
done()
})
}
it('should create jobs from single block', function (done) {
test$([blockTemplates[0]], stratumSubmissionsResults[0], done)
})
it('should create jobs from all blocks', function (done) {
test$(blockTemplates, stratumSubmissionsResults[1], done)
})
})
describe('Setting new difficulty', function () {
const difficultyMock = jsonfile.readFileSync(path.join(__dirname, '/difficultyMocks.json'))
difficultyMock.forEach(function ({submissions, target, response}, index) {
it('Should produce correct difficulty for scenario ' + index, function (done) {
let now = new Date()
now = now.getTime()
let session = new Session({})
session.get('worker').add({id: '007', name: 'wolfgang', user: new UserModel({name: 'wolf001'})})
session.set('miningCoin', COIN_TYPE)
let submissionCollection = submissions.map((submission) => {
now = now + submission[0]
return new Submission({
create: new Date(now),
'valid': true,
worker: '12123',
job: new Job({difficulty: submission[1]})
})
})
let templateCollection = new BlockCollection([], {coinType: COIN_TYPE})
templateCollection.add({target})
let submission$ = kefir.sequentially(0, submissionCollection)
const templateCollections = [templateCollection]
GetDifficulty$({session, submissionStream: submission$, templateCollections, miningCoinService})
.onValue(function (diff) {
expect(diff).to.equal(response)
done()
})
setTimeout(() => {
templateCollection.add({target})
templateCollection.add({target})
templateCollection.add({target})
templateCollection.add({target})
}, 100)
})
})
})
xdescribe('Create block submission from templates', function () {
const blockTemplates = jsonfile.readFileSync(path.join(__dirname, '/blockTemplatesMaster.json'))
let templatesCollection = new BlockCollection()
before(function (done) {
blockTemplates.forEach(function (blockTemplate) {
templatesCollection.add(templateToBlock(_.assign(blockTemplate.request, {id: uuid.v4()})))
})
done()
})
// TODO: add content to test
// it('should return a valid block for submission', function (done) {
// done()
// })
})
|
EpicSquid/MysticalLib | src/main/java/epicsquid/mysticallib/material/MaterialTypes.java | <reponame>EpicSquid/MysticalLib<gh_stars>1-10
package epicsquid.mysticallib.material;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
public class MaterialTypes {
public static Map<String, Item.ToolMaterial> materialMap = new HashMap<>();
public static Map<String, ItemArmor.ArmorMaterial> armorMaterialMap = new HashMap<>();
public static Map<String, KnifeStats> statsMap = new HashMap<>();
public static Map<Item.ToolMaterial, KnifeStats> materialToStatsMap = new HashMap<>();
public static void addMaterial(String name, Item.ToolMaterial material, ItemArmor.ArmorMaterial armor, float damage, float speed) {
addMaterial(name, material, armor, new KnifeStats(damage, speed));
}
public static void addMaterial(String name, Item.ToolMaterial material, ItemArmor.ArmorMaterial armor, KnifeStats stats) {
materialToStatsMap.put(material, stats);
armorMaterialMap.put(name, armor);
statsMap.put(name, stats);
materialMap.put(name, material);
}
public static Item.ToolMaterial material(String name) {
return materialMap.get(name);
}
public static ItemArmor.ArmorMaterial armor (String name) {
return armorMaterialMap.get(name);
}
public static KnifeStats stats(String name) {
return statsMap.get(name);
}
public static KnifeStats stats(Item.ToolMaterial tool) {
return materialToStatsMap.get(tool);
}
public static class KnifeStats {
public float damage;
public float speed;
public KnifeStats(float damage, float speed) {
this.damage = damage;
this.speed = speed;
}
}
}
|
jmckenna/ZOO-Project | zoo-project/zoo-kernel/service_internal_php7.c | /*
* Author : <NAME>, <NAME>
*
* Copyright (c) 2009-2016 GeoLabs SARL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifdef WIN32
#define NO_FCGI_DEFINES
#define ZEND_WIN32_KEEP_INLINE
#endif
#ifndef ZEND_DEBUG
#define ZEND_DEBUG 0
#endif
#include <sapi/embed/php_embed.h>
#include <zend_stream.h>
#include "service_internal_php.h"
#include "response_print.h"
map* php_hashtable_to_map(HashTable* tab);
maps* php_array_to_maps(HashTable* arr);
void php_map_to_array(map* src, zval* arr);
void php_maps_to_array(maps* src, zval* arr);
#define zval_make_ref_array(zv,len) for (int elem = 0; elem < len; elem++) ZVAL_MAKE_REF(&zv[elem]);
#define zval_unref_array(zv,len) for (int elem = 0; elem < len; elem++) ZVAL_UNREF(&zv[elem]);
#ifdef ZTS
void ***tsrm_ls;
#endif
ZEND_BEGIN_MODULE_GLOBALS(zoo)
long _SERVICE_SUCCEEDED;
long _SERVICE_FAILED;
ZEND_END_MODULE_GLOBALS(zoo)
#ifdef ZTS
#define ZOO_G(v) TSRMG(zoo_globals_id, zend_zoo_globals *, v)
#else
#define ZOO_G(v) (zoo_globals.v)
#endif
#define PHP_ZOO_VERSION "1.0"
#define PHP_ZOO_EXTNAME "ZOO"
PHP_MINIT_FUNCTION(zoo);
PHP_MSHUTDOWN_FUNCTION(zoo);
PHP_RINIT_FUNCTION(zoo);
PHP_FUNCTION(zoo_Translate);
PHP_FUNCTION(zoo_UpdateStatus);
PHP_FUNCTION(zoo_SERVICE_SUCCEEDED);
PHP_FUNCTION(zoo_SERVICE_FAILED);
extern zend_module_entry zoo_module_entry;
#define phpext_zoo_ptr &zoo_entry
ZEND_DECLARE_MODULE_GLOBALS(zoo)
static zend_function_entry zoo_functions[] = {
PHP_FE(zoo_Translate, NULL)
PHP_FE(zoo_UpdateStatus, NULL)
PHP_FE(zoo_SERVICE_SUCCEEDED, NULL)
PHP_FE(zoo_SERVICE_FAILED, NULL)
{NULL, NULL, NULL}
};
zend_module_entry zoo_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
PHP_ZOO_EXTNAME,
zoo_functions,
PHP_MINIT(zoo),
PHP_MSHUTDOWN(zoo),
PHP_RINIT(zoo),
NULL,
NULL,
#if ZEND_MODULE_API_NO >= 20010901
PHP_ZOO_VERSION,
#endif
STANDARD_MODULE_PROPERTIES
};
ZEND_GET_MODULE(zoo)
PHP_INI_BEGIN()
PHP_INI_END()
static void
php_zoo_init_globals(zend_zoo_globals *zoo_globals)
{
zoo_globals->_SERVICE_SUCCEEDED=3;
zoo_globals->_SERVICE_FAILED=4;
}
PHP_RINIT_FUNCTION(zoo)
{
return SUCCESS;
}
PHP_MINIT_FUNCTION(zoo)
{
ZEND_INIT_MODULE_GLOBALS(zoo, php_zoo_init_globals,NULL);
REGISTER_INI_ENTRIES();
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(zoo)
{
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
PHP_FUNCTION(zoo_Translate)
{
char *value;
size_t value_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &value, &value_len) == FAILURE) {
RETURN_NULL();
}
//RETURN_STRING(_ss(value), 1);
RETURN_STRINGL(_ss(value), 1);
}
PHP_FUNCTION(zoo_UpdateStatus)
{
zval *arr;
char *message;
size_t message_len;
zend_long pourcent;
char *status=(char*)malloc(4*sizeof(char));
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "asl", &arr, &message, &message_len,&pourcent) == FAILURE) {
RETURN_NULL();
}
HashTable* t=HASH_OF(arr);
maps* conf = php_array_to_maps(t);
setMapInMaps(conf,"lenv","message",message);
sprintf(status,"%d",pourcent);
setMapInMaps(conf,"lenv","status",status);
_updateStatus(conf);
freeMaps(&conf);
free(conf);
free(status);
RETURN_NULL();
}
PHP_FUNCTION(zoo_SERVICE_SUCCEEDED)
{
RETURN_LONG(ZOO_G(_SERVICE_SUCCEEDED));
}
PHP_FUNCTION(zoo_SERVICE_FAILED)
{
RETURN_LONG(ZOO_G(_SERVICE_FAILED));
}
/**
* Load a PHP script then run the function corresponding to the service by
* passing the conf, inputs and outputs parameters by reference.
*
* @param main_conf the conf maps containing the main.cfg settings
* @param request the map containing the HTTP request
* @param s the service structure
* @param real_inputs the maps containing the inputs
* @param real_outputs the maps containing the outputs
*/
int zoo_php_support(maps** main_conf, map* request, service* s, maps **real_inputs, maps **real_outputs) {
maps* m = *main_conf;
maps* inputs = *real_inputs;
maps* outputs = *real_outputs;
map* libp = getMapFromMaps(m, "main", "libPath");
int res=SERVICE_FAILED;
map* tmp = getMap(s->content, "serviceProvider");
if (tmp == NULL || tmp->value == NULL) {
return errorException(m, "Missing serviceProvider (library file)", "NoApplicableCode", NULL);
}
#ifdef IGNORE_METAPATH
map* mp = createMap("metapath", "");
#else
map* mp = getMap(request, "metapath");
#endif
map* cwd = getMapFromMaps(m,"lenv","cwd");
char *scriptName;
if (libp != NULL && libp->value != NULL) {
scriptName = (char*) malloc((strlen(libp->value) + strlen(tmp->value) + 2)*sizeof(char));
sprintf (scriptName, "%s/%s", libp->value, tmp->value);
}
else {
if(mp != NULL && strlen(mp->value) > 0) {
scriptName = (char*) malloc((strlen(cwd->value)+strlen(mp->value)+strlen(tmp->value)+3)*sizeof(char));
sprintf(scriptName, "%s/%s/%s", cwd->value, mp->value, tmp->value);
}
else {
scriptName = (char*) malloc((strlen(cwd->value)+strlen(tmp->value)+2)*sizeof(char));
sprintf(scriptName, "%s/%s", cwd->value, tmp->value);
}
}
zend_file_handle iscript;
iscript.type = ZEND_HANDLE_FD;
iscript.opened_path = NULL;
iscript.filename = tmp->value;
iscript.free_filename = 0;
FILE* temp = fopen(scriptName, "rb");
if(temp == NULL) {
char tmp1[1024];
sprintf(tmp1, _("Unable to load the PHP file %s"), tmp->value);
free(scriptName);
return errorException(m, tmp1, "NoApplicableCode", NULL);
}
iscript.handle.fd = fileno(temp);
php_embed_init(0, NULL);
zend_try {
zend_startup_module(&zoo_module_entry);
php_execute_script(&iscript TSRMLS_CC);
zval iargs[3];
zval iret, ifunc;
ZVAL_STRING(&ifunc, s->name);
php_maps_to_array(*main_conf, iargs);
php_maps_to_array(*real_inputs, iargs+1);
php_maps_to_array(*real_outputs, iargs+2);
zval_make_ref_array(iargs,3);
if((res = call_user_function(EG(function_table), NULL, &ifunc, &iret, 3, iargs)) == SUCCESS) {
zval_unref_array(iargs,3);
zend_string_release(Z_STR_P(&ifunc));
HashTable* t = HASH_OF(iargs+2);
HashTable* t1 = HASH_OF(iargs);
freeMaps(real_outputs);
free(*real_outputs);
freeMaps(main_conf);
free(*main_conf);
*real_outputs = php_array_to_maps(t);
*main_conf = php_array_to_maps(t1);
res = Z_LVAL(iret);
}
else {
free(scriptName);
fclose(temp);
return errorException(m, "Unable to process.", "NoApplicableCode", NULL);;
}
}
zend_catch {
free(scriptName);
fclose(temp);
return errorException(m, "Unable to process.", "NoApplicableCode", NULL);;
}
zend_end_try();
free(scriptName);
fclose(temp);
php_embed_shutdown(TSRMLS_C);
return res;
}
/**
* Convert a Zoo struct maps to a php array
*
* @param src the struct maps* to convert (source data structure)
* @param arr pointer to zval that is to hold the php array
*/
void php_maps_to_array(maps* src, zval* arr) {
int tres = array_init(arr);
maps* pm = src;
while (pm != NULL) {
zval zv; // allocate on heap??
php_map_to_array(pm->content, &zv);
add_assoc_zval(arr, pm->name, &zv);
pm = pm->next;
}
}
/**
* Convert a Zoo map to a php array
*
* @param src the struct map* to convert (source data structure)
* @param arr pointer to zval that is to hold the php array
*/
void php_map_to_array(map* src, zval* arr) {
int tres = array_init(arr);
map* pm = src;
while(pm != NULL) {
map* sMap = getMapArray(pm, "size", 0);
if (pm->value != NULL && strncmp(pm->name, "value", 5) == 0 && sMap != NULL) {
tres = add_assoc_stringl(arr, pm->name, pm->value, atoi(sMap->value));
}
else {
tres = add_assoc_string(arr, pm->name, pm->value);
}
pm = pm->next;
}
}
/**
* Convert a php hashtable (array) to a Zoo maps
*
* @param arr the php hashtable to convert
* @return the created struct maps*
*/
maps* php_array_to_maps(HashTable* arr) {
maps* res = NULL;
zval* data;
zend_string* key = NULL;
ulong num_key;
ZEND_HASH_FOREACH_KEY_VAL(arr, num_key, key, data)
if (!key) { // HASH_KEY_IS_LONG
key = strpprintf(64, "%lu", num_key);
}
zval copy;
ZVAL_DUP(©, data);
HashTable* tab = HASH_OF(©);
maps* node = createMaps(ZSTR_VAL(key));
node->content = php_hashtable_to_map(tab);
if(res == NULL) {
res = node;
}
else {
addMapsToMaps(&res, node);
freeMaps(&node);
free(node);
}
zval_dtor(©);
ZEND_HASH_FOREACH_END();
return res;
}
/**
* Convert a php hashtable (array) to a Zoo map
*
* @param tab the php hashtable to convert
* @return the created struct map*
*/
map* php_hashtable_to_map(HashTable* tab) {
map* res = NULL;
zval* data;
zend_string* key = NULL;
ulong num_key;
ZEND_HASH_FOREACH_KEY_VAL(tab, num_key, key, data)
if (!key) { // HASH_KEY_IS_LONG
key = strpprintf(64, "%lu", num_key);
}
zval copy;
ZVAL_DUP(©, data);
convert_to_string(©);
if(strncmp(ZSTR_VAL(key), "value", 5) == 0) {
size_t len = Z_STRLEN(copy);
res = addToMapWithSize(res, ZSTR_VAL(key), Z_STRVAL(copy), len);
}
else {
if (res == NULL) {
res = createMap(ZSTR_VAL(key), Z_STRVAL(copy));
}
else {
addToMap(res, ZSTR_VAL(key), Z_STRVAL(copy));
}
}
zval_dtor(©);
ZEND_HASH_FOREACH_END();
return res;
}
|
macaurther/DOCUSA | CvGameCoreDLL/Boost-1.32.0/include/boost/random/discard_block.hpp | <reponame>macaurther/DOCUSA
/* boost random/discard_block.hpp header file
*
* Copyright <NAME> 2002
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org for most recent version including documentation.
*
* $Id: discard_block.hpp,v 1.10 2004/07/27 03:43:32 dgregor Exp $
*
* Revision history
* 2001-03-02 created
*/
#ifndef BOOST_RANDOM_DISCARD_BLOCK_HPP
#define BOOST_RANDOM_DISCARD_BLOCK_HPP
#include <iostream>
#include <boost/config.hpp>
#include <boost/limits.hpp>
#include <boost/static_assert.hpp>
namespace boost {
namespace random {
template<class UniformRandomNumberGenerator, unsigned int p, unsigned int r>
class discard_block
{
public:
typedef UniformRandomNumberGenerator base_type;
typedef typename base_type::result_type result_type;
BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
BOOST_STATIC_CONSTANT(unsigned int, total_block = p);
BOOST_STATIC_CONSTANT(unsigned int, returned_block = r);
#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
BOOST_STATIC_ASSERT(total_block >= returned_block);
#endif
discard_block() : _rng(), _n(0) { }
explicit discard_block(const base_type & rng) : _rng(rng), _n(0) { }
template<class It> discard_block(It& first, It last)
: _rng(first, last), _n(0) { }
void seed() { _rng.seed(); _n = 0; }
template<class T> void seed(T s) { _rng.seed(s); _n = 0; }
template<class It> void seed(It& first, It last)
{ _n = 0; _rng.seed(first, last); }
const base_type& base() const { return _rng; }
result_type operator()()
{
if(_n >= returned_block) {
// discard values of random number generator
for( ; _n < total_block; ++_n)
_rng();
_n = 0;
}
++_n;
return _rng();
}
result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return (_rng.min)(); }
result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return (_rng.max)(); }
static bool validation(result_type x) { return true; } // dummy
#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
template<class CharT, class Traits>
friend std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits>& os, const discard_block& s)
{
os << s._rng << " " << s._n << " ";
return os;
}
template<class CharT, class Traits>
friend std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits>& is, discard_block& s)
{
is >> s._rng >> std::ws >> s._n >> std::ws;
return is;
}
#endif
friend bool operator==(const discard_block& x, const discard_block& y)
{ return x._rng == y._rng && x._n == y._n; }
friend bool operator!=(const discard_block& x, const discard_block& y)
{ return !(x == y); }
#else
// Use a member function; Streamable concept not supported.
bool operator==(const discard_block& rhs) const
{ return _rng == rhs._rng && _n == rhs._n; }
bool operator!=(const discard_block& rhs) const
{ return !(*this == rhs); }
#endif
private:
base_type _rng;
unsigned int _n;
};
#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
// A definition is required even for integral static constants
template<class UniformRandomNumberGenerator, unsigned int p, unsigned int r>
const bool discard_block<UniformRandomNumberGenerator, p, r>::has_fixed_range;
template<class UniformRandomNumberGenerator, unsigned int p, unsigned int r>
const unsigned int discard_block<UniformRandomNumberGenerator, p, r>::total_block;
template<class UniformRandomNumberGenerator, unsigned int p, unsigned int r>
const unsigned int discard_block<UniformRandomNumberGenerator, p, r>::returned_block;
#endif
} // namespace random
} // namespace boost
#endif // BOOST_RANDOM_DISCARD_BLOCK_HPP
|
BeatHubmann/19H-AdvNCSE | series1_workbench/fvm_scalar_1d/tests/test_numerical_flux.cpp | <gh_stars>1-10
#include <gtest/gtest.h>
#include <ancse/numerical_flux.hpp>
template <class NumericalFlux>
void check_consistency(const NumericalFlux &nf) {
auto model = make_dummy_model();
auto to_check = std::vector<double>{1.0, 2.0, 3.3251, -1.332};
for (auto u : to_check) {
ASSERT_DOUBLE_EQ(model.flux(u), nf(u, u));
}
}
TEST(TestCentralFlux, consistency) {
auto model = make_dummy_model();
auto central_flux = CentralFlux(model);
check_consistency(central_flux);
}
TEST(TestRusanovFlux, consistency)
{
auto model= make_dummy_model();
auto rusanov_flux= RusanovFlux(model);
check_consistency(rusanov_flux);
}
TEST(TestLxFFlux, consistency)
{
auto model= make_dummy_model();
const double dx{0.1};
const double dt{0.1};
auto lxf_flux= LxFFlux(model, dx, dt);
check_consistency(lxf_flux);
}
|
meee1/OpenSolo | sololink/flightcode/python/usb_nop.py | <gh_stars>10-100
#!/bin/bash
def init():
pass
def uninit():
pass
def enable():
pass
def disable():
pass
|
colorofchange/Champaign | app/models/phone_number.rb | <filename>app/models/phone_number.rb<gh_stars>10-100
# == Schema Information
#
# Table name: phone_numbers
#
# id :integer not null, primary key
# number :string
# country :string
#
class PhoneNumber < ActiveRecord::Base
validates :number, presence: true, phony_plausible: true
phony_normalize :number
end
|
Miffyli/incubator | entity_gym/entity_gym/examples/cherry_pick.py | <reponame>Miffyli/incubator
from dataclasses import dataclass, field
from entity_gym.environment.environment import EntityType
import numpy as np
from typing import Dict, List, Mapping
from entity_gym.environment import (
SelectEntityActionMask,
Entity,
EntityID,
Environment,
EpisodeStats,
ObsSpace,
SelectEntityAction,
SelectEntityActionSpace,
ActionSpace,
Observation,
Action,
)
@dataclass
class CherryPick(Environment):
"""
The CherryPick environment is initialized with a list of 32 cherries of random quality.
On each timestep, the player can pick up one of the cherries.
The player receives a reward of the quality of the cherry picked.
The environment ends after 16 steps.
The quality of the top 16 cherries is normalized so that the maximum total achievable reward is 1.0.
"""
num_cherries: int = 32
cherries: List[float] = field(default_factory=list)
last_reward: float = 0.0
step: int = 0
@classmethod
def obs_space(cls) -> ObsSpace:
return ObsSpace(
{
"Cherry": Entity(["quality"]),
"Player": Entity([]),
}
)
@classmethod
def action_space(cls) -> Dict[str, ActionSpace]:
return {"Pick Cherry": SelectEntityActionSpace()}
def reset(self) -> Observation:
cherries = [np.random.normal() for _ in range(self.num_cherries)]
# Normalize so that the sum of the top half is 1.0
top_half = sorted(cherries, reverse=True)[: self.num_cherries // 2]
sum_top_half = sum(top_half)
add = 2.0 * (1.0 - sum_top_half) / self.num_cherries
self.cherries = [c + add for c in cherries]
self.last_reward = 0.0
self.step = 0
self.total_reward = 0.0
return self.observe()
def observe(self) -> Observation:
done = self.step == self.num_cherries // 2
ids: Dict[EntityType, List[EntityID]] = {
"Cherry": [("Cherry", a) for a in range(len(self.cherries))],
"Player": ["Player"],
}
return Observation(
features={
"Cherry": np.array(self.cherries, dtype=np.float32).reshape(-1, 1),
"Player": np.zeros([1, 0], dtype=np.float32),
},
ids=ids,
actions={
"Pick Cherry": SelectEntityActionMask(
actor_ids=["Player"],
actee_ids=ids["Cherry"],
),
},
reward=self.last_reward,
done=done,
end_of_episode_info=EpisodeStats(self.step, self.total_reward)
if done
else None,
)
def act(self, action: Mapping[str, Action]) -> Observation:
assert len(action) == 1, action
a = action["Pick Cherry"]
assert isinstance(a, SelectEntityAction)
_, chosen_cherry_idx = a.actees[0]
self.last_reward = self.cherries.pop(chosen_cherry_idx)
self.total_reward += self.last_reward
self.step += 1
return self.observe()
|
hanswenzel/opticks | ana/cie.py | #!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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.
#
"""
cie.py: converts wavelength spectra into XYZ and RGB colorspaces
===================================================================
Conversion of the binned wavelength spectra into XYZ (using
CIE weighting functions) and then RGB produces a spectrum
[FIXED] Unphysical color repetition
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Uniform scaling by maximal single X,Y,Z or R,G,B
prior to clipping gets rid of the unphysical color repetition
but theres kinda a between the green and the blue, where cyan
should be
#hRGB_raw /= hRGB_raw[0,:,0].max() # scaling by maximal red, results in muted spectrum
#hRGB_raw /= hRGB_raw[0,:,1].max() # scaling by maximal green, OK
#hRGB_raw /= hRGB_raw[0,:,2].max() # scaling by maximal blue, similar to green by pumps the blues and nice yellow
The entire spectral locus is outside sRGB gamut (the triangle),
so all bins are being clipped.
Not clipping produces a psychedelic mess.
[ISSUE] Blue/Green transition looks unphysical
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Need better way to handle out of gamut ?
Raw numbers show that green ramps up thru 430..480 nm but
its all negative, so that info is clipped.
::
In [68]: np.set_printoptions(linewidth=150)
In [75]: np.hstack([wd[:-1,None],c.raw[0],c.xyz[0],c.rgb[0]])
Out[75]:
array([[ 350. , 0. , 0.016, 0.102, 0. , 0. , 0. , -0. , 0. , 0. ],
[ 370. , 0.015, 0.105, 1.922, 0. , 0. , 0.001, -0.001, 0. , 0.001],
[ 390. , 1.873, 0.582, 20.444, 0.001, 0. , 0.011, -0.003, 0. , 0.012],
[ 410. , 49.306, 2.691, 205.061, 0.028, 0.002, 0.115, 0.03 , -0.019, 0.123],
[ 430. , 273.393, 10.384, 1386.823, 0.153, 0.006, 0.779, 0.1 , -0.105, 0.83 ],
[ 450. , 343.75 , 33.415, 1781.385, 0.193, 0.019, 1. , 0.098, -0.11 , 1.064],
[ 470. , 191.832, 89.944, 1294.473, 0.108, 0.05 , 0.727, -0.091, 0.021, 0.764],
[ 490. , 32.012, 213.069, 465.525, 0.018, 0.12 , 0.261, -0.256, 0.218, 0.253],
[ 510. , 16.48 , 500.611, 155.962, 0.009, 0.281, 0.088, -0.446, 0.522, 0.036],
[ 530. , 159.607, 869.052, 43.036, 0.09 , 0.488, 0.024, -0.472, 0.829, -0.069],
[ 550. , 433.715, 994.463, 8.758, 0.243, 0.558, 0.005, -0.072, 0.812, -0.095],
[ 570. , 772.904, 950.107, 1.308, 0.434, 0.533, 0.001, 0.586, 0.58 , -0.084],
[ 590. , 1021.039, 762.587, 0.143, 0.573, 0.428, 0. , 1.199, 0.248, -0.055],
[ 610. , 1000.205, 500.338, 0.012, 0.561, 0.281, 0. , 1.388, -0.017, -0.026],
[ 630. , 656.21 , 263.667, 0.001, 0.368, 0.148, 0. , 0.966, -0.079, -0.01 ],
[ 650. , 283.632, 110.045, 0. , 0.159, 0.062, 0. , 0.421, -0.038, -0.004],
[ 670. , 80.766, 36.117, 0. , 0.045, 0.02 , 0. , 0.116, -0.006, -0.002],
[ 690. , 17.024, 11.172, 0. , 0.01 , 0.006, 0. , 0.021, 0.003, -0.001]])
Chromatic Adaption
~~~~~~~~~~~~~~~~~~~~
* http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
Refs
~~~~~
https://github.com/colour-science/colour/issues/191
http://www.scipy-lectures.org/advanced/image_processing/index.html
http://www.scipy-lectures.org/packages/scikit-image/index.html#scikit-image
http://www.scipy.org/scikits.html
separate from scipy, but under the "brand"
"""
import os, logging, numpy as np
log = logging.getLogger(__name__)
np.set_printoptions(linewidth=150)
import matplotlib.pyplot as plt
import ciexyz.ciexyz as _cie
from env.graphics.ciexyz.XYZ import Spectrum
from env.graphics.ciexyz.RGB import RGB
class CIE(object):
def __init__(self, colorspace="sRGB/D65", whitepoint=None):
cs = RGB(colorspace)
self.x2r = cs.x2r
self.whitepoint = whitepoint
def hist0d_XYZ(self,w, nb=100):
X = np.sum(_cie.X(w))
Y = np.sum(_cie.Y(w))
Z = np.sum(_cie.Z(w))
hX = np.repeat(X, nb)
hY = np.repeat(Y, nb)
hZ = np.repeat(Z, nb)
raw = np.dstack([hX,hY,hZ])
self.raw = np.copy(raw)
return raw
def hist1d_XYZ(self,w,x,xb):
hX, hXx = np.histogram(x,bins=xb, weights=_cie.X(w))
hY, hYx = np.histogram(x,bins=xb, weights=_cie.Y(w))
hZ, hZx = np.histogram(x,bins=xb, weights=_cie.Z(w))
assert np.all(hXx == xb) & np.all(hYx == xb ) & np.all(hZx == xb)
raw = np.dstack([hX,hY,hZ])
self.raw = np.copy(raw)
return raw
def hist2d_XYZ(self,w,x,y,xb,yb):
bins = [xb,yb]
hX, hXx, hXy = np.histogram2d(x,y,bins=bins, weights=_cie.X(w))
hY, hYx, hYy = np.histogram2d(x,y,bins=bins, weights=_cie.Y(w))
hZ, hZx, hZy = np.histogram2d(x,y,bins=bins, weights=_cie.Z(w))
assert np.all(hXx == xb) & np.all(hYx == xb ) & np.all(hZx == xb)
assert np.all(hXy == yb) & np.all(hYy == yb ) & np.all(hZy == yb)
return np.dstack([hX,hY,hZ])
def norm_XYZ(self, hXYZ, norm=2, scale=1):
"""
Trying to find an appropriate way to normalize XYZ values
0,1,2
scale by maximal of X,Y,Z
3
scale by maximal X+Y+Z
4
scale by Yint of an externally determined whitepoint
(problem is that is liable to be with very much more light
than are looking at...)
5
scale by Yint of the spectrum provided, this
is also yielding very small X,Y,Z
>50
scale is used, for normalization with Y value
obtained from the histogram norm identified bin
Hmm, some adhoc exposure factor seems unavoidable given the
range of intensities so perhaps the adhoc techniques are appropriate after all.
Initial thinking was that the out-of-gamut problem was tied up with the
exposure problem, but they are kinda orthogonal: think vectors in XYZ space,
the length of the vector doesnt change the hue.
"""
if norm in [0,1,2]:
nscale = hXYZ[:,:,norm].max()
elif norm == 3:
nscale = np.sum(hXYZ, axis=2).max()
elif norm == 4:
assert not self.whitepoint is None
nscale = self.whitepoint[4]
elif norm == 5 or norm > 50:
nscale = scale
else:
nscale = 1
pass
hXYZ /= nscale
self.scale = nscale
self.xyz = np.copy(hXYZ)
return hXYZ
def XYZ_to_RGB(self, hXYZ):
return np.dot( hXYZ, self.x2r.T )
def hist0d(self, w, norm=2, nb=100):
hXYZ_raw = self.hist0d_XYZ(w, nb=nb)
hXYZ = self.norm_XYZ(hXYZ_raw, norm=norm)
hRGB = self.XYZ_to_RGB(hXYZ)
self.rgb = np.copy(hRGB)
return hRGB,hXYZ,None
def hist1d(self, w, x, xb, norm=2):
hXYZ_raw = self.hist1d_XYZ(w,x,xb)
if norm == 5:
scale = np.sum(_cie.Y(w))
elif norm > 50:
# assume norm is pointing to a bin, the Y value of which is used for scaling
scale = hXYZ_raw[0,norm,1]
else:
scale = 1
pass
hXYZ = self.norm_XYZ(hXYZ_raw, norm=norm, scale=scale)
hRGB = self.XYZ_to_RGB(hXYZ)
self.rgb = np.copy(hRGB)
return hRGB,hXYZ,xb
def hist2d(self, w, x, y, xb, yb, norm=2):
hXYZ_raw = self.hist2d_XYZ(w,x,y,xb,yb)
self.raw = hXYZ_raw
hXYZ = self.norm_XYZ(hXYZ_raw, norm=norm)
hRGB = self.XYZ_to_RGB(hXYZ)
extent = [xb[0], xb[-1], yb[0], yb[-1]]
return hRGB,hXYZ,extent
def spectral_plot(self, ax, wd, norm=2):
ndupe = 1000
w = np.tile(wd, ndupe)
x = np.tile(wd, ndupe)
xb = wd
hRGB_raw, hXYZ_raw, bx = self.hist1d(w, x, xb, norm=norm)
hRGB_1d = np.clip(hRGB_raw, 0, 1)
ntile = 100
hRGB = np.tile(hRGB_1d, ntile ).reshape(-1,ntile,3)
extent = [0,2,bx[0],bx[-1]]
#interpolation = 'none'
#interpolation = 'mitchell'
#interpolation = 'hanning'
interpolation = 'gaussian'
ax.imshow(hRGB, origin="lower", extent=extent, alpha=1, vmin=0, vmax=1, aspect='auto', interpolation=interpolation)
ax.yaxis.set_visible(True)
ax.xaxis.set_visible(False)
def swatch_plot(self, wd, norm=2):
ndupe = 1000
w = np.tile(wd, ndupe)
hRGB_raw, hXYZ_raw, bx = self.hist0d(w, norm=norm)
hRGB_1d = np.clip(hRGB_raw, 0, 1)
ntile = 100
hRGB = np.tile(hRGB_1d, ntile ).reshape(-1,ntile,3)
extent = [0,2,0,1]
ax.imshow(hRGB, origin="lower", extent=extent, alpha=1, vmin=0, vmax=1, aspect='auto')
ax.yaxis.set_visible(True)
ax.xaxis.set_visible(False)
def cie_hist1d(w, x, xb, norm=1, colorspace="sRGB/D65", whitepoint=None):
c = CIE(colorspace, whitepoint=whitepoint)
return c.hist1d(w,x,xb,norm)
def cie_hist2d(w, x, y, xb, yb, norm=1, colorspace="sRGB/D65", whitepoint=None):
c = CIE(colorspace, whitepoint=whitepoint)
return c.hist2d(w,x,y,xb,yb,norm)
class Whitepoint(object):
def __init__(self, w):
"""
For spectra close to original (think perfect diffuse reflector)
this is expected to yield the characteristic of the illuminant.
XYZ values must be normalized as clearly simulating more photons
will give larger values...
The Yint is hoped to provide a less adhoc way of doing the
normalization.
"""
assert w is not None
X = np.sum(_cie.X(w))
Y = np.sum(_cie.Y(w))
Z = np.sum(_cie.Z(w))
Yint = Y
X /= Yint # normalize such that Y=1
Y /= Yint
Z /= Yint
x = X/(X+Y+Z) # Chromaticity coordinates
y = Y/(X+Y+Z)
self.wp = np.array([X,Y,Z,Yint,x,y])
def __repr__(self):
return str(self.wp)
def whitepoint(wd):
bb = _cie.BB6K(wd)
bb /= bb.max()
X = np.sum( _cie.X(wd)*bb )
Y = np.sum( _cie.Y(wd)*bb )
Z = np.sum( _cie.Z(wd)*bb )
norm = Y
# Normalize Y to 1
X /= norm
Y /= norm
Z /= norm
return [X,Y,Z], norm
def compare_norms(wdom):
"""
norm 0:X,1:Y
look almost identical
norm 2:Z, 3:X+Y+Z
also look the same
0,1 have better yellow and less of a murky gap between green and blue
"""
c = CIE()
nplot = 4
for i, norm in enumerate([0,1,2,3]):
ax = fig.add_subplot(1,nplot,i+1)
c.spectral_plot(ax, wdom, norm)
#ax = fig.add_subplot(1,nplot,2*i+2)
#c.swatch_plot(wd, norm)
if __name__ == '__main__':
pass
logging.basicConfig(level=logging.INFO)
plt.close()
plt.ion()
wdom = np.arange(350,720,20)
fig = plt.figure()
compare_norms(wdom)
plt.show()
wp = whitepoint(wdom)
|
GauthierBossuyt/Boogie | src/p5/acoustic/acoustic_string.js | const AMP_MULT = 50;
export default function acousticString(p5, freq, midpoint, length) {
this.freq = freq;
this.mid = midpoint;
this.length = length;
this.amp = 0;
this.isVibrating = false;
this.framesSincePluck = 0;
this.draw = () => {
p5.stroke(255, 45, 107);
if (!this.isVibrating) {
p5.line(this.mid.x + 50, 0, this.mid.x + 50, length);
} else {
p5.noFill();
p5.beginShape();
for (let x = 0; x < this.length; x++) {
const arc =
this.amp *
Math.sin((6.24 * x) / (this.length / 2)) *
Math.cos((6.24 * this.freq * this.framesSincePluck) / 60) *
AMP_MULT;
p5.vertex(this.mid.x + 50 + arc, this.mid.y - x);
}
p5.endShape();
}
};
this.update = () => {
if (this.isVibrating) {
this.amp *= 0.95;
this.framesSincePluck += 1;
if (this.amp < 0.05) {
this.isVibrating = false;
this.amp = 0;
this.framesSincePluck = 0;
}
}
};
this.pluck = () => {
this.isVibrating = true;
this.amp = 1;
this.framesSincePluck = 0;
};
}
|
SaurabhGujare/LawyerFinder | Assignment4/src/assignment_4/analytics/Analyzers/TopThreeProductsAnalyzer.java | <filename>Assignment4/src/assignment_4/analytics/Analyzers/TopThreeProductsAnalyzer.java<gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package assignment_4.analytics.Analyzers;
import assignment_4.entities.Order;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* @author <NAME> (NUID : 001472377)
*/
public class TopThreeProductsAnalyzer extends TopThreeAnalyzer{
@Override
protected Integer getID(Order order) {
return order.getItem().getProductId();
}
@Override
protected void displayAnalytics(Object result) {
List<Map.Entry<Integer, ArrayList>> rankMapList = new ArrayList<>(((Map) result).entrySet());
System.out.println("Top 3 Most Popular Products are");
for(int i=0;i < MAX_RECORDS && i < rankMapList.size();i++){
for(int prodId :(ArrayList<Integer>)rankMapList.get(rankMapList.size()-1-i).getValue()){
System.out.println(i+1+") Product Id: "+prodId+
" with Total Revenue: $"+rankMapList.get(rankMapList.size()-1-i).getKey());
}
}
}
}
|
elixir-no-nels/nels-core | nels-portal/src/main/java/no/nels/portal/model/IdpGridModel.java | <filename>nels-portal/src/main/java/no/nels/portal/model/IdpGridModel.java
package no.nels.portal.model;
import no.nels.commons.abstracts.ANumberId;
import no.nels.commons.model.NumberIndexedList;
import no.nels.idp.core.model.db.NeLSIdpUser;
import org.primefaces.model.SelectableDataModel;
import javax.faces.model.ListDataModel;
/**
* Created by Kidane on 27.05.2015.
*/
public class IdpGridModel extends ListDataModel<ANumberId> implements SelectableDataModel<NeLSIdpUser>{
private NumberIndexedList idps;
public IdpGridModel(NumberIndexedList idps){
super(idps);
this.idps = idps;
}
public NeLSIdpUser getRowData(String id){return (NeLSIdpUser)idps.getById(Long.parseLong(id));}
public Object getRowKey(NeLSIdpUser idp){return idp.getId();}
}
|
JouleCai/GeoSpaceLab | geospacelab/datahub/sources/gfz/hpo/nowcast/__init__.py | # Licensed under the BSD 3-Clause License
# Copyright (C) 2021 GeospaceLab (geospacelab)
# Author: <NAME>, Space Physics and Astronomy, University of Oulu
__author__ = "<NAME>"
__copyright__ = "Copyright 2021, GeospaceLab"
__license__ = "BSD-3-Clause License"
__email__ = "<EMAIL>"
__docformat__ = "reStructureText"
import datetime
import numpy as np
import geospacelab.datahub as datahub
from geospacelab.datahub import DatabaseModel, ProductModel
from geospacelab import preferences as prf
import geospacelab.toolbox.utilities.pydatetime as dttool
import geospacelab.toolbox.utilities.pybasic as basic
import geospacelab.toolbox.utilities.pylogging as mylog
from geospacelab.datahub.sources.gfz import gfz_database
from geospacelab.datahub.sources.gfz.hpo.loader import Loader as default_Loader
from geospacelab.datahub.sources.gfz.hpo.nowcast.downloader import Downloader as default_Downloader
import geospacelab.datahub.sources.gfz.hpo.variable_config as var_config
default_dataset_attrs = {
'database': gfz_database,
'product': 'Hpo-NOWCAST',
'data_file_ext': 'nc',
'data_root_dir': prf.datahub_data_root_dir / 'GFZ' / 'Indices',
'data_res': 30,
'allow_load': True,
'allow_download': True,
'force_download': False,
'data_search_recursive': False,
'label_fields': ['database', 'product', 'data_file_ext'],
'time_clip': True,
}
default_variable_names = ['DATETIME', 'Hp', 'ap']
# default_data_search_recursive = True
default_attrs_required = []
class Dataset(datahub.DatasetModel):
def __init__(self, **kwargs):
kwargs = basic.dict_set_default(kwargs, **default_dataset_attrs)
super().__init__(**kwargs)
self.database = kwargs.pop('database', gfz_database)
self.product = kwargs.pop('product', 'Hpo')
self.allow_download = kwargs.pop('allow_download', True)
self.force_download = kwargs.pop('force_download', True)
self.data_res = kwargs.pop('data_res', 30)
self.metadata = None
allow_load = kwargs.pop('allow_load', False)
# self.config(**kwargs)
if self.loader is None:
self.loader = default_Loader
if self.downloader is None:
self.downloader = default_Downloader
self._set_default_variables(
default_variable_names,
configured_variables=var_config.configured_variables
)
self._validate_attrs()
if allow_load:
self.load_data()
def _validate_attrs(self):
for attr_name in default_attrs_required:
attr = getattr(self, attr_name)
if not str(attr):
mylog.StreamLogger.warning("The parameter {} is required before loading data!".format(attr_name))
def label(self, **kwargs):
label = super().label()
return label
def load_data(self, **kwargs):
self.check_data_files(**kwargs)
for file_path in self.data_file_paths:
load_obj = self.loader(file_path, file_type=self.data_file_ext, data_res=self.data_res)
for var_name in self._variables.keys():
self._variables[var_name].join(load_obj.variables[var_name])
self._variables['Hp'].config(name=f'Hp{self.data_res}', label=f'Hp{self.data_res}')
import matplotlib.dates as mdates
self._variables['Hp'].visual.plot_config.bar['width'] = \
(mdates.date2num(datetime.datetime(2000, 1, 1,) + datetime.timedelta(minutes=self.data_res)) \
- mdates.date2num(datetime.datetime(2000, 1, 1))) * 0.9
self._variables['ap'].config(name=f'Hp{self.data_res}', label=f'ap{self.data_res}')
# self.select_beams(field_aligned=True)
if self.time_clip:
self.time_filter_by_range()
def search_data_files(self, **kwargs):
dt_fr = self.dt_fr
dt_to = self.dt_to
diff_years = dt_fr.year - dt_to.year
dt0 = datetime.datetime(dt_fr.year, 1, 1)
for i in range(diff_years + 1):
thisyear = datetime.datetime(dt0.year + i, 1, 1)
if datetime.date.today().year == thisyear.year:
self.force_download = True
initial_file_dir = kwargs.pop('initial_file_dir', None)
if initial_file_dir is None:
initial_file_dir = self.data_root_dir / 'Hpo' / f'Hp{self.data_res}'
file_patterns = [thisyear.strftime("%Y")]
# remove empty str
file_patterns = [pattern for pattern in file_patterns if str(pattern)]
search_pattern = '*' + '*'.join(file_patterns) + '*'
if not self.force_download:
done = super().search_data_files(
initial_file_dir=initial_file_dir, search_pattern=search_pattern
)
else:
done = False
# Validate file paths
if not done and self.allow_download:
done = self.download_data()
if done:
done = super().search_data_files(
initial_file_dir=initial_file_dir, search_pattern=search_pattern)
else:
print('Cannot find files from the online database!')
return done
def download_data(self):
if self.data_file_ext == 'nc':
download_obj = self.downloader(
data_res=self.data_res,
data_file_root_dir=self.data_root_dir, force=self.force_download)
else:
raise NotImplementedError
return download_obj.done
@property
def database(self):
return self._database
@database.setter
def database(self, value):
if isinstance(value, str):
self._database = DatabaseModel(value)
elif issubclass(value.__class__, DatabaseModel):
self._database = value
else:
raise TypeError
@property
def product(self):
return self._product
@product.setter
def product(self, value):
if isinstance(value, str):
self._product = ProductModel(value)
elif issubclass(value.__class__, ProductModel):
self._product = value
else:
raise TypeError
|
x1fa/Security-up | doter-common/src/main/java/com/doter/common/security/handler/RestAuthenticationEntryPoint.java | package com.doter.common.security.handler;
import cn.hutool.json.JSONUtil;
import com.doter.common.core.result.Result;
import com.doter.common.enums.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @ClassName AuthAuthenticationEntryPoint
* @Description 匿名用户访问无权限资源时的异常
* @Author HanTP
* @Date 2020/10/13 9:45
*/
@Component
@Slf4j
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e){
log.warn("【未知身份】:{ 业务编码 —— " + ResultStatus.USER_NOT_LOGIN.getCode() + " } —— { 异常信息 —— " + ResultStatus.USER_NOT_LOGIN.getMessage() + " }");
httpServletResponse.setContentType("application/json;charset=utf-8");
//200
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
try {
PrintWriter out = httpServletResponse.getWriter();
if (e instanceof CredentialsExpiredException) {
//账号过期
out.write(JSONUtil.toJsonStr(Result.failed(ResultStatus.USER_NOT_LOGIN,e.getMessage())));
}else {
//
out.write(JSONUtil.toJsonStr(Result.failed(ResultStatus.USER_NOT_LOGIN)));
}
out.flush();
out.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
|
janessasmith/MediaCube-SN | app/components/service/uploadAudioVideo/uploadAudioVideo.js | /*
上传音频视频工具
创建人:bai.zhiming
时间:2016-7-13
*/
"use strict";
angular.module("trsUploadAudioVideoModule", [])
.factory("uploadAudioVideoService", ["$q", "$http", "$sce", "globleParamsSet", "trsHttpService", function($q, $http, $sce, globleParamsSet, trsHttpService) {
var index = 0;
/**
* [uploadAndSubmit description:上传及提交发布]
* @param {[File]} file [description] 需要上传的文件
* @return {[null]} [description] null
*/
function uploadAndSubmit(fileArray) {
var defferUs = $q.defer();
var appendix = [];
var maxlength = fileArray.length;
upload(fileArray[0]).then(function(data) {
doRecursion(appendix, defferUs, data, maxlength, fileArray);
});
return defferUs.promise;
}
/**
* [doRecursion description:递归工具
*/
function doRecursion(appendix, defferUs, data, maxlength, fileArray) {
appendix.push(data);
index++;
if (index < maxlength) {
upload(fileArray[index]).then(function(data_) {
doRecursion(appendix, defferUs, data_, maxlength, fileArray);
});
} else {
index = 0;
defferUs.resolve(appendix);
}
}
/**
* [upload description:上传文件]
* @param {[File]} fd [description] 需要上传的文件
* @return {[null]} [description] null
*/
function upload(file) {
var fd = new FormData();
fd.append("uf", file);
var defferU = $q.defer();
$http({
method: "post",
url: trsHttpService.getMasUploadUrl(),
data: fd,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function(response) {
submit(response).then(function(data) {
defferU.resolve(data);
});
/*appendix.push(response);
index++;
if (index < maxlength) {
upload($scope.data.appendix[index]);
} else {
deffer.resolve();
}*/
}).error(function(response) {
});
return defferU.promise;
}
/**
* [submit description:提交发布]
* @param {[obj]} response [description] 需要提交发布的音视频
* @return {[null]} [description] null
*/
function submit(response) {
var defferS = $q.defer();
var params = {
token: <PASSWORD>.token,
appKey: trsHttpService.getMasConfig(),
isLightIntegrate: true,
title: encodeURI(response.originName)
};
trsHttpService.httpServer(trsHttpService.getMasSubmitUrl(), params, "post")
.then(function(data) {
defferS.resolve(data);
});
return defferS.promise;
}
return {
/**
* [uploadVoiceOrVideo description:上传音频或视频]
* @param {[File]数组} fileArray [description] File类型的数组,数组里只需一个元素
* @return {[string]} masid [description] masid 视频播放ID
*/
uploadVoiceOrVideo: function(fileArray) {
var deffer = $q.defer();
uploadAndSubmit(fileArray)
.then(function(data) {
deffer.resolve(data);
});
return deffer.promise;
},
/**
* [getPlayerById description:根据masid获取视频播放地址]
* @param {[string]} id [description] masid
* @return {[object]} [description] 视频播放信息,包括地址
*/
getPlayerById: function(id) {
var deffer = $q.defer();
var params = {
json: { masId: id, isLive: "false", player: "HTML5" }
};
trsHttpService.httpServer(trsHttpService.getMasPubUrl(), params, "get")
.then(function(data) {
if (angular.isUndefined(data.err)) {
data.streamsMap.l.httpURL = $sce.trustAsResourceUrl(data.streamsMap.l.httpURL);
}
deffer.resolve(data);
});
return deffer.promise;
},
download: function(id) {
window.open(trsHttpService.getMasDownloadUrl() + "&id=" + id);
},
submit: function(response) {
var defferS = $q.defer();
var params = {
token: response.token,
appKey: trsHttpService.getMasConfig(),
isLightIntegrate: true,
title: encodeURI(response.originName)
};
trsHttpService.httpServer(trsHttpService.getMasSubmitUrl(), params, "post")
.then(function(data) {
defferS.resolve(data);
});
return defferS.promise;
}
};
}]);
|
srinivas-kandula/integrations | adm/src/main/java/com/wavefront/rest/models/SortableSearchRequest.java | /*
* Wavefront REST API
* <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer <<API-TOKEN>>\" to your HTTP requests.</p>
*
* OpenAPI spec version: v2
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.wavefront.rest.models;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.wavefront.rest.models.SearchQuery;
import com.wavefront.rest.models.Sorting;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* SortableSearchRequest
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-02-25T16:34:08.557+05:30")
public class SortableSearchRequest {
@SerializedName("limit")
private Integer limit = null;
@SerializedName("offset")
private Integer offset = null;
@SerializedName("query")
private List<SearchQuery> query = null;
@SerializedName("sort")
private Sorting sort = null;
public SortableSearchRequest limit(Integer limit) {
this.limit = limit;
return this;
}
/**
* The number of results to return. Default: 100
*
* @return limit
**/
@ApiModelProperty(value = "The number of results to return. Default: 100")
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public SortableSearchRequest offset(Integer offset) {
this.offset = offset;
return this;
}
/**
* The number of results to skip before returning values. Default: 0
*
* @return offset
**/
@ApiModelProperty(value = "The number of results to skip before returning values. Default: 0")
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public SortableSearchRequest query(List<SearchQuery> query) {
this.query = query;
return this;
}
public SortableSearchRequest addQueryItem(SearchQuery queryItem) {
if (this.query == null) {
this.query = new ArrayList<SearchQuery>();
}
this.query.add(queryItem);
return this;
}
/**
* A list of queries by which to limit the search results. Entities that match ALL queries in the list are returned
*
* @return query
**/
@ApiModelProperty(value = "A list of queries by which to limit the search results. Entities that match ALL queries in the list are returned")
public List<SearchQuery> getQuery() {
return query;
}
public void setQuery(List<SearchQuery> query) {
this.query = query;
}
public SortableSearchRequest sort(Sorting sort) {
this.sort = sort;
return this;
}
/**
* Get sort
*
* @return sort
**/
@ApiModelProperty(value = "")
public Sorting getSort() {
return sort;
}
public void setSort(Sorting sort) {
this.sort = sort;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SortableSearchRequest sortableSearchRequest = (SortableSearchRequest) o;
return Objects.equals(this.limit, sortableSearchRequest.limit) &&
Objects.equals(this.offset, sortableSearchRequest.offset) &&
Objects.equals(this.query, sortableSearchRequest.query) &&
Objects.equals(this.sort, sortableSearchRequest.sort);
}
@Override
public int hashCode() {
return Objects.hash(limit, offset, query, sort);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SortableSearchRequest {\n");
sb.append(" limit: ").append(toIndentedString(limit)).append("\n");
sb.append(" offset: ").append(toIndentedString(offset)).append("\n");
sb.append(" query: ").append(toIndentedString(query)).append("\n");
sb.append(" sort: ").append(toIndentedString(sort)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
sbanal/jclif | src/main/java/org/jclif/annotation/Command.java | <filename>src/main/java/org/jclif/annotation/Command.java
/**
* 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.jclif.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Command annotation is used to mark a class that defines a command in a command line input.
* A command annotated class is a POJO class whose fields are either annotated with Parameter,
* Option and Handler to specify its options, parameters and the handler method.
*
* @author <NAME> <<EMAIL>>
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Command {
public static final String DEFAULT_COMMAND_IDENTIFIER = "-default-";
public String identifier() default DEFAULT_COMMAND_IDENTIFIER;
public String longIdentifier() default "";
public String description() default "";
public String longDescription() default "";
}
|
SunNy820828449/CINN | cinn/backends/codegen_c_x86.cc | // Copyright (c) 2021 CINN 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.
#include "cinn/backends/codegen_c_x86.h"
namespace cinn {
namespace backends {
void CodeGenCX86::Visit(const ir::Add *op) { VisitBinaryOp(op, op->a(), op->b(), "add"); }
void CodeGenCX86::Visit(const ir::Sub *op) { VisitBinaryOp(op, op->a(), op->b(), "sub"); }
void CodeGenCX86::Visit(const ir::Mul *op) { VisitBinaryOp(op, op->a(), op->b(), "mul"); }
void CodeGenCX86::Visit(const ir::Div *op) { VisitBinaryOp(op, op->a(), op->b(), "div"); }
void CodeGenCX86::Visit(const ir::Load *op) {
Expr dense_strided_ramp = detail::StridedRampBase(op->index(), 1);
if (dense_strided_ramp.defined()) { // Loading a continuous Ramp address.
CHECK(op->type().is_vector());
int bits = op->type().bits() * op->type().lanes();
if (SupportsAVX512() && bits == 512) {
os() << "cinn_avx512_load(";
PrintAbsAddr(op);
os() << ")";
} else if (SupportsAVX256() && bits == 256) {
os() << "cinn_avx256_load(";
PrintAbsAddr(op);
os() << ")";
} else {
CodeGenC::Visit(op);
}
} else {
CodeGenC::Visit(op);
}
}
void CodeGenCX86::Visit(const ir::Broadcast *op) {
CHECK_GT(op->type().lanes(), 1);
int bits = op->type().bits() * op->type().lanes();
if (SupportsAVX512() && bits == 512) {
os() << "cinn_avx512_set1(";
PrintCastExpr(op->value.type().ElementOf(), op->value);
os() << ")";
} else if (SupportsAVX256() && bits == 256) {
os() << "cinn_avx256_set1(";
PrintCastExpr(op->value.type().ElementOf(), op->value);
os() << ")";
} else {
CodeGenC::Visit(op);
}
}
void CodeGenCX86::Visit(const ir::Store *op) {
if (op->type().lanes() == 1) {
CodeGenC::Visit(op);
return;
}
int bits = op->type().bits() * op->type().lanes();
if (SupportsAVX512() && bits == 512) {
os() << "cinn_avx512_store(";
PrintAbsAddr(op);
os() << ", ";
Print(op->value);
os() << ")";
} else if (SupportsAVX256() && bits == 256) {
os() << "cinn_avx256_store(";
PrintAbsAddr(op);
os() << ", ";
Print(op->value);
os() << ")";
} else {
CodeGenC::Visit(op);
}
}
void CodeGenCX86::PrintVecInputArgument(const Expr *op) {
int bits = op->type().bits() * op->type().lanes();
auto *broadcast_n = op->As<ir::Broadcast>();
if (op->type().lanes() == 1 || broadcast_n) {
Expr value = op->type().lanes() == 1 ? *op : broadcast_n->value;
if (SupportsAVX512()) {
os() << "cinn_avx512_set1(";
Print(value);
os() << ")";
} else if (SupportsAVX256()) {
os() << "cinn_avx256_set1(";
Print(value);
os() << ")";
} else {
CINN_NOT_IMPLEMENTED
}
} else {
Print(*op);
}
}
void CodeGenCX86::Visit(const ir::intrinsics::BuiltinIntrin *op) {
if (op->type().lanes() == 1) {
CodeGenC::Visit(op);
return;
}
int bits = op->type().bits() * op->type().lanes();
if (SupportsAVX512() && bits == 512) {
os() << "cinn_avx512_" << op->name << "(";
if (!op->args.empty()) {
for (int i = 0; i < op->args.size() - 1; i++) {
PrintVecInputArgument(&op->args[i]);
os() << ", ";
}
Print(op->args.back());
}
os() << ")";
} else if (SupportsAVX256() && bits == 256) {
os() << "cinn_avx256_" << op->name << "(";
if (!op->args.empty()) {
for (int i = 0; i < op->args.size() - 1; i++) {
PrintVecInputArgument(&op->args[i]);
os() << ", ";
}
PrintVecInputArgument(&op->args.back());
}
os() << ")";
} else if (bits == 128) {
os() << "cinn_avx128_" << op->name << "(";
if (!op->args.empty()) {
for (int i = 0; i < op->args.size() - 1; i++) {
PrintVecInputArgument(&op->args[i]);
os() << ", ";
}
PrintVecInputArgument(&op->args.back());
}
os() << ")";
} else {
CodeGenC::Visit(op);
}
}
} // namespace backends
} // namespace cinn
|
hugorebelo/gitlabhq | app/policies/snippet_policy.rb | # frozen_string_literal: true
class SnippetPolicy < PersonalSnippetPolicy
end
|
negativelo/Coder-Essentials | Algorithm/java/src/main/java/wx/algorithm/op/backtracking/Sudoku.java | <filename>Algorithm/java/src/main/java/wx/algorithm/op/backtracking/Sudoku.java
package wx.algorithm.op.backtracking;
/**
* Created by apple on 16/8/14.
*/
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @function 数独
* @description 数独是一个我们都非常熟悉的经典游戏,运用计算机我们可以很快地解开数独难题,现在有一些简单的数独题目,请编写一个程序求解。
* @OJ http://www.nowcoder.com/practice/2b8fa028f136425a94e1a733e92f60dd?tpId=49&tqId=29298&rp=3&ru=/ta/2016test&qru=/ta/2016test/question-ranking
*/
public class Sudoku {
/**
* @param index 当前要处理的下标
* @param matrix 数据矩阵
* @param row 存放某一行中包含的所有数据
* @param column 存放某一列中包含的所有数据
* @return 如果已经搜索到最后一个, 则成功, 否则失败
* @function 每次迭代所需要处理的点
*/
public static boolean bps(int index, int[][] matrix, ArrayList<HashSet<Integer>> row, ArrayList<HashSet<Integer>> column, ArrayList<HashSet<Integer>> squ) {
if (index == 81) {
//已经搜索到
//打印矩阵
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if(j == 8){
System.out.print(matrix[i][j] + "");
}else {
System.out.print(matrix[i][j] + " ");
}
}
System.out.println();
}
return true;
}
//获取当前处理的点的坐标
int x = index / 9;
int y = index % 9;
int z = x / 3 * 3 + y / 3;
//判断当前点是否不为0
//如果不为0,则直接搜索下一层
if (matrix[x][y] != 0) {
if (bps(index + 1, matrix, row, column, squ)) {
return true;
}
return false;
} else {
//获取所有当前点的取值
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 1; i < 10; i++) {
//如果某个值还没有被包含
if (!row.get(x).contains(i) && !column.get(y).contains(i) && !squ.get(z).contains(i)) {
arrayList.add(i);
}
}
for (int i = 0; i < arrayList.size(); i++) {
//将当前处理点设置状态
matrix[x][y] = arrayList.get(i);
//将当前值加入到所在行列
row.get(x).add(arrayList.get(i));
column.get(y).add(arrayList.get(i));
squ.get(z).add(arrayList.get(i));
//搜索下一层
if (bps(index + 1, matrix, row, column,squ)) {
return true;
}
//进行回溯
//将当前处理点设置状态
matrix[x][y] = 0;
//将当前值加入到所在行列
row.get(x).remove(arrayList.get(i));
column.get(y).remove(arrayList.get(i));
squ.get(z).remove(arrayList.get(i));
}
return false;
}
}
/**
* 测试用例:
* 7 2 6 9 0 4 0 5 1
* 0 8 0 6 0 7 4 3 2
* 3 4 1 0 8 5 0 0 9
* 0 5 2 4 6 8 0 0 7
* 0 3 7 0 0 0 6 8 0
* 0 9 0 0 0 3 0 1 0
* 0 0 0 0 0 0 0 0 0
* 9 0 0 0 2 1 5 0 0
* 8 0 0 3 0 0 0 0 0
* <p>
* 对应输出应该为:
* <p>
* 7 2 6 9 3 4 8 5 1
* 5 8 9 6 1 7 4 3 2
* 3 4 1 2 8 5 7 6 9
* 1 5 2 4 6 8 3 9 7
* 4 3 7 1 9 2 6 8 5
* 6 9 8 5 7 3 2 1 4
* 2 1 5 8 4 6 9 7 3
* 9 6 3 7 2 1 5 4 8
* 8 7 4 3 5 9 1 2 6
* 测试用例:
* 0 9 5 0 2 0 0 6 0
* 0 0 7 1 0 3 9 0 2
* 6 0 0 0 0 5 3 0 4
* 0 4 0 0 1 0 6 0 7
* 5 0 0 2 0 7 0 0 9
* 7 0 3 0 9 0 0 2 0
* 0 0 9 8 0 0 0 0 6
* 8 0 6 3 0 2 1 0 5
* 0 5 0 0 7 0 2 8 3
* <p>
* 对应输出应该为:
* <p>
* 3 9 5 7 2 4 8 6 1
* 4 8 7 1 6 3 9 5 2
* 6 2 1 9 8 5 3 7 4
* 9 4 2 5 1 8 6 3 7
* 5 6 8 2 3 7 4 1 9
* 7 1 3 4 9 6 5 2 8
* 2 3 9 8 5 1 7 4 6
* 8 7 6 3 4 2 1 9 5
* 1 5 4 6 7 9 2 8 3
*
* @param args
*/
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
//存放每一行的数据
ArrayList<HashSet<Integer>> row = new ArrayList<HashSet<Integer>>();
//存放每一列的数据
ArrayList<HashSet<Integer>> column = new ArrayList<HashSet<Integer>>();
//存放对角线的数据
ArrayList<HashSet<Integer>> squ = new ArrayList<HashSet<Integer>>();
while (scanner.hasNext()) {
int[][] matrix = new int[9][9];
for (int i = 0; i < 9; i++) {
row.add(new HashSet<Integer>());
column.add(new HashSet<Integer>());
squ.add(new HashSet<Integer>());
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
int number = scanner.nextInt();
matrix[i][j] = number;
row.get(i).add(number);
column.get(j).add(number);
squ.get(i / 3 * 3 + j / 3).add(number);
}
}
bps(0, matrix, row, column, squ);
}
}
}
|
ihumphrey-usgs/ISIS3_old | isis/src/base/objs/EmbreeTargetShape/EmbreeTargetShape.cpp | <gh_stars>1-10
/**
* @file
* $Revision$
* $Date$
* $Id$
*
* Unless noted otherwise, the portions of Isis written by the USGS are
* public domain. See individual third-party library and package descriptions
* for intellectual property information, user agreements, and related
* information.
*
* Although Isis has been used by the USGS, no warranty, expressed or
* implied, is made by the USGS as to the accuracy and functioning of such
* software and related material nor shall the fact of distribution
* constitute any such warranty, and no responsibility is assumed by the
* USGS in connection therewith.
*
* For additional information, launch
* $ISISROOT/doc//documents/Disclaimers/Disclaimers.html
* in a browser or see the Privacy & Disclaimers page on the Isis website,
* http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
* http://www.usgs.gov/privacy.html.
*/
#include "EmbreeTargetShape.h"
#include <iostream>
#include <iomanip>
#include <numeric>
#include <sstream>
#include "NaifDskApi.h"
#include "FileName.h"
#include "IException.h"
#include "IString.h"
#include "NaifStatus.h"
#include "Pvl.h"
namespace Isis {
/**
* Default constructor for RTCMultiHitRay.
*/
RTCMultiHitRay::RTCMultiHitRay() {
tnear = 0.0;
tfar = std::numeric_limits<float>::infinity(); // Should be INF
mask = 0xFFFFFFFF;
lastHit = -1;
u = 0.0;
v = 0.0;
geomID = RTC_INVALID_GEOMETRY_ID;
primID = RTC_INVALID_GEOMETRY_ID;
instID = RTC_INVALID_GEOMETRY_ID;
org[0] = 0.0;
org[1] = 0.0;
org[2] = 0.0;
dir[0] = 0.0;
dir[1] = 0.0;
dir[2] = 0.0;
Ng[0] = 0.0;
Ng[1] = 0.0;
Ng[2] = 0.0;
}
/**
* Constructor for RTCMultiHitRay given a ray origin and look direction.
*
* @param origin The body-fixed (x, y, z) origin of the ray in kilometers.
* @param direction The unit look direction vector in body-fixed (x, y, z).
*/
RTCMultiHitRay::RTCMultiHitRay(const std::vector<double> &origin,
const std::vector<double> &direction) {
tnear = 0.0;
tfar = std::numeric_limits<float>::infinity(); // Should be INF
mask = 0xFFFFFFFF;
lastHit = -1;
u = 0.0;
v = 0.0;
geomID = RTC_INVALID_GEOMETRY_ID;
primID = RTC_INVALID_GEOMETRY_ID;
instID = RTC_INVALID_GEOMETRY_ID;
org[0] = origin[0];
org[1] = origin[1];
org[2] = origin[2];
dir[0] = direction[0];
dir[1] = direction[1];
dir[2] = direction[2];
Ng[0] = 0.0;
Ng[1] = 0.0;
Ng[2] = 0.0;
}
/**
* Constructor for RTCMultiHitRay given a ray origin and look direction as
* ISIS linear algebra vectors.
*
* @param origin The body-fixed (x, y, z) origin of the ray in kilometers.
* @param direction The unit look direction vector in body-fixed (x, y, z).
*/
RTCMultiHitRay::RTCMultiHitRay(LinearAlgebra::Vector origin,
LinearAlgebra::Vector direction) {
tnear = 0.0;
tfar = std::numeric_limits<float>::infinity(); // Should be INF
mask = 0xFFFFFFFF;
lastHit = -1;
u = 0.0;
v = 0.0;
geomID = RTC_INVALID_GEOMETRY_ID;
primID = RTC_INVALID_GEOMETRY_ID;
instID = RTC_INVALID_GEOMETRY_ID;
org[0] = origin[0];
org[1] = origin[1];
org[2] = origin[2];
dir[0] = direction[0];
dir[1] = direction[1];
dir[2] = direction[2];
Ng[0] = 0.0;
Ng[1] = 0.0;
Ng[2] = 0.0;
}
/**
* Default constructor for RTCOcclussionRay.
*/
RTCOcclusionRay::RTCOcclusionRay() {
tnear = 0.0;
tfar = std::numeric_limits<float>::infinity(); // Should be INF
mask = 0xFFFFFFFF;
lastHit = -1;
u = 0.0;
v = 0.0;
ignorePrimID = -1;
geomID = RTC_INVALID_GEOMETRY_ID;
primID = RTC_INVALID_GEOMETRY_ID;
instID = RTC_INVALID_GEOMETRY_ID;
org[0] = 0.0;
org[1] = 0.0;
org[2] = 0.0;
dir[0] = 0.0;
dir[1] = 0.0;
dir[2] = 0.0;
Ng[0] = 0.0;
Ng[1] = 0.0;
Ng[2] = 0.0;
}
/**
* Constructor for RTCOcclusionRay given a ray origin and look direction.
*
* @param origin The body-fixed (x, y, z) origin of the ray in kilometers.
* @param direction The unit look direction vector in body-fixed (x, y, z).
*/
RTCOcclusionRay::RTCOcclusionRay(const std::vector<double> &origin,
const std::vector<double> &direction) {
tnear = 0.0;
tfar = std::numeric_limits<float>::infinity(); // Should be INF
mask = 0xFFFFFFFF;
lastHit = -1;
u = 0.0;
v = 0.0;
geomID = RTC_INVALID_GEOMETRY_ID;
ignorePrimID = -1;
instID = RTC_INVALID_GEOMETRY_ID;
org[0] = origin[0];
org[1] = origin[1];
org[2] = origin[2];
dir[0] = direction[0];
dir[1] = direction[1];
dir[2] = direction[2];
Ng[0] = 0.0;
Ng[1] = 0.0;
Ng[2] = 0.0;
}
/**
* Constructor for RTCOcclusionRay given a ray origin and look direction as
* ISIS linear algebra vectors.
*
* @param origin The body-fixed (x, y, z) origin of the ray in kilometers.
* @param direction The unit look direction vector in body-fixed (x, y, z).
*/
RTCOcclusionRay::RTCOcclusionRay(LinearAlgebra::Vector origin,
LinearAlgebra::Vector direction) {
tnear = 0.0;
tfar = std::numeric_limits<float>::infinity(); // Should be INF
mask = 0xFFFFFFFF;
lastHit = -1;
u = 0.0;
v = 0.0;
geomID = RTC_INVALID_GEOMETRY_ID;
ignorePrimID = -1;
instID = RTC_INVALID_GEOMETRY_ID;
org[0] = origin[0];
org[1] = origin[1];
org[2] = origin[2];
dir[0] = direction[0];
dir[1] = direction[1];
dir[2] = direction[2];
Ng[0] = 0.0;
Ng[1] = 0.0;
Ng[2] = 0.0;
}
/**
* Default constructor for RayHitInformation
*/
RayHitInformation::RayHitInformation() {
intersection = LinearAlgebra::vector(0, 0, 0);
surfaceNormal = LinearAlgebra::vector(0, 0, 0);
primID = 0;
}
/**
* Constructor for RayHitInformation given an intersection and unit surface
* normal.
*
* @param location The body-fixed (x, y, z) location of the intersection in kilometers.
* @param normal The unit surface normal vector in body-fixed (x, y, z).
* @param primID The primitive ID
*/
RayHitInformation::RayHitInformation(LinearAlgebra::Vector &location,
LinearAlgebra::Vector &normal,
int prim)
: intersection(location),
surfaceNormal(normal) ,
primID(prim) { }
/**
* @brief Default empty constructor.
*
* The filename defaults to an empty string and the file handle defaults to 0.
* Counts default to 0 and the cache size defaults to 0.
*/
EmbreeTargetShape::EmbreeTargetShape()
: m_name(),
m_mesh(),
m_cloud(),
m_device(rtcNewDevice(NULL)),
m_scene(rtcDeviceNewScene(m_device,
RTC_SCENE_STATIC | RTC_SCENE_HIGH_QUALITY | RTC_SCENE_ROBUST,
RTC_INTERSECT1)) { }
/**
* Constructs an EmbreeTargetShape from a PointCloudLibrary polygon mesh.
*
* @param mesh The polygon mesh to construct the scene from.
* @param name The name of the target being represented.
*/
EmbreeTargetShape::EmbreeTargetShape(pcl::PolygonMesh::Ptr mesh, const QString &name)
: m_name(name),
m_mesh(),
m_cloud(),
m_device(rtcNewDevice(NULL)),
m_scene(rtcDeviceNewScene(m_device,
RTC_SCENE_STATIC | RTC_SCENE_HIGH_QUALITY | RTC_SCENE_ROBUST,
RTC_INTERSECT1)) {
initMesh(mesh);
}
/**
* Constructs an EmbreeTargetShape from a file.
*
* @param dem The file to construct the target shape from. The file type is determined
* based on the file extension.
* @param conf Pvl containing configuration settings for the target shape.
* Currently unused.
*
* @throws IException::Io
*/
EmbreeTargetShape::EmbreeTargetShape(const QString &dem, const Pvl *conf)
: m_name(),
m_mesh(),
m_cloud(),
m_device(rtcNewDevice(NULL)),
m_scene(rtcDeviceNewScene(m_device,
RTC_SCENE_STATIC | RTC_SCENE_HIGH_QUALITY | RTC_SCENE_ROBUST,
RTC_INTERSECT1)) {
FileName file(dem);
pcl::PolygonMesh::Ptr mesh;
m_name = file.baseName();
try {
// DEMs (ISIS cubes) TODO implement this
if (file.extension() == "cub") {
QString msg = "DEMs cannot be used to create an EmbreeTargetShape.";
throw IException(IException::Io, msg, _FILEINFO_);
}
// DSKs
else if (file.extension() == "bds") {
mesh = readDSK(file);
}
// Let PCL try to handle other formats (obj, ply, etc.)
else {
mesh = readPC(file);
}
}
catch (IException &e) {
QString msg = "Failed creating an EmbreeTargetShape from ["
+ file.expanded() + "].";
throw IException(e, IException::Io, msg, _FILEINFO_);
}
initMesh(mesh);
}
/**
* Read a NAIF type 2 DSK file into a PointCloudLibrary polygon mesh.
* The vertex and plate ordering in the DSK file is maintained in the polygon mesh.
*
* @param file The DSK file to load.
*
* @return @b pcl::PolygonMesh::Ptr A boost shared pointer to the mesh.
*
* @throws IException::User
* @throws IException::Io
*/
pcl::PolygonMesh::Ptr EmbreeTargetShape::readDSK(FileName file) {
/** NAIF DSK parameter setup */
SpiceInt dskHandle; //!< The DAS file handle of the DSK file.
SpiceDLADescr dlaDescriptor; /**< The DLA descriptor of the DSK segment representing the
target surface.*/
SpiceDSKDescr dskDescriptor; //!< The DSK descriptor.
SpiceInt numPlates; //!< Number of Plates in the model.
SpiceInt numVertices; //!< Number of vertices in the model.
// Sanity check
if ( !file.fileExists() ) {
QString mess = "NAIF DSK file [" + file.expanded() + "] does not exist.";
throw IException(IException::User, mess, _FILEINFO_);
}
// Open the NAIF Digital Shape Kernel (DSK)
dasopr_c( file.expanded().toLatin1().data(), &dskHandle );
NaifStatus::CheckErrors();
// Search to the first DLA segment
SpiceBoolean found;
dlabfs_c( dskHandle, &dlaDescriptor, &found );
NaifStatus::CheckErrors();
if ( !found ) {
QString mess = "No segments found in DSK file [" + file.expanded() + "]";
throw IException(IException::User, mess, _FILEINFO_);
}
dskgd_c( dskHandle, &dlaDescriptor, &dskDescriptor );
NaifStatus::CheckErrors();
// Get The number of polygons and vertices
dskz02_c( dskHandle, &dlaDescriptor, &numVertices, &numPlates );
NaifStatus::CheckErrors();
// Allocate polygon and vertices arrays
// These arrays are actually numVertices x 3 and numPlates x 3,
// this allocation is easier and produces needed memory layout for dskv02_c
// These arrays are very large, so they need to be heap allocated.
double *verticesArray = new double[numVertices * 3];
int *polygonsArray = new int[numPlates * 3];
// Read the vertices from the dsk file
SpiceInt numRead = 0;
dskv02_c(dskHandle, &dlaDescriptor, 1, numVertices,
&numRead, ( SpiceDouble(*)[3] )(verticesArray) );
NaifStatus::CheckErrors();
if ( numRead != numVertices ) {
QString msg = "Failed reading all vertices from the DSK file, ["
+ toString(numRead) + "] out of ["
+ toString(numVertices) + "] vertices read.";
throw IException(IException::Io, msg, _FILEINFO_);
}
// Read the polygons from the DSK
numRead = 0;
dskp02_c(dskHandle, &dlaDescriptor, 1, numPlates,
&numRead, ( SpiceInt(*)[3] )(polygonsArray) );
NaifStatus::CheckErrors();
if ( numRead != numPlates ) {
QString msg = "Failed reading all polygons from the DSK file, ["
+ toString(numRead) + "] out of ["
+ toString(numPlates) + "] polygons read.";
throw IException(IException::Io, msg, _FILEINFO_);
}
// Store the vertices in a point cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
for (int vertexIndex = 0; vertexIndex < numVertices; ++vertexIndex) {
cloud->push_back(pcl::PointXYZ(verticesArray[vertexIndex * 3],
verticesArray[vertexIndex * 3 + 1],
verticesArray[vertexIndex * 3 + 2]));
}
// Store the polygons as a vector of vertices
std::vector<pcl::Vertices> polygons;
for (int plateIndex = 0; plateIndex < numPlates; ++plateIndex) {
pcl::Vertices vertexIndices;
// NAIF uses 1 based indexing for the vertices, so subtract 1
vertexIndices.vertices.push_back(polygonsArray[plateIndex * 3] - 1);
vertexIndices.vertices.push_back(polygonsArray[plateIndex * 3 + 1] - 1);
vertexIndices.vertices.push_back(polygonsArray[plateIndex * 3 + 2] - 1);
polygons.push_back(vertexIndices);
}
// Create the mesh
pcl::PolygonMesh::Ptr mesh(new pcl::PolygonMesh);
mesh->polygons = polygons;
pcl::PCLPointCloud2::Ptr cloudBlob(new pcl::PCLPointCloud2);
pcl::toPCLPointCloud2(*cloud, *cloudBlob);
mesh->cloud = *cloudBlob;
// Free the vectors used to read the vertices and polygons
delete [] verticesArray;
delete [] polygonsArray;
return mesh;
}
/**
* Read a PointCloudLibrary file into a PointCloudLibrary polygon mesh.
*
* @param file The PointCloudLibrary file to load.
*
* @return @b pcl::PolygonMesh::Ptr A boost shared pointer to the mesh.
*
* @throws IException::Io
*/
pcl::PolygonMesh::Ptr EmbreeTargetShape::readPC(FileName file) {
pcl::PolygonMesh::Ptr mesh( new pcl::PolygonMesh );
int loadStatus = pcl::io::load(file.expanded().toStdString(), *mesh);
if (loadStatus == -1) {
QString msg = "Failed loading target shape file [" + file.expanded() + "]";
throw IException(IException::Io, msg, _FILEINFO_);
}
return mesh;
}
/**
* Internalize a PointCloudLibrary polygon mesh in the target shape. The mesh
* itself is stored along with a duplicate of the vertex point cloud because
* the point cloud stored in the polygon mesh cannot be read without
* Robot Operating System routines. The mesh is loaded into the internal
* Embree scene and the scene is commited. Any changes made to the Embree
* scene after this method is called will not take effect until
* embree::rtcCommit is called again.
*
* @note This method is NOT reentrant. Calling this again with a new mesh
* will remove the PointCloudLibrary representation of the old mesh
* but the Embree scene will contain all previous meshes along with
* the new mesh. Use embree::rtcDeleteGeometry to remove an old mesh
* from the scene.
*
* @param mesh The mesh to be internalized.
*/
void EmbreeTargetShape::initMesh(pcl::PolygonMesh::Ptr mesh) {
m_mesh = mesh;
// The points are stored in a pcl::PCLPointCloud2 object that we cannot used.
// So, convert them into a pcl::PointCloud<pcl::PointXYZ> object that we can use.
pcl::fromPCLPointCloud2(mesh->cloud, m_cloud);
// Create a static geometry (the body) in our scene
unsigned geomID = rtcNewTriangleMesh(m_scene,
RTC_GEOMETRY_STATIC,
numberOfPolygons(),
numberOfVertices(),
1);
// Add vertices and faces (indices)
addVertices(geomID); // add cloud of points
addIndices(geomID); // connect dots of cloud into triangles
// Add the multi-hit filter
rtcSetIntersectionFilterFunction(m_scene, geomID,
(RTCFilterFunc)&EmbreeTargetShape::multiHitFilter);
// Add the occlusion filter
rtcSetOcclusionFilterFunction(m_scene, geomID,
(RTCFilterFunc)&EmbreeTargetShape::occlusionFilter);
// Done, now we can perform some ray tracing
rtcCommit(m_scene);
}
/**
* Adds the vertices from the internalized vertex point cloud to the Embree
* scene.
*
* @param geomID The Embree geometry ID of the Embree geometry that the
* vertices will be stored in.
*
* @see EmbreeTargetShape::initMesh
*/
void EmbreeTargetShape::addVertices(int geomID) {
if (!isValid()) {
return;
}
// Add the body's vertices to the Embree ray tracing device's vertex buffer
Vertex *vertices = (Vertex *) rtcMapBuffer(m_scene, geomID, RTC_VERTEX_BUFFER);
for (int v = 0; v < numberOfVertices(); ++v) {
vertices[v].x = m_cloud.points[v].x;
vertices[v].y = m_cloud.points[v].y;
vertices[v].z = m_cloud.points[v].z;
}
// Flush buffer
rtcUnmapBuffer(m_scene, geomID, RTC_VERTEX_BUFFER);
}
/**
* Adds the polygon vertex indices from the internalized polygon mesh to the
* Embree scene.
*
* @param geomID The Embree geometry ID of the Embree geometry that the
* indices will be stored in.
*
* @see EmbreeTargetShape::initMesh
*/
void EmbreeTargetShape::addIndices(int geomID) {
if (!isValid()) {
return;
}
// Add the body's face (vertex indices) to the Embree device's index buffer
Triangle *triangles = (Triangle *) rtcMapBuffer(m_scene, geomID, RTC_INDEX_BUFFER);
for (int t = 0; t < numberOfPolygons(); ++t) {
triangles[t].v0 = m_mesh->polygons[t].vertices[0];
triangles[t].v1 = m_mesh->polygons[t].vertices[1];
triangles[t].v2 = m_mesh->polygons[t].vertices[2];
}
// Flush buffer
rtcUnmapBuffer(m_scene, geomID, RTC_INDEX_BUFFER);
}
/**
* Desctructor. The PointCloudLibrary objects are automatically cleaned up,
* but the Embree scene and device must be manually cleaned up.
*/
EmbreeTargetShape::~EmbreeTargetShape() {
rtcDeleteScene(m_scene);
rtcDeleteDevice(m_device);
}
/**
* Return the number of polygons in the target shape.
*
* @return @b int The number of polygons in the polygon mesh representation
* of the target.
*/
int EmbreeTargetShape::numberOfPolygons() const {
if (isValid()) {
return m_mesh->polygons.size();
}
return 0;
}
/**
* Return the number of vertices in the target shape.
*
* @return @b int The number of vertices in the polygon mesh representation
* of the target.
*/
int EmbreeTargetShape::numberOfVertices() const {
if (isValid()) {
return m_mesh->cloud.height * m_mesh->cloud.width;
}
return 0;
}
/**
* Returns the bounds of the Embree scene. If the scene has not been
* initialized, then all bounds are returned as 0.0.
*
* @return @b RTCBounds Struct containing the upper and lower bounds on each
* dimension of the scene. Bounds are stored as floats
* in lower_x, upper_x, lower_y, upper_y, lower_z, and
* upper_z.
*
*/
RTCBounds EmbreeTargetShape::sceneBounds() const {
RTCBounds sceneBounds;
if (isValid()) {
rtcGetBounds(m_scene, sceneBounds);
}
else {
sceneBounds.lower_x = 0.0;
sceneBounds.lower_y = 0.0;
sceneBounds.lower_z = 0.0;
sceneBounds.upper_x = 0.0;
sceneBounds.upper_y = 0.0;
sceneBounds.upper_z = 0.0;
}
return sceneBounds;
}
/**
* Return the maximum distance within the scene. This is computed as the
* length of the diagonal from once corner of the scene to the opposite.
*
* @return @b double The maximum distance within the Embree scene in kilometers.
*/
double EmbreeTargetShape::maximumSceneDistance() const {
RTCBounds sceneBoundary = sceneBounds();
LinearAlgebra::Vector diagonal(3);
diagonal[0] = sceneBoundary.upper_x - sceneBoundary.lower_x;
diagonal[1] = sceneBoundary.upper_y - sceneBoundary.lower_y;
diagonal[2] = sceneBoundary.upper_z - sceneBoundary.lower_z;
return LinearAlgebra::magnitude(diagonal);
}
/**
* Intersect a ray with the target shape. After calling, up to 16
* intersections will be stored within the RTCMultiHitRay. The intersection
* information will be stored in the following arrays:
* <ul>
* <li> <b>hitGeomIDs:</b>
* The Embree Geometry ID of the intersected geometry </li>
* <li> <b>hitPrimIDs:</b>
* The index of the intersected polygon </li>
* <li> <b>hitUs:</b>
* The Barycentric u coordinate of the intersection relative to the
* intersected polygon </li>
* <li> <b>hitVs:</b>
* The Barycentric V coordinate of the intersection relative to the
* intersected polygon </li>
* </ul>
* The index of the last intersection is stored in <b>lastHit</b>.
*
* @note The intersection information is stored in the order that Embree
* finds them. This is not necessarily their order along the ray. Only
* the first intersection is guaranteed to be in the correct order.
* Other intersections may be swapped with the next, or previous,
* intersection relative to their order along the ray.
*
* @param[in,out] ray The ray to intersect with the scene. After calling, The
* intersection information will be stored in the ray.
*
* @see embree::rtcIntersect
*/
void EmbreeTargetShape::intersectRay(RTCMultiHitRay &ray) {
if (isValid()) {
rtcIntersect(m_scene, *((RTCRay*)&ray));
}
}
/**
* Check if a ray intersects the target body.
*
* @return @b bool If the ray intersects anything.
*
* @see embree::rtcOccluded
*/
bool EmbreeTargetShape::isOccluded(RTCOcclusionRay &ray) {
rtcOccluded(m_scene, ray);
// rtcOccluded sets the geomID to 0 if the ray hits anything
if (ray.geomID == 0) {
return true;
}
return false;
}
/**
* Extract the intersection point and unit surface normal from an
* RTCMultiHitRay that has been intersected with the target shape. This
* method performs two calculations. First, it converts the intersection
* point from barycentric coordinates relative to the intersected polygon to
* the body-fixed (x, y, z) coordinates. Second, it computes the unit normal
* vector of the intersected polygon. The polygon vertices are assumed to be
* ordered counter-clockwise about the exterior surface normal as they are in
* NAIF type 2 DSK files.
*
* @param ray The ray to extract intersection information from.
* @param hitIndex The index of the intersection to extract.
*
* @return @b RayHitInformation The body-fixed intersection coordinate in
* kilometers and the unit surface normal at the
* intersection.
*
* @throws IException::Programmer
*/
RayHitInformation EmbreeTargetShape::getHitInformation(RTCMultiHitRay &ray, int hitIndex) {
if (hitIndex > ray.lastHit || hitIndex < 0) {
QString msg = "Hit index [" + toString(hitIndex) + "] is out of bounds.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
// Get the vertices of the triangle hit
pcl::PointXYZ v0 = m_cloud.points[m_mesh->polygons[ray.hitPrimIDs[hitIndex]].vertices[0]];
pcl::PointXYZ v1 = m_cloud.points[m_mesh->polygons[ray.hitPrimIDs[hitIndex]].vertices[1]];
pcl::PointXYZ v2 = m_cloud.points[m_mesh->polygons[ray.hitPrimIDs[hitIndex]].vertices[2]];
// The intersection location comes out in barycentric coordinates, (u, v, w).
// Only u and v are returned because u + v + w = 1. If the coordinates of the
// triangle vertices are v0, v1, and v2, then the cartesian coordinates are:
// w*v0 + u*v1 + v*v2
float u = ray.hitUs[hitIndex];
float v = ray.hitVs[hitIndex];
float w = 1.0 - u - v;
LinearAlgebra::Vector intersection(3);
intersection[0] = w*v0.x + v*v1.x + u*v2.x;
intersection[1] = w*v0.y + v*v1.y + u*v2.y;
intersection[2] = w*v0.z + v*v1.z + u*v2.z;
// Calculate the normal vector as (v1 - v0) x (v2 - v0) and normalize it
// TODO This calculation assumes that the shape conforms to the NAIF dsk standard
// of the plate vertices being ordered counterclockwise about the normal.
// Check if this is true for other file types and/or make a more generic process
LinearAlgebra::Vector surfaceNormal(3);
surfaceNormal[0] = (v1.y - v0.y) * (v2.z - v0.z)
- (v1.z - v0.z) * (v2.y - v0.y);
surfaceNormal[1] = (v1.z - v0.z) * (v2.x - v0.x)
- (v1.x - v0.x) * (v2.z - v0.z);
surfaceNormal[2] = (v1.x - v0.x) * (v2.y - v0.y)
- (v1.y - v0.y) * (v2.x - v0.x);
// The surface normal is not normalized so normalize it.
surfaceNormal = LinearAlgebra::normalize(surfaceNormal);
return RayHitInformation(intersection, surfaceNormal, ray.hitPrimIDs[hitIndex]);
}
/**
* Return the name of the target shape.
*
* @return @b QString The name of the target.
*/
QString EmbreeTargetShape::name() const {
return ( m_name );
}
/**
* Return if a valid mesh is internalized and ready for use.
*
* @return @b bool If a mesh is internalized and the Embree scene is ready.
*/
bool EmbreeTargetShape::isValid() const {
return m_mesh.get();
}
/**
* Filter function for collecting multiple hits during ray intersection.
* This function is called by the Embree library during ray tracing. Each
* time an intersection is found, this method is called.
*
* @param[in] userDataPtr Data pointer from the geometry hit. Not used.
* @param[in,out] ray The ray being traced. Information about the
* intersection will be stored in the ray.
*/
void EmbreeTargetShape::multiHitFilter(void* userDataPtr, RTCMultiHitRay& ray) {
// Calculate the index to store the hit in
ray.lastHit ++;
// Store the hits
ray.hitGeomIDs[ray.lastHit] = ray.geomID;
ray.hitPrimIDs[ray.lastHit] = ray.primID;
ray.hitUs[ray.lastHit] = ray.u;
ray.hitVs[ray.lastHit] = ray.v;
// If there are less than 16 hits, continue ray tracing.
if (ray.lastHit < 15) {
ray.geomID = RTC_INVALID_GEOMETRY_ID;
}
}
/**
* Filter function for collecting multiple primitiveIDs
* This function is called by the Embree library during ray tracing. Each
* time an intersection is found, this method is called.
*
* @param[in] userDataPtr Data pointer from the geometry hit. Not used.
* @param[in,out] ray The ray being traced. Information about the
* intersection will be stored in the ray.
*/
void EmbreeTargetShape::occlusionFilter(void* userDataPtr, RTCOcclusionRay& ray) {
// This is the case where we've re-intersected the occluded plate. If this happens, ignore
// and keep tracing
if ( ray.primID == ray.ignorePrimID) {
ray.geomID = RTC_INVALID_GEOMETRY_ID;
}
}
} // namespace Isis
|
felixjones/gba-plusplus | include/gba/types/screen_tile.hpp | #ifndef GBAXX_TYPES_SCREEN_TILE_HPP
#define GBAXX_TYPES_SCREEN_TILE_HPP
#include <gba/types/int_type.hpp>
namespace gba {
enum class tile_flip : uint8 {
none = 0,
horizontal = 1,
vertical = 2,
both = 3
};
struct screen_tile {
uint16 tile_index : 10;
tile_flip flip : 2;
uint16 palette_bank : 4;
};
static_assert( sizeof( screen_tile ) == 2, "screen_tile must be tightly packed" );
} // gba
#endif // define GBAXX_TYPES_SCREEN_TILE_HPP
|
zhaozexin/kissy | build/core/core-pkg-min.js | <gh_stars>0
/*
Copyright 2011, KISSY UI Library v1.20dev
MIT Licensed
build time: ${build.time}
*/
KISSY.add("core",function(d,b,e,f,c,h,a,g,i,j){a.getScript=d.getScript;b={UA:b,DOM:e,Event:f,EventTarget:f.Target,Node:c,NodeList:c.List,JSON:h,Ajax:a,IO:a,ajax:a,io:a,jsonp:a.jsonp,Anim:g,Easing:g.Easing,Base:i,Cookie:j,one:c.one,all:c.List.all,get:e.get,query:e.query};d.mix(d,b);return b},{requires:["ua","dom","event","node","json","ajax","anim","base","cookie"]});
|
ryanberryhill/iimc | src/copt/AIGUtil.cpp | /********************************************************************
Copyright (c) 2010-2015, Regents of the University of Colorado
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 University of Colorado nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
********************************************************************/
#include "AIGUtil.h"
using namespace std;
namespace {
using namespace Opt;
vector<ID> or2(ID l1, ID l2) {
vector<ID> lits;
lits.push_back(l1);
lits.push_back(l2);
return lits;
}
ID rep(NodeRef ref, Expr::Manager::View& v, RefIDMap* satIdOfRef) {
ostringstream buf;
buf << "r" << ref;
ID newId = v.newVar(buf.str());
if(satIdOfRef != NULL) {
satIdOfRef->insert(RefIDMap::value_type(ref, newId));
}
return newId;
}
}
namespace Opt {
ID buildClauses(const AIG& aig, NodeRef ref, Expr::Manager::View& v,
vector<vector<ID> >& clauses, const RefIDMap& idOfAigRef, RefIDMap* satIdOfRef,
vector<pair<bool, ID> >& visited) {
if(ref == 0)
return v.bfalse();
if(ref == 1)
return v.btrue();
if(isNot(ref))
return v.apply(Expr::Not, buildClauses(aig, invert(ref), v, clauses, idOfAigRef, satIdOfRef, visited));
if(visited[UIGET(indexOf(ref))].first)
return visited[UIGET(indexOf(ref))].second;
if(aig[indexOf(ref)].isVar()) {
assert(idOfAigRef.find(ref) != idOfAigRef.end());
if(satIdOfRef != NULL) {
satIdOfRef->insert(RefIDMap::value_type(ref, idOfAigRef.find(ref)->second));
}
return idOfAigRef.find(ref)->second;
}
ID r = rep(ref, v, satIdOfRef);
visited[UIGET(indexOf(ref))].first = true;
visited[UIGET(indexOf(ref))].second = r;
ID nr = v.apply(Expr::Not, r);
vector<ID> lits;
NodeRef fanin1 = aig[indexOf(ref)][0];
ID fanin1ID = buildClauses(aig, fanin1, v, clauses, idOfAigRef, satIdOfRef, visited);
clauses.push_back(or2(nr, fanin1ID));
lits.push_back(v.apply(Expr::Not, fanin1ID));
NodeRef fanin2 = aig[indexOf(ref)][1];
ID fanin2ID = buildClauses(aig, fanin2, v, clauses, idOfAigRef, satIdOfRef, visited);
clauses.push_back(or2(nr, fanin2ID));
lits.push_back(v.apply(Expr::Not, fanin2ID));
lits.push_back(r);
clauses.push_back(lits);
return r;
}
ID tseitin(const AIG& aig, NodeRef ref, Expr::Manager::View& v, vector<vector<ID> >& clauses,
const RefIDMap& idOfAigRef, RefIDMap* satIdOfRef, bool assert_roots) {
vector<pair<bool, ID> > visited(aig.size(), pair<bool, ID>(false, 0));
if(satIdOfRef != NULL) {
satIdOfRef->insert(RefIDMap::value_type(0, v.bfalse()));
}
ID root = buildClauses(aig, ref, v, clauses, idOfAigRef, satIdOfRef, visited);
if(assert_roots) {
clauses.push_back(vector<ID>(1, root));
}
return root;
}
vector<ID> tseitin(const AIG& aig, const vector<NodeRef>& refs, Expr::Manager::View& v,
vector<vector<ID> >& clauses, const RefIDMap& idOfAigRef, RefIDMap* satIdOfRef,
bool assert_roots) {
vector<pair<bool, ID> > visited(aig.size(), pair<bool, ID>(false, 0));
if(satIdOfRef != NULL) {
satIdOfRef->insert(RefIDMap::value_type(0, v.bfalse()));
}
vector<ID> retIds;
for(unsigned i = 0; i < refs.size(); ++i) {
ID root = buildClauses(aig, refs[i], v, clauses, idOfAigRef, satIdOfRef, visited);
if(assert_roots) {
clauses.push_back(vector<ID>(1, root));
}
retIds.push_back(root);
}
return retIds;
}
void countNodes(const AIG& aig, NodeRef ref, unsigned& count, vector<char>& visited) {
if(isNot(ref))
countNodes(aig, invert(ref), count, visited);
NodeIndex index = indexOf(ref);
if(visited[UIGET(index)] == 1)
return;
++count;
visited[UIGET(index)] = 1;
if(index == 0 || aig[index].isVar()) {
return;
}
NodeRef fanin1 = aig[index][0];
countNodes(aig, fanin1, count, visited);
NodeRef fanin2 = aig[index][1];
countNodes(aig, fanin2, count, visited);
}
unsigned sizeOf(const AIG& aig, NodeRef ref) {
vector<char> visited(aig.size(), 0);
unsigned count = 0;
countNodes(aig, ref, count, visited);
return count;
}
unsigned sizeOf(const AIG& aig, vector<NodeRef>& refs) {
vector<char> visited(aig.size(), 0);
unsigned total = 0;
for(unsigned i = 0; i < refs.size(); ++i) {
countNodes(aig, refs[i], total, visited);
}
return total;
}
unsigned nodeCount(const AIG& aig) {
unsigned numNodes = 0;
vector<NodeRef> all = aig.nextStateFnRefs();
all.insert(all.end(), aig.outputFnRefs().begin(), aig.outputFnRefs().end());
numNodes += sizeOf(aig, all);
return numNodes;
}
void nodeDepth(const AIG &aig, NodeIndex index, vector<unsigned> &depth, vector<char> &seen)
{
if (seen[UIGET(index)] == 1) return;
if (aig[index].isVar() || index == 0) return;
NodeIndex i0 = indexOf(aig[index][0]), i1 = indexOf(aig[index][1]);
depth[UIGET(i0)] = max(depth[UIGET(i0)], depth[UIGET(index)]+1);
depth[UIGET(i1)] = max(depth[UIGET(i1)], depth[UIGET(index)]+1);
nodeDepth(aig, i0, depth, seen);
nodeDepth(aig, i1, depth, seen);
seen[UIGET(index)] = 1;
}
void countDepth(const AIG &aig, std::vector<unsigned> &depth)
{
vector<char> seen(aig.size(), 0);
depth.assign(aig.size(), 0);
for (vector<NodeRef>::const_iterator i = aig.outputFnRefs().begin(); i != aig.outputFnRefs().end(); ++i)
nodeDepth(aig, indexOf(*i), depth, seen);
for (vector<NodeRef>::const_iterator i = aig.nextStateFnRefs().begin(); i != aig.nextStateFnRefs().end(); ++i)
nodeDepth(aig, indexOf(*i), depth, seen);
}
}
|
amphiaraus/AndroidChromium | app/src/main/java/org/chromium/chrome/browser/webapps/WebappDataStorage.java | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.webapps;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import org.chromium.base.ThreadUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.ShortcutHelper;
import java.util.Map;
/**
* Stores data about an installed web app. Uses SharedPreferences to persist the data to disk.
* Before this class is used, the web app must be registered in {@link WebappRegistry}.
*
* EXAMPLE USAGE:
*
* (1) UPDATING/RETRIEVING THE ICON (web app MUST have been registered in WebappRegistry)
* WebappDataStorage storage = WebappDataStorage.open(context, id);
* storage.updateSplashScreenImage(bitmap);
* storage.getSplashScreenImage(callback);
*/
public class WebappDataStorage {
static final String SHARED_PREFS_FILE_PREFIX = "webapp_";
static final String KEY_SPLASH_ICON = "splash_icon";
static final String KEY_LAST_USED = "last_used";
static final long INVALID_LAST_USED = -1;
private static Factory sFactory = new Factory();
private final SharedPreferences mPreferences;
/**
* Opens an instance of WebappDataStorage for the web app specified.
* @param context The context to open the SharedPreferences.
* @param webappId The ID of the web app which is being opened.
*/
public static WebappDataStorage open(final Context context, final String webappId) {
final WebappDataStorage storage = sFactory.create(context, webappId);
new AsyncTask<Void, Void, Void>() {
@Override
protected final Void doInBackground(Void... nothing) {
if (storage.getLastUsedTime() == INVALID_LAST_USED) {
// If the last used time is invalid then assert that there is no data
// in the WebappDataStorage which needs to be cleaned up.
assert storage.getAllData().isEmpty();
} else {
storage.updateLastUsedTime();
}
return null;
}
}.execute();
return storage;
}
/**
* Asynchronously retrieves the time which this WebappDataStorage was last
* opened using {@link WebappDataStorage#open(Context, String)}.
* @param context The context to read the SharedPreferences file.
* @param webappId The ID of the web app the used time is being read for.
* @param callback Called when the last used time has been retrieved.
*/
public static void getLastUsedTime(final Context context, final String webappId,
final FetchCallback<Long> callback) {
new AsyncTask<Void, Void, Long>() {
@Override
protected final Long doInBackground(Void... nothing) {
long lastUsed = new WebappDataStorage(context.getApplicationContext(), webappId)
.getLastUsedTime();
assert lastUsed != INVALID_LAST_USED;
return lastUsed;
}
@Override
protected final void onPostExecute(Long lastUsed) {
callback.onDataRetrieved(lastUsed);
}
}.execute();
}
/**
* Deletes the data for a web app by clearing all the information inside the SharedPreferences
* file. This does NOT delete the file itself but the file is left empty.
* @param context The context to read the SharedPreferences file.
* @param webappId The ID of the web app being deleted.
*/
static void deleteDataForWebapp(final Context context, final String webappId) {
assert !ThreadUtils.runningOnUiThread();
openSharedPreferences(context, webappId).edit().clear().commit();
}
/**
* Sets the factory used to generate WebappDataStorage objects.
*/
@VisibleForTesting
public static void setFactoryForTests(Factory factory) {
sFactory = factory;
}
private static SharedPreferences openSharedPreferences(Context context, String webappId) {
return context.getApplicationContext().getSharedPreferences(
SHARED_PREFS_FILE_PREFIX + webappId, Context.MODE_PRIVATE);
}
protected WebappDataStorage(Context context, String webappId) {
mPreferences = openSharedPreferences(context, webappId);
}
/*
* Asynchronously retrieves the splash screen image associated with the
* current web app.
* @param callback Called when the splash screen image has been retrieved.
* May be null if no image was found.
*/
public void getSplashScreenImage(FetchCallback<Bitmap> callback) {
new BitmapFetchTask(KEY_SPLASH_ICON, callback).execute();
}
/*
* Update the information associated with the web app with the specified data.
* @param splashScreenImage The image which should be shown on the splash screen of the web app.
*/
public void updateSplashScreenImage(Bitmap splashScreenImage) {
new UpdateTask(splashScreenImage).execute();
}
void updateLastUsedTime() {
assert !ThreadUtils.runningOnUiThread();
mPreferences.edit().putLong(KEY_LAST_USED, System.currentTimeMillis()).commit();
}
long getLastUsedTime() {
assert !ThreadUtils.runningOnUiThread();
return mPreferences.getLong(KEY_LAST_USED, INVALID_LAST_USED);
}
private Map<String, ?> getAllData() {
return mPreferences.getAll();
}
/**
* Called after data has been retrieved from storage.
*/
public interface FetchCallback<T> {
public void onDataRetrieved(T readObject);
}
/**
* Factory used to generate WebappDataStorage objects.
*
* It is used in tests to override methods in WebappDataStorage and inject the mocked objects.
*/
public static class Factory {
/**
* Generates a WebappDataStorage class for a specified web app.
*/
public WebappDataStorage create(final Context context, final String webappId) {
return new WebappDataStorage(context, webappId);
}
}
private final class BitmapFetchTask extends AsyncTask<Void, Void, Bitmap> {
private final String mKey;
private final FetchCallback<Bitmap> mCallback;
public BitmapFetchTask(String key, FetchCallback<Bitmap> callback) {
mKey = key;
mCallback = callback;
}
@Override
protected final Bitmap doInBackground(Void... nothing) {
return ShortcutHelper.decodeBitmapFromString(mPreferences.getString(mKey, null));
}
@Override
protected final void onPostExecute(Bitmap result) {
mCallback.onDataRetrieved(result);
}
}
private final class UpdateTask extends AsyncTask<Void, Void, Void> {
private final Bitmap mSplashImage;
public UpdateTask(Bitmap splashImage) {
mSplashImage = splashImage;
}
@Override
protected Void doInBackground(Void... nothing) {
mPreferences.edit()
.putString(KEY_SPLASH_ICON, ShortcutHelper.encodeBitmapAsString(mSplashImage))
.commit();
return null;
}
}
} |
PatelN123/chatwoot | spec/factories/super_admins.rb | <filename>spec/factories/super_admins.rb
FactoryBot.define do
factory :super_admin do
name { Faker::Name.name }
email { "<EMAIL>" }
password { '<PASSWORD>!' }
type { 'SuperAdmin' }
confirmed_at { Time.zone.now }
end
end
|
irwansetiawan/android-publisher-sdk | publisher-sdk/src/main/java/com/criteo/publisher/privacy/gdpr/GdprData.java | <gh_stars>1-10
/*
* Copyright 2020 Criteo
*
* 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.criteo.publisher.privacy.gdpr;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
@AutoValue
public abstract class GdprData {
public static GdprData create(
@NonNull String consentData,
@Nullable Boolean gdprApplies,
@NonNull Integer version
) {
return new AutoValue_GdprData(consentData, gdprApplies, version);
}
public static TypeAdapter<GdprData> typeAdapter(Gson gson) {
return new AutoValue_GdprData.GsonTypeAdapter(gson);
}
public abstract String consentData();
@Nullable
public abstract Boolean gdprApplies();
public abstract Integer version();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.