repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
6un9-h0-Dan/swamp-eclipse-plugin
eclipseplugin/src/org/continuousassurance/swamp/eclipse/handlers/AboutSwampHandler.java
/* * Copyright 2016-2017 <NAME>. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.continuousassurance.swamp.eclipse.handlers; import org.continuousassurance.swamp.eclipse.dialogs.AboutSWAMPDialog; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * Handler for showing AboutSWAMP dialog (which has information about the SWAMP * and this plug-in) * @author reid-jr * */ public class AboutSwampHandler extends AbstractHandler { @Override /** * Opens AboutSWAMP dialog * @param event click event * @return null */ public Object execute(ExecutionEvent event) throws ExecutionException { // gets workbench window IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); if (window != null) { AboutSWAMPDialog asd = new AboutSWAMPDialog(window.getShell()); asd.open(); } return null; } }
VikThor997/Hobby
OpenCVPython/openCV-1.py
<gh_stars>0 import cv2 print(cv2.__version__) cam = cv2.VideoCapture(0) while True: ignore, frame = cam.read() grayFrame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) cv2.imshow('my WEBcam',grayFrame) cv2.moveWindow('my WEBcam',0,0) if cv2.waitKey(1) & 0xff == ord('q'): break cam.release()
DamieFC/chromium
third_party/blink/renderer/core/inspector/inspector_highlight_test.cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/inspector/inspector_highlight.h" #include "base/test/values_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/html/html_element.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h" #include "third_party/inspector_protocol/crdtp/json.h" #include "third_party/inspector_protocol/crdtp/span.h" namespace blink { namespace { using base::test::ParseJson; using testing::ByRef; using testing::Eq; void AssertValueEqualsJSON(const std::unique_ptr<protocol::Value>& actual_value, const std::string& json_expected) { std::string json_actual; auto status_to_json = crdtp::json::ConvertCBORToJSON( crdtp::SpanFrom(actual_value->Serialize()), &json_actual); EXPECT_TRUE(status_to_json.ok()); base::Value parsed_json_actual = ParseJson(json_actual); base::Value parsed_json_expected = ParseJson(json_expected); EXPECT_THAT(parsed_json_actual, Eq(ByRef(parsed_json_expected))); } } // namespace class InspectorHighlightTest : public testing::Test { protected: void SetUp() override; Document& GetDocument() { return dummy_page_holder_->GetDocument(); } private: std::unique_ptr<DummyPageHolder> dummy_page_holder_; }; void InspectorHighlightTest::SetUp() { dummy_page_holder_ = std::make_unique<DummyPageHolder>(IntSize(800, 600)); } TEST_F(InspectorHighlightTest, BuildSnapContainerInfoNoSnapAreas) { GetDocument().body()->setInnerHTML(R"HTML( <div id="target">test</div> )HTML"); GetDocument().View()->UpdateAllLifecyclePhasesForTest(); Element* target = GetDocument().getElementById("target"); EXPECT_FALSE(BuildSnapContainerInfo(target)); } TEST_F(InspectorHighlightTest, BuildSnapContainerInfoSnapAreas) { GetDocument().body()->setInnerHTML(R"HTML( <style> #snap { background-color: white; scroll-snap-type: y mandatory; overflow-x: hidden; overflow-y: scroll; width: 150px; height: 150px; } #snap > div { width: 75px; height: 75px; scroll-snap-align: center; margin: 10px; padding: 10px; } </style> <div id="snap"><div>A</div><div>B</div></div> )HTML"); GetDocument().View()->UpdateAllLifecyclePhasesForTest(); Element* container = GetDocument().getElementById("snap"); auto info = BuildSnapContainerInfo(container); EXPECT_TRUE(info); EXPECT_EQ(2u, info->getArray("snapAreas")->size()); protocol::ErrorSupport errors; std::string expected_container = R"JSON( { "snapport":["M",8,8,"L",158,8,"L",158,158,"L",8,158,"Z"], "paddingBox":["M",8,8,"L",158,8,"L",158,158,"L",8,158,"Z"], "snapAreas": [ { "path":["M",18,18,"L",113,18,"L",113,113,"L",18,113,"Z"], "borderBox":["M",18,18,"L",113,18,"L",113,113,"L",18,113,"Z"], "alignBlock":"center" }, { "path":["M",18,123,"L",113,123,"L",113,218,"L",18,218,"Z"], "borderBox":["M",18,123,"L",113,123,"L",113,218,"L",18,218,"Z"], "alignBlock":"center" } ] } )JSON"; AssertValueEqualsJSON(protocol::ValueConversions<protocol::Value>::fromValue( info.get(), &errors), expected_container); } TEST_F(InspectorHighlightTest, BuildSnapContainerInfoTopLevelSnapAreas) { GetDocument().body()->setInnerHTML(R"HTML( <style> :root { scroll-snap-type: y mandatory; overflow-x: hidden; overflow-y: scroll; } div { width: 100%; height: 100vh; scroll-snap-align: start; } </style> <div>A</div><div>B</div> )HTML"); GetDocument().View()->UpdateAllLifecyclePhasesForTest(); Element* container = GetDocument().documentElement(); auto info = BuildSnapContainerInfo(container); EXPECT_TRUE(info); EXPECT_EQ(2u, info->getArray("snapAreas")->size()); protocol::ErrorSupport errors; std::string expected_container = R"JSON( { "paddingBox": [ "M", 0, 0, "L", 800, 0, "L", 800, 600, "L", 0, 600, "Z" ], "snapAreas": [ { "alignBlock": "start", "borderBox": [ "M", 8, 0, "L", 792, 0, "L", 792, 600, "L", 8, 600, "Z" ], "path": [ "M", 8, 0, "L", 792, 0, "L", 792, 600, "L", 8, 600, "Z" ] }, { "alignBlock": "start", "borderBox": [ "M", 8, 600, "L", 792, 600, "L", 792, 1200, "L", 8, 1200, "Z" ], "path": [ "M", 8, 600, "L", 792, 600, "L", 792, 1200, "L", 8, 1200, "Z" ] } ], "snapport": [ "M", 0, 0, "L", 800, 0, "L", 800, 600, "L", 0, 600, "Z" ] } )JSON"; AssertValueEqualsJSON(protocol::ValueConversions<protocol::Value>::fromValue( info.get(), &errors), expected_container); } } // namespace blink
suzil/awsstepfuncs
docs/source/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import sys from pathlib import Path import sphinx_rtd_theme # noqa: F401 from sphinx.ext import apidoc from awsstepfuncs import __version__ current_dir = Path(__file__).parent.absolute() base_dir = current_dir.parents[1] code_dir = base_dir / "src" / "awsstepfuncs" sys.path.insert(0, str(code_dir)) readme_dest = current_dir / "README.md" readme_src = base_dir / "README.md" if readme_dest.exists(): readme_dest.unlink() readme_dest.symlink_to(readme_src) # -- Project information ----------------------------------------------------- project = "awsstepfuncs" author = "<NAME>" copyright = "<NAME>" # noqa: A001 # The full version, including alpha/beta/rc tags release = __version__ # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "recommonmark", "sphinx_markdown_tables", "sphinx_rtd_theme", "sphinx.ext.autodoc", "sphinx.ext.coverage", "sphinx.ext.napoleon", ] autodoc_typehints = "description" # recommonmark extension allows mixed filetypes source_suffix = [".rst", ".md"] # Add any paths that contain templates here, relative to this directory. # templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] def run_apidoc(_): exclude = [] argv = [ "--doc-project", "Code Reference", "-M", "-f", "-d", "3", "--tocfile", "index", "-o", str(current_dir / "_code_reference"), str(code_dir), ] + exclude apidoc.main(argv) def setup(app): app.connect("builder-inited", run_apidoc)
hlooalklampc/tss
generated/ZendEngine_2/optimizers/isscalar.zep.c
#ifdef HAVE_CONFIG_H #include "../../ext_config.h" #endif #include <php.h> #include "../../php_ext.h" #include "../../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/memory.h" ZEPHIR_INIT_CLASS(Test_Optimizers_IsScalar) { ZEPHIR_REGISTER_CLASS(Test\\Optimizers, IsScalar, test, optimizers_isscalar, test_optimizers_isscalar_method_entry, 0); return SUCCESS; } PHP_METHOD(Test_Optimizers_IsScalar, testIntVar) { zval _0; int a; a = 1; ZEPHIR_SINIT_VAR(_0); ZVAL_LONG(&_0, a); RETURN_BOOL(zephir_is_scalar(&_0)); } PHP_METHOD(Test_Optimizers_IsScalar, testDoubleVar) { zval _0; double a; a = (double) (1); ZEPHIR_SINIT_VAR(_0); ZVAL_DOUBLE(&_0, a); RETURN_BOOL(zephir_is_scalar(&_0)); } PHP_METHOD(Test_Optimizers_IsScalar, testBoolVar) { zval _0; zend_bool a; a = 1; ZEPHIR_SINIT_VAR(_0); ZVAL_BOOL(&_0, (a ? 1 : 0)); RETURN_BOOL(zephir_is_scalar(&_0)); } PHP_METHOD(Test_Optimizers_IsScalar, testStringVar) { zval *a; ZEPHIR_MM_GROW(); ZEPHIR_INIT_VAR(a); ZVAL_STRING(a, "test string", 1); RETURN_MM_BOOL(zephir_is_scalar(a)); } PHP_METHOD(Test_Optimizers_IsScalar, testEmptyArrayVar) { zval *a; ZEPHIR_MM_GROW(); ZEPHIR_INIT_VAR(a); array_init(a); RETURN_MM_BOOL(zephir_is_scalar(a)); } PHP_METHOD(Test_Optimizers_IsScalar, testVar) { zval _0; int a; a = 1; ZEPHIR_SINIT_VAR(_0); ZVAL_LONG(&_0, a); RETURN_BOOL(zephir_is_scalar(&_0)); } PHP_METHOD(Test_Optimizers_IsScalar, testVarParameter) { zval *a; zephir_fetch_params(0, 1, 0, &a); RETURN_BOOL(zephir_is_scalar(a)); }
mcanoy/lodestar-backend
src/main/java/com/redhat/labs/lodestar/model/search/BsonSearch.java
<filename>src/main/java/com/redhat/labs/lodestar/model/search/BsonSearch.java package com.redhat.labs.lodestar.model.search; import static com.mongodb.client.model.Filters.and; import static com.mongodb.client.model.Filters.or; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bson.conversions.Bson; import lombok.Builder; @Builder public class BsonSearch { private static final String STATE = "state"; private static final String START = "start"; private static final String END = "end"; private static final String SEARCH_DELIMITER = "&"; private static final String EQUALS = "="; private String searchString; /** * Creates the {@link Bson} based on the given search {@link String}. * * @param search * @return */ public Optional<Bson> createBsonForSearch() { // parse the search string Optional<Map<Object, Map<Object, List<DefaultSearchComponent>>>> searchComponentMap = parseSearchString(); if (searchComponentMap.isEmpty()) { return Optional.empty(); } // create state search Optional<Bson> stateSearchBson = isRangeSearchComponent(searchComponentMap.get()) ? createRangeSearchComponent(searchComponentMap.get()) : Optional.empty(); // create bson for all other attributes Optional<Bson> searchBson = convertToBson(searchComponentMap.get()); if (searchBson.isPresent() && stateSearchBson.isPresent()) { return Optional.of(and(stateSearchBson.get(), searchBson.get())); } else if (searchBson.isPresent()) { return Optional.of(searchBson.get()); } else if (stateSearchBson.isPresent()) { return Optional.of(stateSearchBson.get()); } else { return Optional.empty(); } } /** * Return true if the map contains the START, END, or STATE keys. Otherwise, * false. * * @param searchComponentMap * @return */ private boolean isRangeSearchComponent(Map<Object, Map<Object, List<DefaultSearchComponent>>> searchComponentMap) { return searchComponentMap.containsKey(START) || searchComponentMap.containsKey(END) || searchComponentMap.containsKey(STATE); } /** * Creates a {@link Bson} for a range search using a date range and state if * provided. * * @param searchComponentMap * @return */ private Optional<Bson> createRangeSearchComponent( Map<Object, Map<Object, List<DefaultSearchComponent>>> searchComponentMap) { // get range start value String start = findFirstSearchComponentValue(searchComponentMap, START, EQUALS).orElse(null); searchComponentMap.remove(START); // get range end value String end = findFirstSearchComponentValue(searchComponentMap, END, EQUALS).orElse(null); searchComponentMap.remove(END); // create state search if required if (searchComponentMap.containsKey(STATE)) { // get state value EngagementState state = EngagementState .lookup(findFirstSearchComponentValue(searchComponentMap, STATE, EQUALS).orElse(null)); searchComponentMap.remove(STATE); // build state searchc component StateSearchComponent ssc = StateSearchComponent.builder().state(state).start(start).end(end).build(); return ssc.getBson(); } // create range search if state not provided RangeSearchComponent rsc = RangeSearchComponent.builder().start(start).end(end).build(); return rsc.getBson(); } /** * Parses the given search string to return a {@link List} of * {@link DefaultSearchComponent} grouping by attribute name and then operator. * * @param search * @return */ private Optional<Map<Object, Map<Object, List<DefaultSearchComponent>>>> parseSearchString() { if (null == searchString) { return Optional.empty(); } String[] components = searchString.split(SEARCH_DELIMITER); // group by attribute name and then operator return Optional.of(Stream.of(components).map(c -> DefaultSearchComponent.builder().component(c).build()) .filter(sc -> sc.getAttribute().isPresent() && sc.getOperator().isPresent()) .collect(Collectors.groupingBy(sc -> sc.getAttribute().get(), Collectors.groupingBy(sc -> sc.getOperator().get())))); } /** * Converts the {@link Map} containing {@link DefaultSearchComponent}s to a * {@link Bson} representing the search criteria. * * @param componentMap * @return */ private Optional<Bson> convertToBson(Map<Object, Map<Object, List<DefaultSearchComponent>>> searchComponentMap) { // field component List<Bson> andBsonList = searchComponentMap.entrySet().stream().map(fieldEntry -> { // and the bson for each operator in its list List<Bson> bsonList = fieldEntry.getValue().entrySet().stream().map(Entry::getValue).flatMap(List::stream) .map(DefaultSearchComponent::getBson).filter(Optional::isPresent).map(Optional::get) .collect(Collectors.toList()); return 1 == bsonList.size() ? bsonList.get(0) : or(bsonList); }).collect(Collectors.toList()); return andBsonList.isEmpty() ? Optional.empty() : Optional.of(and(andBsonList)); } /** * Returns an {@link Optional} containing the value of * {@link DefaultSearchComponent}. Otherwise, returns an empty {@link Optional}. * * @param searchComponent * @return */ private Optional<String> getValueFromSearchComponent(Optional<DefaultSearchComponent> searchComponent) { return searchComponent.filter(c -> c.getValue().isPresent()).map(DefaultSearchComponent::getValue) .filter(Optional::isPresent).map(Optional::get); } /** * Returns an {@link Optional} containing the value associated to the * {@link DefaultSearchComponent} for the given attribute name and operator * names. Otherwise, returns an empty {@link Optional}. * * @param searchComponentMap * @param attributeName * @param operator * @return */ private Optional<String> findFirstSearchComponentValue( Map<Object, Map<Object, List<DefaultSearchComponent>>> searchComponentMap, String attributeName, String operator) { Optional<DefaultSearchComponent> searchComponent = findFirtSearchComponent(searchComponentMap, attributeName, operator); return getValueFromSearchComponent(searchComponent); } /** * Returns an {@link Optional} containing the first * {@link DefaultSearchComponent} in the {@link Map} for the given attribute * name and operator name. Otherwise, returns an empty {@link Optional}. * * @param searchComponentMap * @param attribute * @param operator * @return */ private Optional<DefaultSearchComponent> findFirtSearchComponent( Map<Object, Map<Object, List<DefaultSearchComponent>>> searchComponentMap, String attribute, String operator) { return findSearchComponentList(searchComponentMap, attribute, operator).stream().findFirst(); } /** * Returns a {@link List} of {@link DefaultSearchComponent} in the {@link Map} * for the given attribute name and operator name. Otherwise, an empty * {@link List} is returned. * * @param searchComponentMap * @param attribute * @param operator * @return */ private List<DefaultSearchComponent> findSearchComponentList( Map<Object, Map<Object, List<DefaultSearchComponent>>> searchComponentMap, String attribute, String operator) { // get map for given attribute Map<Object, List<DefaultSearchComponent>> operatorMap = searchComponentMap.get(attribute); if (null == operatorMap) { return Arrays.asList(); } return operatorMap.entrySet().stream().filter(e -> e.getKey().equals(operator)) .filter(e -> null != e.getValue()).flatMap(e -> e.getValue().stream()).collect(Collectors.toList()); } }
Taschee/schafkopf
schafkopf/players/data/encodings.py
import numpy as np from schafkopf.game_modes import SOLO, WENZ, PARTNER_MODE, NO_GAME from schafkopf.suits import ACORNS, BELLS, LEAVES, HEARTS from schafkopf.helpers import sort_hand def encode_one_hot_card(card): index = card[0] * 4 + card[1] encoded_card = np.zeros(32) encoded_card[index] = 1 return encoded_card def decode_one_hot_card(encoded_card): index = np.where(encoded_card == 1)[0][0] card_decoded = (index // 4, index % 4) return card_decoded def encode_one_hot_hand(hand): hand = sort_hand(hand) enc_hand = np.zeros((len(hand), 32)) for card, i in zip(hand, range(len(hand))): enc_hand[i] = encode_one_hot_card(card) return enc_hand def decode_on_hot_hand(hand_encoded): hand = [] for card_enc in hand_encoded: card = decode_one_hot_card(card_enc) hand.append(card) return hand def encode_hand_inference(hand): enc_hand_one_hot = encode_one_hot_hand(hand) hand_encoded = np.sum(enc_hand_one_hot.transpose(), axis=1) return hand_encoded def decode_hand_inference(hand_enc): card_indices = np.where(hand_enc == 1)[0] hand_still_enc = np.zeros((len(card_indices), 32)) for i, card_index in enumerate(card_indices): hand_still_enc[i][card_index] = 1 hand = decode_on_hot_hand(hand_still_enc) return hand def encode_one_hot_player_position(position): position_encoded = np.zeros(4) position_encoded[position] = 1 return position_encoded def decode_one_hot_player_position(position_encoded): return np.where(position_encoded == 1)[0][0] def encode_one_hot_game_mode(game_mode, length=9): encoded_mode = np.zeros(length) if game_mode[0] == NO_GAME: encoded_mode[0] = 1 elif game_mode[0] == PARTNER_MODE: if game_mode[1] == BELLS: encoded_mode[1] = 1 elif game_mode[1] == LEAVES: encoded_mode[2] = 1 elif game_mode[1] == ACORNS: encoded_mode[3] = 1 elif game_mode[0] == WENZ: encoded_mode[4] = 1 elif game_mode[0] == SOLO: shift = game_mode[1] encoded_mode[5 + shift] = 1 return encoded_mode def decode_one_hot_game_mode(game_mode_encoded): index = np.where(game_mode_encoded == 1)[0][0] game_mode = decode_mode_index(index) return game_mode def decode_mode_index(index): if index == 0: game_mode = (NO_GAME, None) elif index == 1: game_mode = (PARTNER_MODE, BELLS) elif index == 2: game_mode = (PARTNER_MODE, LEAVES) elif index == 3: game_mode = (PARTNER_MODE, ACORNS) elif index == 4: game_mode = (WENZ, None) else: suit = index - 5 game_mode = (SOLO, suit) return game_mode def encode_played_cards(played_cards, next_rel_pos): """Takes list of tuples of (played_card, player) and next player to act as input. Outputs those encoded as (28, 36) numpy array.""" seq = np.zeros((28, 36)) if len(played_cards) == 0: rel_pos = next_rel_pos seq[0][32:] = encode_one_hot_player_position(rel_pos) else: # first entry contains only the relative player position of the player playing at the moment rel_pos = played_cards[0][1] seq[0][32:] = encode_one_hot_player_position(rel_pos) # after this, the next card and the relative player position of the next player are added to sequence for card_index in range(len(played_cards) - 1): card = played_cards[card_index][0] rel_pos_next_player = played_cards[card_index + 1][1] next_part_in_seq = np.zeros(36) next_part_in_seq[32:] = encode_one_hot_player_position(rel_pos_next_player) next_part_in_seq[:32] = encode_one_hot_card(card) seq[card_index + 1] = next_part_in_seq last_index = len(played_cards) last_card = played_cards[-1][0] last_part_in_seq = np.zeros(36) last_part_in_seq[32:] = encode_one_hot_player_position(next_rel_pos) last_part_in_seq[:32] = encode_one_hot_card(last_card) seq[last_index] = last_part_in_seq return seq
fgirse/commodore3
node_modules/@theme-ui/components/src/Badge.js
import React from 'react' import Box from './Box' export const Badge = React.forwardRef((props, ref) => ( <Box ref={ref} variant="primary" {...props} __themeKey="badges" __css={{ display: 'inline-block', verticalAlign: 'baseline', fontSize: 0, fontWeight: 'bold', whiteSpace: 'nowrap', px: 1, borderRadius: 2, color: 'white', bg: 'primary', }} /> ))
l1ttleO/splatcraft-forge
src/main/java/com/cibernet/splatcraft/data/capabilities/saveinfo/SaveInfoCapability.java
<gh_stars>1-10 package com.cibernet.splatcraft.data.capabilities.saveinfo; import net.minecraft.nbt.CompoundNBT; import net.minecraft.server.MinecraftServer; import net.minecraft.util.Direction; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class SaveInfoCapability implements ICapabilitySerializable<CompoundNBT> { @CapabilityInject(ISaveInfo.class) public static final Capability<ISaveInfo> CAPABILITY = null; private static final ISaveInfo DEFAULT = new SaveInfo(); private final LazyOptional<ISaveInfo> instance = LazyOptional.of(CAPABILITY::getDefaultInstance); public static void register() { CapabilityManager.INSTANCE.register(ISaveInfo.class, new SaveInfoStorage(), SaveInfo::new); } public static ISaveInfo get(MinecraftServer server) throws NullPointerException { return server.getWorld(World.OVERWORLD).getCapability(CAPABILITY).orElseThrow(() -> new NullPointerException("Couldn't find WorldData capability!")); } @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return CAPABILITY.orEmpty(cap, instance); } @Override public CompoundNBT serializeNBT() { return (CompoundNBT) CAPABILITY.getStorage().writeNBT(CAPABILITY, instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional cannot be empty!")), null); } @Override public void deserializeNBT(CompoundNBT nbt) { CAPABILITY.getStorage().readNBT(CAPABILITY, instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional cannot be empty!")), null, nbt); } }
joaomrcsmartins/MIEIC_AIAD_2020
Repast-3.1/RepastJ/src/uchicago/src/sim/analysis/ObjectData.java
/*$$ * Copyright (c) 1999, Trustees of the University of Chicago * 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 Chicago 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 TRUSTEES OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *$$*/ package uchicago.src.sim.analysis; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Vector; import uchicago.src.sim.util.SimUtilities; /** * Stores simulation data as objects. These objects can be written out * to a file as Strings via the Objects toString() method. It is assumed * that such data is already approriately formatted. These objects are * from DataSources stored by an ObjectDataRecorder. * * @author <NAME> * @version $Revision: 1.4 $ $Date: 2004/11/03 19:51:00 $ */ public class ObjectData { private Vector data = new Vector(); private String dataHeader; private String fileName; private String modelHeader; private boolean isBatch; //private boolean writeHeader = true; private boolean nothingWritten = true; /** * Creates an ObjectData with the specified fileName, model header, and * whether this is a batch run or not. * * @param filename the name of the file to write the data out to. * @param modelHeader the model header (parameters etc.) * @param header the header for this data. * @param isBatch whether this is a batch run or not. */ public ObjectData(String filename, String modelHeader, String header, boolean isBatch) { this.fileName = filename; this.modelHeader = modelHeader; this.isBatch = isBatch; dataHeader = header; } /** * Adds newData to this ObjectData * * @param newData the new data to add */ public void addData(Object newData) { data.add(newData); } private void renameFile() throws IOException { File oldFile = new File(fileName); fileName = oldFile.getCanonicalPath(); if (oldFile.exists()) { int x = 1; File newFile; String newName = fileName; String lastPart = ""; if (fileName.indexOf(".") != -1) { int index = fileName.lastIndexOf("."); newName = fileName.substring(0, index); lastPart = fileName.substring(index, fileName.length()); } if (isBatch) { newName += ".bak"; } do { newFile = new File(newName + x + lastPart); x++; } while (newFile.exists()); oldFile.renameTo(newFile); oldFile.delete(); } } /** * Writes the data (and a file header) out to a file. This flushes all * data from the data vector out to a file. */ public void writeToFile() { BufferedWriter out = null; try { // has not written anything out yet if (nothingWritten) { renameFile(); out = new BufferedWriter(new FileWriter(fileName, true)); out.write(modelHeader); out.newLine(); out.newLine(); out.write(dataHeader); out.newLine(); } nothingWritten = false; if (out == null) out = new BufferedWriter(new FileWriter(fileName, true)); for (int i = 0; i < data.size(); i++) { out.write(data.get(i).toString()); out.newLine(); } out.flush(); out.close(); data.clear(); } catch (IOException ex) { SimUtilities.showError("Unable to write data to file", ex); ex.printStackTrace(); try { out.flush(); out.close(); } catch (Exception ex1) {} System.exit(0); } } }
pousse-cafe/pousse-cafe-source
src/test/resources/poussecafe/source/generation/generatedfull/process/Process1.java
package poussecafe.source.generation.generatedfull.process; import poussecafe.domain.Process; public interface Process1 extends Process { }
v-ya/local
av1/obu/frame_render_size.h
#ifndef _av1_obu_frame_render_size_h_ #define _av1_obu_frame_render_size_h_ #include "obu.h" typedef struct av1_frame_render_size_t { uint32_t frame_width; // [1, 65536] uint32_t frame_height; // [1, 65536] uint32_t render_width; // [1, 65536] uint32_t render_height; // [1, 65536] uint32_t superres_denom; // [8, 16] // calc uint32_t UpscaledWidth; uint32_t FrameWidth; uint32_t FrameHeight; uint32_t RenderWidth; uint32_t RenderHeight; uint32_t MiCols; uint32_t MiRows; } av1_frame_render_size_t; av1_frame_render_size_t* av1_frame_render_size_init(av1_frame_render_size_t *restrict frsize); av1_frame_render_size_t* av1_frame_render_size_read_superres_params(av1_frame_render_size_t *restrict frsize, av1_bits_reader_t *restrict reader, const struct av1_obu_sequence_header_t *restrict header); av1_frame_render_size_t* av1_frame_render_size_read(av1_frame_render_size_t *restrict frsize, av1_bits_reader_t *restrict reader, const struct av1_obu_sequence_header_t *restrict header, uint8_t frame_size_override_flag); const av1_frame_render_size_t* av1_frame_render_size_write_superres_params(const av1_frame_render_size_t *restrict frsize, av1_bits_writer_t *restrict writer, const struct av1_obu_sequence_header_t *restrict header); const av1_frame_render_size_t* av1_frame_render_size_write(const av1_frame_render_size_t *restrict frsize, av1_bits_writer_t *restrict writer, const struct av1_obu_sequence_header_t *restrict header, uint8_t frame_size_override_flag); uint64_t av1_frame_render_size_bits_superres_params(const av1_frame_render_size_t *restrict frsize, const struct av1_obu_sequence_header_t *restrict header); uint64_t av1_frame_render_size_bits(const av1_frame_render_size_t *restrict frsize, const struct av1_obu_sequence_header_t *restrict header, uint8_t frame_size_override_flag); void av1_frame_render_size_dump(const av1_frame_render_size_t *restrict frsize, mlog_s *restrict mlog); #endif
FindYourGrind/esp32
components/cpp_utils/BLEAdvertising.cpp
<reponame>FindYourGrind/esp32<gh_stars>0 /* * BLEAdvertising.cpp * * This class encapsulates advertising a BLE Server. * Created on: Jun 21, 2017 * Author: kolban */ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include "BLEAdvertising.h" #include <esp_log.h> #include <esp_err.h> #include "BLEUtils.h" #include "GeneralUtils.h" static char LOG_TAG[] = "BLEAdvertising"; /** * @brief Construct a default advertising object. * */ BLEAdvertising::BLEAdvertising() { m_advData.set_scan_rsp = false; m_advData.include_name = true; m_advData.include_txpower = true; m_advData.min_interval = 0x20; m_advData.max_interval = 0x40; m_advData.appearance = 0x00; m_advData.manufacturer_len = 0; m_advData.p_manufacturer_data = nullptr; m_advData.service_data_len = 0; m_advData.p_service_data = nullptr; m_advData.service_uuid_len = 0; m_advData.p_service_uuid = nullptr; m_advData.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT); m_advParams.adv_int_min = 0x20; m_advParams.adv_int_max = 0x40; m_advParams.adv_type = ADV_TYPE_IND; m_advParams.own_addr_type = BLE_ADDR_TYPE_PUBLIC; m_advParams.channel_map = ADV_CHNL_ALL; m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; } // BLEAdvertising /** * @brief Set the device appearance in the advertising data. * The appearance attribute is of type 0x19. The codes for distinct appearances can be found here: * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml. * @param [in] appearance The appearance of the device in the advertising data. * @return N/A. */ void BLEAdvertising::setAppearance(uint16_t appearance) { m_advData.appearance = appearance; } // setAppearance /** * @brief Set the service UUID. * @param [in] uuid The UUID of the service. * @return N/A. */ void BLEAdvertising::setServiceUUID(BLEUUID uuid) { ESP_LOGD(LOG_TAG, ">> setServiceUUID(%s)", uuid.toString().c_str()); m_serviceUUID = uuid; // Save the new service UUID esp_bt_uuid_t espUUID = *m_serviceUUID.getNative(); switch(espUUID.len) { case ESP_UUID_LEN_16: { m_advData.service_uuid_len = 2; m_advData.p_service_uuid = reinterpret_cast<uint8_t*>(&espUUID.uuid.uuid16); break; } case ESP_UUID_LEN_32: { m_advData.service_uuid_len = 4; m_advData.p_service_uuid = reinterpret_cast<uint8_t*>(&espUUID.uuid.uuid32); break; } case ESP_UUID_LEN_128: { m_advData.service_uuid_len = 16; m_advData.p_service_uuid = reinterpret_cast<uint8_t*>(&espUUID.uuid.uuid128); break; } } // switch ESP_LOGD(LOG_TAG, "<< setServiceUUID()"); } // setServiceUUID /** * @brief Start advertising. * Start advertising. * @return N/A. */ void BLEAdvertising::start() { ESP_LOGD(LOG_TAG, ">> start()"); if (m_advData.service_uuid_len > 0) { uint8_t hexData[16*2+1]; BLEUtils::buildHexData(hexData, m_advData.p_service_uuid, m_advData.service_uuid_len); ESP_LOGD(LOG_TAG, " - Service: service_uuid_len=%d, p_service_uuid=0x%x (data=%s)", m_advData.service_uuid_len, (uint32_t)m_advData.p_service_uuid, (m_advData.service_uuid_len > 0?(char *)hexData:"N/A") ); } // We have a service to advertise // Set the configuration for advertising. esp_err_t errRc = ::esp_ble_gap_config_adv_data(&m_advData); if (errRc != ESP_OK) { ESP_LOGE(LOG_TAG, "<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } // Start advertising. errRc = ::esp_ble_gap_start_advertising(&m_advParams); if (errRc != ESP_OK) { ESP_LOGE(LOG_TAG, "<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } ESP_LOGD(LOG_TAG, "<< start();") } // start /** * @brief Stop advertising. * Stop advertising. * @return N/A. */ void BLEAdvertising::stop() { esp_err_t errRc = ::esp_ble_gap_stop_advertising(); if (errRc != ESP_OK) { ESP_LOGE(LOG_TAG, "esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } } // stop #endif /* CONFIG_BT_ENABLED */
Proskomma/diegesis
src/components/treeLeaves.js
const leaves1 = nodes => { const ret = []; for (const node of nodes) { if (node.children && node.children.length > 0) { for (const child of leaves1(node.children)) { if (!child.cv) { child.cv = node.cv } ret.push(child); } } else { ret.push(node.content); } } return ret; } const leaves = (nodes, cv, sentence) => { if (nodes.length === 0) { return []; } const node = nodes[0]; if (node.cv && node.cv !== cv) { cv = node.cv; } else { delete node.cv; } if (node.sentence && node.sentence !== sentence) { sentence = node.sentence; } else { delete node.sentence; } return [node].concat(leaves(nodes.slice(1), cv, sentence)); } export {leaves, leaves1};
KeyWorksRW/ttBld
src/archive/convertdlg.h
///////////////////////////////////////////////////////////////////////////// // Name: CConvertDlg // Purpose: IDDDLG_CONVERT dialog handler // Author: <NAME> // Copyright: Copyright (c) 2019-2020 KeyWorks Software (<NAME>) // License: Apache License (see ../LICENSE) ///////////////////////////////////////////////////////////////////////////// #pragma once #ifndef IDDDLG_CONVERT #include "resource.h" #endif #include <ttcwd.h> // cwd -- Class for storing and optionally restoring the current directory #include <ttwindlg.h> // Class for displaying a dialog #include "writesrc.h" // CWriteSrcFiles -- Writes a new or update srcfiles.yaml file class CConvertDlg : public ttlib::dlg { public: CConvertDlg(); CConvertDlg(std::string_view projectFile); const ttlib::cstr& GetOutSrcFiles() { return m_cszOutSrcFiles; } const ttlib::cstr& GetDirSrcFiles() { return m_cszDirSrcFiles; } const ttlib::cstr& GetConvertScript() { return m_ConvertFile; } void SetConvertScritpt(std::string_view filename); bool isCreateVsCode() { return m_CreateVscode; } bool isAddToGitExclude() { return m_AddToGitExclude; } protected: BEGIN_TTCMD_MAP() TTCASE_CMD(IDBTN_CHANGE_IN, OnBtnChangeIn) TTCASE_CMD(IDBTN_CHANGE_OUT, OnBtnChangeOut) TTCASE_CMD(IDBTN_LOCATE_SCRIPT, OnBtnLocateScript) TTCASE_CMD(IDRADIO_CONVERT, OnCheckConvert) TTCASE_CMD(IDRADIO_FILES, OnCheckFiles) END_TTMSG_MAP() void OnCheckFiles(); void OnCheckConvert(); void OnBtnChangeIn(); void OnBtnChangeOut(); void OnBtnLocateScript(); void OnBegin(void) override; void OnOK(void) override; bool ConvertSrcfiles(); // BUGBUG: [KeyWorks - 03-28-2020] This should return bld:RESULT bool doConversion(); private: ttlib::dlgCombo m_comboScripts; CWriteSrcFiles m_cSrcFiles; ttlib::cstr m_cszOutSrcFiles; // Where .srcfiles should be created ttlib::cstr m_cszDirSrcFiles; ttlib::cstr m_ConvertFile; ttlib::cstr m_cszScriptRoot; ttlib::cstr m_cszOutRoot; ttlib::cstr m_cszRelative; // Used to create a relative location for a source file ttlib::cwd m_cwd { true }; bool m_CreateVscode { false }; bool m_AddToGitExclude { false }; };
WuzgXY-GitHub/Melon-Slabs
src/main/java/net/melon/slabs/mixin/ComposterMixin.java
<reponame>WuzgXY-GitHub/Melon-Slabs package net.melon.slabs.mixin; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import it.unimi.dsi.fastutil.objects.Object2FloatMap; import net.melon.slabs.items.MelonSlabsItems; import net.minecraft.block.ComposterBlock; import net.minecraft.item.ItemConvertible; @Mixin(ComposterBlock.class) public class ComposterMixin{ @Shadow @Final public static Object2FloatMap<ItemConvertible> ITEM_TO_LEVEL_INCREASE_CHANCE; @Inject(at = @At("HEAD"), method = "registerDefaultCompostableItems") private static void registerDefaultCompostableITems(final CallbackInfo info) { ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.CARVED_MELON.asItem(), 0.65f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.MELON_SLAB.asItem(), 0.55f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.CARVED_MELON_SLAB.asItem(), 0.55f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.MELON_STAIRS.asItem(), 0.6f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.PUMPKIN_SLAB.asItem(), 0.55f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.CARVED_PUMPKIN_SLAB.asItem(), 0.55f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.PUMPKIN_STAIRS.asItem(), 0.6f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.PUMPKIN_SLICE.asItem(), 0.5f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.COOKED_PUMPKIN_SLICE.asItem(), 0.3f); ITEM_TO_LEVEL_INCREASE_CHANCE.put(MelonSlabsItems.CACTUS_SLAB.asItem(), 0.3f); } }
fche-tools/FCHE
src/main/java/entitybuilder/javabuilder/javavisitor/JavaEntityVisitor.java
<reponame>fche-tools/FCHE package entitybuilder.javabuilder.javavisitor; import entitybuilder.javabuilder.javaentity.ClassEntity; import entitybuilder.javabuilder.javaentity.InterfaceEntity; import entitybuilder.javabuilder.javaentity.MethodEntity; import entitybuilder.javabuilder.javaentity.VarEntity; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.tree.ErrorNodeImpl; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import parser.parsejava.JavaBaseVisitor; import parser.parsejava.JavaParser; import sun.misc.Queue; import uerr.SingleCollect; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author wsz */ public class JavaEntityVisitor extends JavaBaseVisitor { private String fileFullPath; public JavaProcessTask processTask = new JavaProcessTask(); private ClassEntity classEntity = new ClassEntity(); public JavaEntityVisitor(String fileFullPath){ this.fileFullPath = fileFullPath; } /** * find import * @param ctx * @return */ @Override public String visitImportDeclaration(JavaParser.ImportDeclarationContext ctx) { String str; str = ctx.children.get(1).getText(); classEntity.addToImportList(str); return str; } /** * find interface * @param ctx * @return */ @Override public String visitInterfaceDeclaration(JavaParser.InterfaceDeclarationContext ctx) { SingleCollect singleCollect = SingleCollect.getSingleCollectInstance(); String str; if(ctx==null){ return ""; } str = ctx.children.get(1).getText(); int parentId = processTask.processPackage(fileFullPath); String name = fileFullPath; int id = singleCollect.getCurrentIndex(); InterfaceEntity interfaceEntity = new InterfaceEntity(id,name,parentId); singleCollect.addEntity(interfaceEntity); return str; } /** * find Class * @param ctx * @return */ @Override public String visitClassDeclaration(JavaParser.ClassDeclarationContext ctx) { SingleCollect singleCollect = SingleCollect.getSingleCollectInstance(); String str; if (ctx==null){ return ""; } //创建package实体返回id int parentId = processTask.processPackage(fileFullPath); //包含包名和文件名 str = fileFullPath; //发现implements if(ctx.children.size()>3 && ctx.children.get(2).getText().equals("implements")) { classEntity.setImplementFile(ctx.children.get(3).getChild(0).getText()); } //发现extends if(ctx.children.size()>3 && ctx.children.get(2).getText().equals("extends")) { classEntity.setExtendsFile(ctx.children.get(3).getChild(0).getText()); } classEntity.setName(str); classEntity.setId(processTask.singleCollect.getCurrentIndex()); classEntity.setParentId(parentId); singleCollect.addEntity(classEntity); RuleContext ctx2; // 排除错误节点 if (ctx.children.get(ctx.children.size()-1) instanceof ErrorNodeImpl) { return ""; } try { ctx2 = (RuleContext) ctx.children.get(ctx.children.size()-1); visitClassBody((JavaParser.ClassBodyContext) ctx2); }catch (Exception e){ e.printStackTrace(); } //创建类实体,添加入singleCollect singleCollect.class_method_map.put(classEntity.getName(),classEntity.getMethodList()); return str; } /** * find class body * @param ctx * @return */ @Override public String visitClassBody(JavaParser.ClassBodyContext ctx) { String str = ""; if(ctx==null){ return ""; } //0:'{';1-size-2:'ClassBodyDeclarationContext';size-1:'}'; for (int i =1;i<ctx.children.size()-1;i++){ RuleContext ctx2; //出现错误节点,进行排除 if(ctx.children.get(i) instanceof ErrorNodeImpl) { System.out.println("error node"); continue; } ctx2 = (RuleContext) ctx.children.get(i); visitClassBodyDeclaration((JavaParser.ClassBodyDeclarationContext) ctx2); } return str; } /** * find class declaration */ @Override public String visitClassBodyDeclaration(JavaParser.ClassBodyDeclarationContext ctx) { String str = ""; if(ctx==null){ return ""; } RuleContext ctx2; //last:MemberDeclarationContext for (int i =0;i<ctx.children.size();i++) { if(ctx.children.get(i) instanceof JavaParser.MemberDeclarationContext) { ctx2 = (RuleContext) ctx.children.get(i); visitMemberDeclaration((JavaParser.MemberDeclarationContext) ctx2); return str; } } return ""; } @Override public String visitMemberDeclaration(JavaParser.MemberDeclarationContext ctx) { String str = ""; if(ctx==null || ctx.children==null){ return ""; } RuleContext ctx2; for(int i=0;i<ctx.children.size();i++){ if(ctx.children.get(i) instanceof JavaParser.FieldDeclarationContext){ ctx2 = (RuleContext) ctx.children.get(i); visitFieldDeclaration((JavaParser.FieldDeclarationContext) ctx2); }else if(ctx.children.get(i) instanceof JavaParser.ConstructorDeclarationContext){ }else if(ctx.children.get(i) instanceof JavaParser.MethodDeclarationContext){ ctx2 = (RuleContext) ctx.children.get(i); visitMethodDeclaration((JavaParser.MethodDeclarationContext) ctx2); } } return str; } /** * find var declaration * @param ctx * @return */ @Override public String visitFieldDeclaration(JavaParser.FieldDeclarationContext ctx) { if(ctx==null){ return ""; } String str=""; SingleCollect singleCollect = SingleCollect.getSingleCollectInstance(); VarEntity varEntity = new VarEntity(); for (int i=0;i<ctx.children.size();i++){ if(ctx.children.get(i) instanceof JavaParser.TypeContext){ varEntity.setType(((JavaParser.TypeContext) ctx.children.get(i)).children.get(0).getChild(0).getText()); } if(ctx.children.get(i) instanceof JavaParser.VariableDeclaratorsContext){ varEntity.setName(fileFullPath.replace(".java","")+"."+ctx.children.get(i).getChild(0).getText().split("=")[0]); } } //设置变量列表 classEntity.getVarList().add(varEntity.getVarType()); varEntity.setId(singleCollect.getCurrentIndex()); varEntity.setParentId(classEntity.getId()); singleCollect.addEntity(varEntity); return str; } /** * find Constructor * @param ctx * @return */ @Override public String visitConstructorDeclaration(JavaParser.ConstructorDeclarationContext ctx) { String str; str = ctx.children.get(0).getText(); str = "Constructor:"+str; classEntity.setConstructor(true); return str; } /** * find method * @param ctx * @return */ @Override public String visitMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { SingleCollect singleCollect = SingleCollect.getSingleCollectInstance(); String methodName; methodName=fileFullPath.replace(".java","")+"."+ctx.children.get(1).getText(); MethodEntity methodEntity = new MethodEntity(classEntity.getId(),singleCollect.getCurrentIndex(),methodName); //最大块深度,inQueue/outQueue用于计算最大深度,分别表示当前进入队列数与当次退出队列数, int max_block_depth=0; int thisQ=0; int inQueue=1; int outQueue=0; //临时变量个数 int localVarDecl=0; //可执行语句 int execStmt=0; //操作数,操作符 Map<String,Integer> operands = new HashMap<>(); Map<String,Integer> operators = new HashMap<>(); //控制语句块个数 int control_block_num=1; //获取方法的总行数setMethod_line methodEntity.setMethod_line(ctx.stop.getLine()-ctx.start.getLine()+1); //添加方法_类hashmap method_class_map if(!singleCollect.method_class_map.containsKey(methodName)){ Set<String> methodList = new HashSet<String>(); methodList.add(classEntity.getName()); singleCollect.method_class_map.put(methodName,methodList); }else{ singleCollect.method_class_map.get(methodName).add(classEntity.getName()); } //找出返回类型setReturnType if(ctx.children.get(0) instanceof JavaParser.TypeContext){ methodEntity.setReturnType(ctx.children.get(0).getChild(0).getText()); } //获取参数的个数setPara_num //找出参数列中存在的类形存入para_class_list //是否有返回参数 if(ctx.children.size()>=3) { int child_count = ctx.children.get(2).getChild(1).getChildCount(); methodEntity.setPara_num((child_count+1)/2); if(ctx.children.get(2).getChildCount()>2) { for (int i =0; i<child_count;i++) { String typeName=ctx.children.get(2).getChild(1).getChild(i).getText(); if (!typeName.contains(",")){ methodEntity.para_class_list.add(ctx.children.get(2).getChild(1).getChild(i).getChild(0).getText()); } } } } //找出方法体中的类,存在抽象方法(没函数体) if (ctx.children.size() == 4) { //排除抽象方法(无函数体情况)abstract XXX(); if(!";".equals(ctx.children.get(3).getText())) { //广度优先遍历函数体,访问其中的所有块,声明块中存在函数,其他块则继续访问 Queue queue = new Queue(); queue.enqueue(ctx.children.get(3).getChild(0)); while(!queue.isEmpty()){ //出队 try { //计算max_block_depth最大深度深度 if(inQueue==outQueue) { inQueue += thisQ; thisQ = 0; max_block_depth++; } outQueue++; ParserRuleContext ctx1 = (ParserRuleContext) queue.dequeue(); ParserRuleContext ctx2 = null; //后续入队 if(ctx1 instanceof JavaParser.StatementContext ){ //ifelse语句块导致ctx1.child中存在StatementContext if(ctx1.getChildCount()>1) { for (int i = 0; i < ctx1.getChildCount(); i++) { if (ctx1.getChild(i) instanceof JavaParser.StatementContext && ctx1.getChild(i).getChild(0) instanceof JavaParser.BlockContext) { ctx2 = (ParserRuleContext) ctx1.getChild(i).getChild(0); } } } else if(ctx1.getChild(0) instanceof JavaParser.BlockContext){ ctx2 = (ParserRuleContext) ctx1.getChild(0); } }else if(ctx1 instanceof JavaParser.BlockContext){ //第一次入队 ctx2 = ctx1; } if(ctx2!=null){ //方法体里面的块的个数(包含两个括号) int blocksize = ctx2.getChildCount(); //排除空函数体情况XXX(){} if(blocksize>=3){ for (int i=1;i<blocksize-1;i++) { //声明语句块(LocalVariableDeclarationStatementContext):可检测出类的声明、可执行语句 ParserRuleContext ctx3 = (ParserRuleContext) ctx2.getChild(i).getChild(0); // 声明语句 if(ctx3 instanceof JavaParser.LocalVariableDeclarationStatementContext){ localVarDecl++; if(ctx3.getChild(0) instanceof JavaParser.LocalVariableDeclarationContext){ methodEntity.body_class_list.add(ctx3.getChild(0).getChild(0).getText()); } // 其他语句 }else{ //非声明语句块:if,else,while,for,try,switch等(return) if(ctx3 instanceof JavaParser.StatementContext){ if("if".equals(ctx3.getChild(0).getText())|| "do".equals(ctx3.getChild(0).getText())|| "while".equals(ctx3.getChild(0).getText())|| "for".equals(ctx3.getChild(0).getText())|| "switch".equals(ctx3.getChild(0).getText())|| "try".equals(ctx3.getChild(0).getText())|| "return".equals(ctx3.getChild(0).getText()) ) { //记录本次加入块数 int addnum = 0; //将{}的statementContext 继续放入队列 for (int j = 0; j < ctx3.getChildCount(); j++) { if (ctx3.getChild(j) instanceof JavaParser.StatementContext) {//for while do queue.enqueue(ctx3.getChild(j)); control_block_num++; addnum++; }else if(ctx3.getChild(j) instanceof JavaParser.BlockContext){ //try for(int k=1;k<ctx3.getChild(j).getChildCount()-1;k++){ if(ctx3.getChild(j).getChild(k).getText().contains("{")){ queue.enqueue(ctx3.getChild(j).getChild(k).getChild(0)); control_block_num++; addnum++; } } }else if(ctx3.getChild(j) instanceof JavaParser.FinallyBlockContext){ //finally for(int k=0;k<ctx3.getChild(j).getChild(1).getChildCount();k++){ if(ctx3.getChild(j).getChild(1).getChild(k).getChild(0) instanceof JavaParser.StatementContext && ctx3.getChild(j).getChild(1).getChild(k).getChild(0).getText().contains("{")){ queue.enqueue(ctx3.getChild(j).getChild(1).getChild(k).getChild(0)); control_block_num++; addnum++; } } }else if(ctx3.getChild(j) instanceof JavaParser.SwitchBlockStatementGroupContext){//switch for(int k=0;k<ctx3.getChild(j).getChildCount();k++){ if (ctx3.getChild(j).getChild(k) instanceof JavaParser.BlockStatementContext && (ctx3.getChild(j).getChild(k).getChild(0).getText()).contains("{")){ queue.enqueue(ctx3.getChild(j).getChild(k).getChild(0)); control_block_num++; addnum++; } } } } thisQ += addnum; }else{//普通语句,用于检测调用其他类方法否 execStmt++; } } } } } } }catch (Exception e){ e.printStackTrace(); } } } } else { // System.out.println("lengths too low"); } if (ctx.children.size() == 4) { //排除抽象方法(无函数体情况)abstract XXX(); if (!";".equals(ctx.children.get(3).getText())) { //广度优先遍历函数体,访问其中的所有块,声明块中存在函数,其他块则继续访问 Queue queue = new Queue(); queue.enqueue(ctx.children.get(3).getChild(0)); while (!queue.isEmpty()) { //出队 try { ParserRuleContext ctx1 = (ParserRuleContext) queue.dequeue(); ParserRuleContext ctx2 = null; if (ctx1 instanceof JavaParser.StatementContext) { //后续入队 //ifelse语句块导致ctx1.child中存在StatementContext if (ctx1.getChildCount() > 1) { for (int i = 0; i < ctx1.getChildCount(); i++) { if (ctx1.getChild(i) instanceof JavaParser.StatementContext && ctx1.getChild(i).getChild(0) instanceof JavaParser.BlockContext) { ctx2 = (ParserRuleContext) ctx1.getChild(i).getChild(0); } } } else if (ctx1.getChild(0) instanceof JavaParser.BlockContext) { ctx2 = (ParserRuleContext) ctx1.getChild(0); } } else if (ctx1 instanceof JavaParser.BlockContext) { //第一次入队 ctx2 = ctx1; } if (ctx2 != null) { //方法体里面的块的个数(包含两个括号) int blocksize = ctx2.getChildCount(); if (blocksize >= 3) { //排除空函数体情况XXX(){} boolean setMethodName = false; for (int i = 1; i < blocksize - 1; i++) { //声明语句块(LocalVariableDeclarationStatementContext):可检测出类的声明、可执行语句 ParserRuleContext ctx3 = (ParserRuleContext) ctx2.getChild(i).getChild(0); // 解析ctx3里面的各个节点 Queue queue1 = new Queue(); queue1.enqueue(ctx3); //将方法名等信息加入map(只能加一次) if(!setMethodName) { for (int k = 0; k < ctx.children.get(2).getChildCount() - 1; k++) { queue1.enqueue(ctx.children.get(2).getChild(k)); } setMethodName = true; } while (!queue1.isEmpty()){ Object obj=queue1.dequeue(); if(obj instanceof TerminalNode || obj instanceof JavaParser.TypeContext){ String objString =""; if(obj instanceof TerminalNode){ objString = obj.toString(); }else{ JavaParser.TypeContext typeContext = (JavaParser.TypeContext)obj; objString = typeContext.getText(); } // 已经存在该操作符 if(operators.containsKey(objString)) { operators.put(objString,operators.get(objString)+1); }else { // 不存在该操作符 operators.put(objString,1); } }else if (obj instanceof JavaParser.PrimaryContext || obj instanceof JavaParser.VariableDeclaratorIdContext){ String objString=""; if(obj instanceof JavaParser.PrimaryContext){ JavaParser.PrimaryContext primaryContext = (JavaParser.PrimaryContext)obj; objString = primaryContext.getText(); }else{ JavaParser.VariableDeclaratorIdContext var = (JavaParser.VariableDeclaratorIdContext)obj; objString = var.getText(); } // 已经存在该操作数 if(operands.containsKey(objString)) { operands.put(objString,operands.get(objString)+1); }else { // 不存在该操作数 operands.put(objString,1); } }else{ // 不属于输出节点时,将其孩子放入队列 ParserRuleContext child = (ParserRuleContext)obj; for(int j=0;j<child.getChildCount();j++) { queue1.enqueue(child.getChild(j)); } } } } } } } catch (Exception e) { } } } } //添加方法实体 methodEntity.setControl_block_num(control_block_num); methodEntity.setMax_block_depth(max_block_depth); methodEntity.setExecStmt(execStmt); methodEntity.setLocalVarDecl(localVarDecl); // 操作符,操作数 计算 // 去除重复的三元运算符,重复的()[]{} operators.remove("?"); operators.remove("("); operators.remove("["); operators.remove("{"); // 去除点(点会被计算到操作符和操作数) 操作符. 操作数. operands.remove("."); operators.remove("."); int sumOperators=0; for (Map.Entry<String, Integer> entry : operators.entrySet()) { sumOperators+=operators.get(entry.getKey()); } methodEntity.setOperators(operators.size()); methodEntity.setSumOperators(sumOperators); int sumOperands=0; for (Map.Entry<String, Integer> entry : operands.entrySet()) { sumOperands+=operands.get(entry.getKey()); } methodEntity.setOperands(operands.size()); methodEntity.setSumOperands(sumOperands); //计算带参方法名 String nameWithPara ; int count=0; int paraNum=methodEntity.getPara_num(); nameWithPara = methodName+'('; if(paraNum!=0) { for(String paraType:methodEntity.para_class_list){ nameWithPara+=paraType; if(count==paraNum-1) { break; } count++; nameWithPara+=' '; } } nameWithPara+=')'; methodEntity.setNameWithPara(nameWithPara); singleCollect.addEntity(methodEntity); classEntity.addToMethodList(methodName); return methodName; } }
anticipasean/girakkafunc
func-core/src/main/java/cyclops/stream/spliterator/OnEmptySpliterator.java
<filename>func-core/src/main/java/cyclops/stream/spliterator/OnEmptySpliterator.java package cyclops.stream.spliterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; public class OnEmptySpliterator<T> extends Spliterators.AbstractSpliterator<T> implements CopyableSpliterator<T> { private final Spliterator<T> source; private final T value; private boolean found = false; private boolean sent = false; public OnEmptySpliterator(Spliterator<T> source, T value) { super(source.estimateSize(), source.characteristics() & Spliterator.ORDERED); this.source = source; this.value = value; } @Override public void forEachRemaining(Consumer<? super T> action) { source.forEachRemaining(e -> { found = true; action.accept(e); }); if (!found) { action.accept(value); sent = true; } } @Override public boolean tryAdvance(Consumer<? super T> action) { if (sent) { return false; } if (found) { return source.tryAdvance(action); } else { boolean result = source.tryAdvance(e -> { found = true; action.accept(e); }); if (!found) { sent = true; action.accept(value); } return result; } } @Override public Spliterator<T> copy() { return new OnEmptySpliterator<T>(CopyableSpliterator.copy(source), value); } }
estools2/esmangle
test/compare/push-assignments-through-sequences-2.expected.js
!function(a){a={},f(),a.p=0}()
dtrajko/HazelGameEngineSeries
Vulkan/src/engine/Print.h
<reponame>dtrajko/HazelGameEngineSeries #pragma once #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include "vulkan/SwapChain.h" #include <iostream> class Print { public: static void deviceExtensionSupport(std::vector<VkExtensionProperties> availableExtensions) { std::cout << std::endl; std::cout << "Device Extension Support: " << std::endl; for (const auto& extension : availableExtensions) { std::cout << "\t" << "extensionName: " << extension.extensionName << std::endl; } } static void printDeviceProperties( VkPhysicalDeviceProperties deviceProperties, VkPhysicalDeviceFeatures deviceFeatures, int score) { std::cout << std::endl; std::cout << "Device Properties" << std::endl; std::cout << "\t" << "deviceID: " << deviceProperties.deviceID << std::endl; std::cout << "\t" << "apiVersion: " << deviceProperties.apiVersion << std::endl; std::cout << "\t" << "deviceName: " << deviceProperties.deviceName << std::endl; std::cout << "\t" << "deviceType: " << deviceProperties.deviceType << std::endl; std::cout << "\t" << "driverVersion: " << deviceProperties.driverVersion << std::endl; std::cout << "\t" << "limits.bufferImageGranularity: " << deviceProperties.limits.bufferImageGranularity << std::endl; std::cout << "\t" << "limits.discreteQueuePriorities: " << deviceProperties.limits.discreteQueuePriorities << std::endl; std::cout << "\t" << "limits.framebufferColorSampleCounts: " << deviceProperties.limits.framebufferColorSampleCounts << std::endl; std::cout << "\t" << "..." << std::endl; std::cout << "\t" << "vendorID: " << deviceProperties.vendorID << std::endl; std::cout << "Device Features" << std::endl; std::cout << "\t" << "geometryShader: " << deviceFeatures.geometryShader << std::endl; std::cout << "\t" << "sparseBinding: " << deviceFeatures.sparseBinding << std::endl; std::cout << "\t" << "..." << std::endl; std::cout << "Physical device score: " << score << std::endl; } static void printSwapChainSupport(bool swapChainAdequate, SwapChainSupportDetails swapChainSupport) { std::cout << std::endl; std::cout << "SwapChain Support: " << std::endl; std::cout << "\t" << "swapChainAdequate: " << (swapChainAdequate ? "YES" : "NO") << std::endl; std::cout << "\t" << "Number of Formats: " << swapChainSupport.formats.size() << std::endl; for (VkSurfaceFormatKHR format : swapChainSupport.formats) { std::cout << "\t\t" << "Format: " << format.format << std::endl; } std::cout << "\t" << "Number of Presentation Modes: " << swapChainSupport.presentModes.size() << std::endl; for (VkPresentModeKHR presentMode : swapChainSupport.presentModes) { std::cout << "\t\t" << "Format: " << presentMode << std::endl; } } };
windystrife/UnrealEngine_NVIDIAGameWork
Engine/Source/ThirdParty/PhysX/APEX_1.4/common/include/ApexCollision.h
<gh_stars>1-10 /* * Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #ifndef APEX_COLLISION_H #define APEX_COLLISION_H #include "ApexDefs.h" #include "ApexUsingNamespace.h" #include "PxVec3.h" #include "PxMat33.h" namespace nvidia { namespace apex { struct Segment { PxVec3 p0; PxVec3 p1; }; struct Capsule : Segment { float radius; }; struct Triangle { Triangle(const PxVec3& a, const PxVec3& b, const PxVec3& c) : v0(a), v1(b), v2(c) {} PxVec3 v0; PxVec3 v1; PxVec3 v2; }; struct Box { PxVec3 center; PxVec3 extents; PxMat33 rot; }; bool capsuleCapsuleIntersection(const Capsule& worldCaps0, const Capsule& worldCaps1, float tolerance = 1.2); bool boxBoxIntersection(const Box& worldBox0, const Box& worldBox1); float APEX_pointTriangleSqrDst(const Triangle& triangle, const PxVec3& position); float APEX_segmentSegmentSqrDist(const Segment& seg0, const Segment& seg1, float* s, float* t); float APEX_pointSegmentSqrDist(const Segment& seg, const PxVec3& point, float* param = 0); uint32_t APEX_RayCapsuleIntersect(const PxVec3& origin, const PxVec3& dir, const Capsule& capsule, float s[2]); bool APEX_RayTriangleIntersect(const PxVec3& orig, const PxVec3& dir, const PxVec3& a, const PxVec3& b, const PxVec3& c, float& t, float& u, float& v); } // namespace apex } // namespace nvidia #endif // APEX_COLLISION_H
LayZhangGitHub/ZLBaseProject
ZLBaseProject/ZLBaseProject/Class/BaseProject/Base/View/BaseCollectionCell.h
<reponame>LayZhangGitHub/ZLBaseProject<filename>ZLBaseProject/ZLBaseProject/Class/BaseProject/Base/View/BaseCollectionCell.h // // BaseCollectionCell.h // ZLBaseProject // // Created by LayZhang on 2017/9/22. // Copyright © 2017年 Zhanglei. All rights reserved. // #import <UIKit/UIKit.h> @interface BaseCollectionCell : UICollectionViewCell @property (nonatomic, strong) id cellData; + (NSString *)cellIdentifier; + (NSNumber *)heightForCell:(id)cellData; + (NSNumber *)widthForCell:(id)cellData; + (instancetype)dequeueCellForCollection:(UICollectionView *)collectionView forIndexPath:(NSIndexPath *)indexPath; - (void)reloadData; - (void)cellAddSubview:(UIView *)view; @end
MikalaiMikalalai/ggrc-core
src/ggrc-client/js/components/issue/issue-main-content-wrapper/issue-main-content-wrapper.js
<reponame>MikalaiMikalalai/ggrc-core /* Copyright (C) 2020 Google Inc. Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ import canComponent from 'can-component'; import canMap from 'can-map'; import {isAllowedFor} from '../../../permission'; export default canComponent.extend({ tag: 'issue-main-content-wrapper', viewModel: canMap.extend({ define: { isInfoPaneReadonly: { get() { return !isAllowedFor('update', this.attr('instance')); }, }, disableIssueTrackerDependentFields: { get() { return this.attr('isIssueLinked') && this.attr('issueTrackerState') !== 'generateNew'; }, }, }, instance: {}, isIssueLinked: false, issueTrackerState: '', updateIssueTrackerState({state}) { this.attr('issueTrackerState', state); }, }), });
alexkarezin/iota-java
jota/src/main/java/org/iota/jota/builder/AbstractBuilder.java
<reponame>alexkarezin/iota-java package org.iota.jota.builder; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.iota.jota.config.Config; import org.iota.jota.config.types.EnvConfig; import org.iota.jota.config.types.IotaDefaultConfig; import org.iota.jota.config.types.PropertiesConfig; import org.iota.jota.store.PropertiesStore; import org.slf4j.Logger; /** * Naming chosen because of preventing confusion in the code * * @param <E> */ @SuppressWarnings("unchecked") public abstract class AbstractBuilder<T, E, F extends Config> { private Logger log; private Config config; public AbstractBuilder(Logger log) { this.log = log; } public E build() { try { generate(); } catch (Exception e) { //You must know that the message comes from creating/building here, so we just log the error log.error(e.getMessage()); e.printStackTrace(); return null; } return compile(); } protected abstract E compile(); protected abstract T generate() throws Exception; public T config(F config) { try { setConfig(config); } catch (Exception e) { // Huh? This can't happen since properties should already be loaded log.error(e.getMessage()); } return (T) this; } public T config(Properties properties) { try { setConfig(new PropertiesConfig(new PropertiesStore(properties))); } catch (Exception e) { // Huh? This can't happen since properties should already be loaded log.error(e.getMessage()); } return (T) this; } public T config(PropertiesConfig properties) { setConfig(properties); return (T) this; } protected List<F> getConfigs() throws Exception{ EnvConfig env = new EnvConfig(); ArrayList<F> array = new ArrayList<>(); array.add((F)env); if (config != null) { array.add((F) config); } array.add((F) new IotaDefaultConfig()); return array; } public Config getConfig() { return config; } private void setConfig(Config config) { this.config = config; } }
indykish/megam_api
lib/megam/core/subscriptions_collection.rb
module Megam class SubscriptionsCollection include Enumerable attr_reader :iterator def initialize @subscriptions = Array.new @subscriptions_by_name = Hash.new @insert_after_idx = nil end def all_subscriptions @subscriptions end def [](index) @subscriptions[index] end def []=(index, arg) is_megam_subscriptions(arg) @subscriptions[index] = arg @subscriptions_by_name[arg.account_id] = index end def <<(*args) args.flatten.each do |a| is_megam_subscriptions(a) @subscriptions << a @subscriptions_by_name[a.account_id] =@subscriptions.length - 1 end self end # 'push' is an alias method to << alias_method :push, :<< def insert(subscriptions) is_megam_subscriptions(subscriptions) if @insert_after_idx # in the middle of executing a run, so any predefs inserted now should # be placed after the most recent addition done by the currently executing # subscriptions @subscriptions.insert(@insert_after_idx + 1, subscriptions) # update name -> location mappings and register new subscriptions @subscriptions_by_name.each_key do |key| @subscriptions_by_name[key] += 1 if@subscriptions_by_name[key] > @insert_after_idx end @subscriptions_by_name[subscriptions.account_id] = @insert_after_idx + 1 @insert_after_idx += 1 else @subscriptions << subscriptions @subscriptions_by_name[subscriptions.account_id] =@subscriptions.length - 1 end end def each @subscriptions.each do |subscriptions| yield subscriptions end end def each_index @subscriptions.each_index do |i| yield i end end def empty? @subscriptions.empty? end def lookup(subscriptions) lookup_by = nil if Subscriptions.kind_of?(Megam::Subscriptions) lookup_by = subscriptions.account_id elsif subscriptions.kind_of?(String) lookup_by = subscriptions else raise ArgumentError, "Must pass a Megam::Subscriptions or String to lookup" end res =@subscriptions_by_name[lookup_by] unless res raise ArgumentError, "Cannot find a subscriptions matching #{lookup_by} (did you define it first?)" end @subscriptions[res] end def to_s @subscriptions.join(", ") end def for_json to_a.map { |item| item.to_s } end def to_json(*a) Megam::JSONCompat.to_json(for_json, *a) end def self.json_create(o) collection = self.new() o["results"].each do |subscriptions_list| subscriptions_array = subscriptions_list.kind_of?(Array) ? subscriptions_list : [ subscriptions_list ] subscriptions_array.each do |subscriptions| collection.insert(subscriptions) end end collection end private def is_megam_subscriptions(arg) unless arg.kind_of?(Megam::Subscriptions) raise ArgumentError, "Members must be Megam::subscriptions's" end true end end end
niello/deusexmachina
DEM/Low/src/System/Win32/OSWindowWin32.h
#pragma once #if DEM_PLATFORM_WIN32 #include <System/OSWindow.h> #include <algorithm> #define WIN32_LEAN_AND_MEAN #include <windows.h> // Win32 operating system window implementation namespace DEM::Sys { typedef Ptr<class COSWindowWin32> POSWindowWin32; class COSWindowWin32 : public COSWindow { RTTI_CLASS_DECL(DEM::Sys::COSWindowWin32, Core::CObject); protected: COSWindowWin32* pParent = nullptr; HWND hWnd = 0; HCURSOR hClientCursor = 0; // For resizing detection in WM_EXITSIZEMOVE U16 PrevWidth = 0; U16 PrevHeight = 0; bool ManualResizingInProgress = false; public: COSWindowWin32(HINSTANCE hInstance, ATOM aWndClass, COSWindowWin32* pParentWnd = nullptr); virtual ~COSWindowWin32(); virtual void SetTitle(const char* pTitle) override; virtual void SetIcon(const char* pIconName) override; virtual bool SetCursor(const char* pCursorName) override; virtual bool SetRect(const Data::CRect& NewRect, bool FullscreenMode = false) override; virtual bool SetInputFocus() override; virtual bool Show() override; virtual bool Hide() override; virtual void Close() override; virtual bool IsValid() const override { return !!hWnd; } virtual bool HasInputFocus() const override; virtual COSWindow* GetParent() const override { return pParent; } virtual CString GetTitle() const override; virtual bool GetCursorPosition(IPTR& OutX, IPTR& OutY) const override; void Minimize(); void Restore(); bool HandleWindowMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, LONG& OutResult); // Mainly for internal use bool GetAbsoluteXY(float XRel, float YRel, int& XAbs, int& YAbs) const; bool GetRelativeXY(int XAbs, int YAbs, float& XRel, float& YRel) const; bool SetTopmost(bool Topmost); HWND GetHWND() const { return hWnd; } LONG GetWin32Style() const; }; inline bool COSWindowWin32::GetAbsoluteXY(float XRel, float YRel, int& XAbs, int& YAbs) const { RECT r; if (!hWnd || !::GetClientRect(hWnd, &r)) FAIL; XAbs = (int)(XRel * std::max<LONG>(r.right - r.left, 1)); YAbs = (int)(YRel * std::max<LONG>(r.bottom - r.top, 1)); OK; } //--------------------------------------------------------------------- inline bool COSWindowWin32::GetRelativeXY(int XAbs, int YAbs, float& XRel, float& YRel) const { RECT r; if (!hWnd || !::GetClientRect(hWnd, &r)) FAIL; XRel = XAbs / float(std::max<LONG>(r.right - r.left, 1)); YRel = YAbs / float(std::max<LONG>(r.bottom - r.top, 1)); OK; } //--------------------------------------------------------------------- } #endif
nortix/lib.reviews
routes/teams.js
'use strict'; const escapeHTML = require('escape-html'); const TeamProvider = require('./handlers/team-provider'); const TeamJoinRequest = require('../models/team-join-request'); const getResourceErrorHandler = require('./handlers/resource-error-handler'); const render = require('./helpers/render'); const mlString = require('../models/helpers/ml-string'); const languages = require('../locales/languages'); const slugs = require('./helpers/slugs'); // Default routes for read, edit, add, delete let router = TeamProvider.bakeRoutes('team'); router.get('/team', (req, res) => res.redirect('/teams')); // Feed of all reviews router.get('/team/:id/feed', (req, res, next) => { const teamProvider = new TeamProvider(req, res, next, { action: 'feed', method: 'GET', id: req.params.id }); teamProvider.execute(); }); // Feed of all reviews before a given date router.get('/team/:id/feed/before/:utcisodate', (req, res, next) => { let offsetDate = new Date(req.params.utcisodate); if (!offsetDate || offsetDate == 'Invalid Date') offsetDate = null; let teamProvider = new TeamProvider(req, res, next, { action: 'feed', method: 'GET', id: req.params.id, offsetDate }); teamProvider.execute(); }); router.get('/team/:id/feed/atom', (req, res) => res.redirect(`/team/${req.params.id}/feed/atom/${req.locale}`) ); // Feed of all reviews in Atom format router.get('/team/:id/feed/atom/:language', (req, res, next) => { let { language } = req.params; if (!languages.isValid(language)) language = 'en'; let teamProvider = new TeamProvider(req, res, next, { action: 'feed', method: 'GET', id: req.params.id, format: 'atom', language }); teamProvider.execute(); }); // Show list of all teams router.get('/teams', function(req, res, next) { let teamProvider = new TeamProvider(req, res, next, { action: 'browse', method: 'GET' }); teamProvider.execute(); }); // Show membership roster for a specific team router.get('/team/:id/members', function(req, res, next) { let teamProvider = new TeamProvider(req, res, next, { action: 'members', method: 'GET', id: req.params.id }); teamProvider.execute(); }); // Moderator tool for managing requests which require moderator approval router.get('/team/:id/manage-requests', function(req, res, next) { let teamProvider = new TeamProvider(req, res, next, { action: 'manageRequests', method: 'GET', id: req.params.id }); teamProvider.execute(); }); // Moderator tool for managing requests which require moderator approval router.post('/team/:id/manage-requests', function(req, res, next) { let teamProvider = new TeamProvider(req, res, next, { action: 'manageRequests', method: 'POST', id: req.params.id }); teamProvider.execute(); }); // Process join requests, form is on team page itself router.post('/team/:id/join', function(req, res, next) { const { id } = req.params; slugs .resolveAndLoadTeam(req, res, id) .then(team => { team.populateUserInfo(req.user); if (!team.userCanJoin) return render.permissionError(req, res); if (team.rules && mlString.resolve(req.locale, team.rules.html) && !req.body['agree-to-rules']) { req.flash('joinErrors', req.__('must agree to team rules')); return res.redirect(`/team/${id}`); } if (team.modApprovalToJoin) { let teamJoinRequest = new TeamJoinRequest({ teamID: team.id, userID: req.user.id, requestMessage: escapeHTML(req.body['join-request-message'].trim()), requestDate: new Date() }); teamJoinRequest.save().then(() => { res.redirect(`/team/${id}`); }) .catch(next); // Problem saving join request } else { // No approval required, just add the new member team.members.push(req.user); team .saveAll() .then(() => { req.flash('pageMessages', req.__('welcome to the team')); res.redirect(`/team/${id}`); }) .catch(next); // Problem saving user changes } }) .catch(getResourceErrorHandler(req, res, next, 'team', id)); }); // Process leave requests, form is on team page itself router.post('/team/:id/leave', function(req, res, next) { const { id } = req.params; slugs .resolveAndLoadTeam(req, res, id) .then(team => { team.populateUserInfo(req.user); if (!team.userCanLeave) return render.permissionError(req, res); team.members = team.members.filter(member => member.id !== req.user.id); team.moderators = team.moderators.filter(moderator => moderator.id !== req.user.id); team .saveAll() .then(() => { req.flash('pageMessages', req.__('goodbye team')); res.redirect(`/team/${id}`); }) .catch(next); // Problem saving user changes }) .catch(getResourceErrorHandler(req, res, next, 'team', id)); }); module.exports = router;
Bhaskers-Blu-Org2/Network-Adapter-Class-Extension
netcx/translator/nxbouncebufferpool.hpp
<reponame>Bhaskers-Blu-Org2/Network-Adapter-Class-Extension // Copyright (C) Microsoft Corporation. All rights reserved. #pragma once #include <net/packet.h> #include <NxRingContext.hpp> class NxBounceBufferPool { public: NxBounceBufferPool( NET_RING_COLLECTION const & Rings, NET_EXTENSION const & VirtualAddressExtension, NET_EXTENSION const & LogicalAddressExtension ); ~NxBounceBufferPool( void ); NTSTATUS Initialize( _In_ NET_CLIENT_DISPATCH const &ClientDispatch, _In_ NET_CLIENT_ADAPTER_DATAPATH_CAPABILITIES &DatapathCapabilities, _In_ size_t NumberOfBuffers ); bool BounceNetBuffer( _In_ NET_BUFFER const &NetBuffer, _Inout_ NET_PACKET &NetPacket ); void FreeBounceBuffers( _Inout_ NET_PACKET &NetPacket ); private: NxRingContext m_fragmentContext; NET_EXTENSION const & m_virtualAddressExtension; NET_EXTENSION const & m_logicalAddressExtension; NET_CLIENT_BUFFER_POOL m_bufferPool = nullptr; NET_CLIENT_BUFFER_POOL_DISPATCH const *m_bufferPoolDispatch = nullptr; NET_RING_COLLECTION const * m_rings = nullptr; size_t m_bufferSize = 0; size_t m_txPayloadBackfill = 0; };
nlowe/aws-sdk-go-v2
service/ssm/api_op_GetConnectionStatus.go
<gh_stars>0 // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ssm import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/internal/awsutil" ) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetConnectionStatusRequest type GetConnectionStatusInput struct { _ struct{} `type:"structure"` // The ID of the instance. // // Target is a required field Target *string `min:"1" type:"string" required:"true"` } // String returns the string representation func (s GetConnectionStatusInput) String() string { return awsutil.Prettify(s) } // Validate inspects the fields of the type to determine if they are valid. func (s *GetConnectionStatusInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetConnectionStatusInput"} if s.Target == nil { invalidParams.Add(aws.NewErrParamRequired("Target")) } if s.Target != nil && len(*s.Target) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Target", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetConnectionStatusResponse type GetConnectionStatusOutput struct { _ struct{} `type:"structure"` // The status of the connection to the instance. For example, 'Connected' or // 'Not Connected'. Status ConnectionStatus `type:"string" enum:"true"` // The ID of the instance to check connection status. Target *string `min:"1" type:"string"` } // String returns the string representation func (s GetConnectionStatusOutput) String() string { return awsutil.Prettify(s) } const opGetConnectionStatus = "GetConnectionStatus" // GetConnectionStatusRequest returns a request value for making API operation for // Amazon Simple Systems Manager (SSM). // // Retrieves the Session Manager connection status for an instance to determine // whether it is connected and ready to receive Session Manager connections. // // // Example sending a request using GetConnectionStatusRequest. // req := client.GetConnectionStatusRequest(params) // resp, err := req.Send(context.TODO()) // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetConnectionStatus func (c *Client) GetConnectionStatusRequest(input *GetConnectionStatusInput) GetConnectionStatusRequest { op := &aws.Operation{ Name: opGetConnectionStatus, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &GetConnectionStatusInput{} } req := c.newRequest(op, input, &GetConnectionStatusOutput{}) return GetConnectionStatusRequest{Request: req, Input: input, Copy: c.GetConnectionStatusRequest} } // GetConnectionStatusRequest is the request type for the // GetConnectionStatus API operation. type GetConnectionStatusRequest struct { *aws.Request Input *GetConnectionStatusInput Copy func(*GetConnectionStatusInput) GetConnectionStatusRequest } // Send marshals and sends the GetConnectionStatus API request. func (r GetConnectionStatusRequest) Send(ctx context.Context) (*GetConnectionStatusResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &GetConnectionStatusResponse{ GetConnectionStatusOutput: r.Request.Data.(*GetConnectionStatusOutput), response: &aws.Response{Request: r.Request}, } return resp, nil } // GetConnectionStatusResponse is the response type for the // GetConnectionStatus API operation. type GetConnectionStatusResponse struct { *GetConnectionStatusOutput response *aws.Response } // SDKResponseMetdata returns the response metadata for the // GetConnectionStatus request. func (r *GetConnectionStatusResponse) SDKResponseMetdata() *aws.Response { return r.response }
tormath1/jclouds
apis/ec2/src/main/java/org/jclouds/ec2/domain/Subnet.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.jclouds.ec2.domain; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.collect.ImmutableMap; /** * Amazon EC2 VPCs contain one or more subnets. * * @see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html" >doc</a> */ public final class Subnet { public static enum State { /** * The subnet is available for use. */ AVAILABLE, /** * The subnet is not yet available for use. */ PENDING, UNRECOGNIZED; public String value() { return name().toLowerCase(); } public static State fromValue(String v) { try { return valueOf(v.toUpperCase()); } catch (IllegalArgumentException e) { return UNRECOGNIZED; } } } private final String subnetId; private final State subnetState; private final String vpcId; private final String cidrBlock; private final int availableIpAddressCount; private final String availabilityZone; private final Map<String, String> tags; private Subnet(String subnetId, State subnetState, String vpcId, String cidrBlock, int availableIpAddressCount, String availabilityZone, ImmutableMap<String, String> tags) { this.subnetId = checkNotNull(subnetId, "subnetId"); this.subnetState = checkNotNull(subnetState, "subnetState for %s", subnetId); this.vpcId = checkNotNull(vpcId, "vpcId for %s", subnetId); this.cidrBlock = checkNotNull(cidrBlock, "cidrBlock for %s", subnetId); this.availableIpAddressCount = availableIpAddressCount; this.availabilityZone = checkNotNull(availabilityZone, "availabilityZone for %s", subnetId); this.tags = checkNotNull(tags, "tags for %s", subnetId); } /** * The subnet ID, ex. subnet-c5473ba8 */ public String getSubnetId() { return subnetId; } /** * The subnet state - either available or pending. */ public State getSubnetState() { return subnetState; } /** * The vpc ID this subnet belongs to. */ public String getVpcId() { return vpcId; } /** * The CIDR block for this subnet. */ public String getCidrBlock() { return cidrBlock; } /** * The number of available IPs in this subnet. */ public int getAvailableIpAddressCount() { return availableIpAddressCount; } /** * The availability zone this subnet is in. */ public String getAvailabilityZone() { return availabilityZone; } /** * Tags that are attached to this subnet. */ public Map<String, String> getTags() { return tags; } @Override public int hashCode() { return Objects.hashCode(subnetId, vpcId, availabilityZone); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Subnet that = Subnet.class.cast(obj); return Objects.equal(this.subnetId, that.subnetId) && Objects.equal(this.vpcId, that.vpcId) && Objects.equal(this.availabilityZone, that.availabilityZone); } @Override public String toString() { return string().toString(); } private ToStringHelper string() { return MoreObjects.toStringHelper(this).omitNullValues().add("subnetId", subnetId).add("subnetState", subnetState) .add("vpcId", vpcId).add("cidrBlock", cidrBlock).add("availableIpAddressCount", availableIpAddressCount) .add("availabilityZone", availabilityZone).add("tags", tags); } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return builder().from(this); } public static final class Builder { private String subnetId; private State subnetState; private String vpcId; private String cidrBlock; private int availableIpAddressCount; private String availabilityZone; private ImmutableMap.Builder<String, String> tags = ImmutableMap.<String, String> builder(); /** * @see Subnet#getSubnetId() */ public Builder subnetId(String subnetId) { this.subnetId = subnetId; return this; } /** * @see Subnet#getState() */ public Builder subnetState(State subnetState) { this.subnetState = subnetState; return this; } /** * @see Subnet#getVpcId() */ public Builder vpcId(String vpcId) { this.vpcId = vpcId; return this; } /** * @see Subnet#getCidrBlock() */ public Builder cidrBlock(String cidrBlock) { this.cidrBlock = cidrBlock; return this; } /** * @see Subnet#getAvailableIpAddressCount() */ public Builder availableIpAddressCount(int availableIpAddressCount) { this.availableIpAddressCount = availableIpAddressCount; return this; } /** * @see Subnet#getAvailabilityZone() */ public Builder availabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; return this; } /** * @see Subnet#getTags() */ public Builder tags(Map<String, String> tags) { this.tags.putAll(checkNotNull(tags, "tags")); return this; } /** * @see Subnet#getTags() */ public Builder tag(String key) { return tag(key, ""); } /** * @see Subnet#getTags() */ public Builder tag(String key, String value) { this.tags.put(checkNotNull(key, "key"), checkNotNull(value, "value")); return this; } public Subnet build() { return new Subnet(subnetId, subnetState, vpcId, cidrBlock, availableIpAddressCount, availabilityZone, tags.build()); } public Builder from(Subnet in) { return this.subnetId(in.getSubnetId()).subnetState(in.getSubnetState()).vpcId(in.getVpcId()) .cidrBlock(in.getCidrBlock()).availableIpAddressCount(in.getAvailableIpAddressCount()) .availabilityZone(in.getAvailabilityZone()).tags(in.getTags()); } } }
timgates42/bokeh
sphinx/source/docs/user_guide/examples/interaction_radio_button_group.py
<filename>sphinx/source/docs/user_guide/examples/interaction_radio_button_group.py from bokeh.io import output_file, show from bokeh.models import RadioButtonGroup output_file("radio_button_group.html") radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) show(radio_button_group)
hananaharonof/payment
db-master/src/main/java/org/hananaharonof/payment/DbMasterApplication.java
<gh_stars>0 package org.hananaharonof.payment; import lombok.extern.slf4j.Slf4j; import org.hananaharonof.payment.service.PaymentCrudService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Slf4j @EnableJpaRepositories @SpringBootApplication public class DbMasterApplication { @Autowired private PaymentCrudService paymentCrudService; public static void main(String[] args) { SpringApplication.run(DbMasterApplication.class, args); } }
bcleveland1022/opensphere
src/os/ol/control/mousepositioncontrol.js
<reponame>bcleveland1022/opensphere goog.provide('os.ol.control.MousePosition'); goog.require('goog.events.EventType'); goog.require('ol.ViewHint'); goog.require('ol.control.MousePosition'); goog.require('ol.coordinate'); goog.require('os.bearing'); goog.require('os.config.DisplaySettings'); goog.require('os.config.Settings'); goog.require('os.geo'); goog.require('os.ui.location'); goog.require('os.ui.user.settings.LocationSetting'); /** * Extends the OpenLayers 3 MousePosition control to allow switching between different coordinate formats. * * @param {olx.control.MousePositionOptions=} opt_options Mouse position options. * @extends {ol.control.MousePosition} * @constructor */ os.ol.control.MousePosition = function(opt_options) { opt_options = opt_options || {}; opt_options.undefinedHTML = 'No coordinate'; os.ol.control.MousePosition.base(this, 'constructor', opt_options); /** * @type {string} * @private */ this.format_ = 'deg'; /** * @type {Object<string, ol.CoordinateFormatType>} * @private */ this.formatMap_ = os.ol.control.MousePosition.FormatMap; /** * @type {?Event} * @private */ this.lastBrowserEvent_ = null; if (opt_options && opt_options.useSettings) { os.settings.listen(os.ui.location.LocationSetting.POSITION, this.onFormatChange_, false, this); this.format_ = /** @type {string} */ (os.settings.get( os.ui.location.LocationSetting.POSITION, os.ui.location.Format.DEG)); } this.setFormat_(this.format_); /** * @type {goog.events.Key} * @private */ this.clickListenKey_ = null; if (this.element) { this.clickListenKey_ = goog.events.listen(this.element, goog.events.EventType.CLICK, this.onMouseClick_, false, this); } os.unit.UnitManager.getInstance().listen(goog.events.EventType.PROPERTYCHANGE, this.onUnitChange_, false, this); os.settings.listen(os.bearing.BearingSettingsKeys.BEARING_TYPE, this.onBearingChange_, false, this); }; goog.inherits(os.ol.control.MousePosition, ol.control.MousePosition); /** * @param {ol.Coordinate|undefined} coordinate * @return {string} */ os.ol.control.MousePosition.LON_LAT_FORMAT = function(coordinate) { if (!coordinate) { return 'No coordinate'; } // fix the number of decimal places var lon = os.geo.padCoordinate(os.geo2.normalizeLongitude( coordinate[0], undefined, undefined, os.proj.EPSG4326), true, 5); var lat = os.geo.padCoordinate(coordinate[1], false, 5); if (lon.length < 10) { lon = '+' + lon; } if (lat.length < 9) { lat = '+' + lat; } return lat + ', ' + lon + ' (DD)' + os.ol.control.MousePosition.elevation(coordinate); }; /** * @param {ol.Coordinate} coordinate * @return {string} */ os.ol.control.MousePosition.MGRS_FORMAT = function(coordinate) { return osasm.toMGRS(coordinate) + ' (MGRS)' + os.ol.control.MousePosition.elevation(coordinate); }; /** * @param {ol.Coordinate} coordinate * @return {string} */ os.ol.control.MousePosition.SEXAGESIMAL_FORMAT = function(coordinate) { return (os.geo.toSexagesimal(coordinate[1], false, false) + ' ' + os.geo.toSexagesimal( os.geo2.normalizeLongitude(coordinate[0], undefined, undefined, os.proj.EPSG4326), true, false) + ' (DMS)').replace(/°/g, '&deg;') + os.ol.control.MousePosition.elevation(coordinate); }; /** * @param {ol.Coordinate} coordinate * @return {string} */ os.ol.control.MousePosition.DDM = function(coordinate) { return (os.geo.toDegreesDecimalMinutes(coordinate[1], false, false) + ' ' + os.geo.toDegreesDecimalMinutes( os.geo2.normalizeLongitude(coordinate[0], undefined, undefined, os.proj.EPSG4326), true, false) + ' (DDM)') .replace(/°/g, '&deg;') + os.ol.control.MousePosition.elevation(coordinate); }; /** * If coordinate has elevation, it will add the elevation to the coordinate string. * @param {ol.Coordinate} coordinate The coordinate. * @return {string} The coordinate string with elevation appended to it if available. */ os.ol.control.MousePosition.elevation = function(coordinate) { let coordString = ''; if (coordinate && coordinate.length > 2 && os.settings.get(os.config.DisplaySetting.ENABLE_TERRAIN)) { const um = os.unit.UnitManager.getInstance(); const elevation = um.formatToBestFit('distance', coordinate[2], 'm', um.getBaseSystem(), 2); coordString = ' ' + elevation; } return coordString; }; /** * @type {!Object<string, ol.CoordinateFormatType>} */ os.ol.control.MousePosition.FormatMap = { 'deg': os.ol.control.MousePosition.LON_LAT_FORMAT, 'dms': os.ol.control.MousePosition.SEXAGESIMAL_FORMAT, 'ddm': os.ol.control.MousePosition.DDM, 'mgrs': os.ol.control.MousePosition.MGRS_FORMAT }; /** * @inheritDoc */ os.ol.control.MousePosition.prototype.disposeInternal = function() { os.settings.unlisten(os.ui.location.LocationSetting.POSITION, this.onFormatChange_, false, this); if (this.clickListenKey_) { goog.events.unlistenByKey(this.clickListenKey_); this.clickListenKey_ = null; } os.unit.UnitManager.getInstance().unlisten(goog.events.EventType.PROPERTYCHANGE, this.onUnitChange_, false, this); os.settings.unlisten(os.bearing.BearingSettingsKeys.BEARING_TYPE, this.onBearingChange_, false, this); os.ol.control.MousePosition.base(this, 'disposeInternal'); }; /** * @param {os.events.SettingChangeEvent} event * @private */ os.ol.control.MousePosition.prototype.onFormatChange_ = function(event) { if (event && typeof event.newVal == 'string') { this.setFormat_(event.newVal); } }; /** * Updates the UI to reflect the new unit system. * * @param {os.events.PropertyChangeEvent} event * @private */ os.ol.control.MousePosition.prototype.onUnitChange_ = function(event) { this.setFormat_(this.format_); }; /** * Set the format for the control. * * @param {string} format * @private */ os.ol.control.MousePosition.prototype.setFormat_ = function(format) { if (!(format in this.formatMap_)) { format = 'deg'; } var formatter = this.formatMap_[format]; this.setCoordinateFormat(formatter); if (format !== this.format_) { this.format_ = format; var settingsFormats = goog.object.getValues(os.ui.location.Format); if (settingsFormats.indexOf(this.format_) > -1) { // only put this in settings if it is one of the supported settings formats os.settings.set(os.ui.location.LocationSetting.POSITION, this.format_); } } if (this.lastBrowserEvent_) { os.ol.control.MousePosition.superClass_.handleMouseMove.call(this, this.lastBrowserEvent_); } }; /** * @inheritDoc */ os.ol.control.MousePosition.prototype.handleMouseMove = function(event) { os.ol.control.MousePosition.base(this, 'handleMouseMove', event); this.lastBrowserEvent_ = event; }; /** * @inheritDoc * @suppress {accessControls} */ os.ol.control.MousePosition.prototype.updateHTML_ = function(pixel) { var map = this.getMap(); if (map && map.getView().getHints()[ol.ViewHint.INTERACTING] <= 0) { os.ol.control.MousePosition.superClass_.updateHTML_.call(this, pixel); } }; /** * @inheritDoc */ os.ol.control.MousePosition.prototype.handleMouseOut = function(event) { // do nothing. this causes the last mouse position to always be displayed instead of clearing the position. }; /** * @param {goog.events.Event} event * @private */ os.ol.control.MousePosition.prototype.onMouseClick_ = function(event) { var keys = goog.object.getKeys(this.formatMap_); var index = keys.indexOf(this.format_); if (index > keys.length) { index = 0; } var newFormat = keys[index + 1]; this.setFormat_(newFormat); if (this.lastBrowserEvent_) { os.ol.control.MousePosition.superClass_.handleMouseMove.call(this, this.lastBrowserEvent_); } }; /** * Return the position of the mouse pointer * * @param {ol.Coordinate=} opt_coord The coordinate * @return {string} * @suppress {accessControls} to allow access to the map and last pixel */ os.ol.control.MousePosition.prototype.getPositionString = function(opt_coord) { var coord = opt_coord || this.map_.getCoordinateFromPixel(this.lastMouseMovePixel_); if (coord) { var s = ''; coord = ol.proj.toLonLat(coord, this.map_.getView().getProjection()); for (var key in this.formatMap_) { var formatter = this.formatMap_[key]; s += formatter(coord) + '\n'; } // chop off the last newline s = s.substring(0, s.length - 1); return s.replace(/&deg;/g, '°'); } else { return ''; } }; /** * Forces an update of the displayed text to show the new bearing. * * @private */ os.ol.control.MousePosition.prototype.onBearingChange_ = function() { if (this.lastBrowserEvent_) { this.handleMouseMove(this.lastBrowserEvent_); } }; /** * Get the element * * @return {Element} */ os.ol.control.MousePosition.prototype.getElement = function() { return this.element; };
jo3-l/cp-practice
src/main/java/binarysearch/PeekableIterator.java
package binarysearch; public class PeekableIterator { private int idx = -1; private int[] nums; public PeekableIterator(int[] nums) { this.nums = nums; } public int peek() { return nums[idx + 1]; } public int next() { return nums[++idx]; } public boolean hasnext() { return idx != nums.length - 1; } }
ThePreviousOne/SVG-Android
svg-sample/src/main/java/com/github/megatronking/svg/sample/drawables/ic_android_red_17.java
package com.github.megatronking.svg.sample.drawables; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import com.github.megatronking.svg.support.SVGRenderer; /** * AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * SVG-Generator. It should not be modified by hand. */ public class ic_android_red_17 extends SVGRenderer { public ic_android_red_17(Context context) { super(context); mAlpha = 1.0f; mWidth = dip2px(48.0f); mHeight = dip2px(48.0f); } @Override public void render(Canvas canvas, int w, int h, ColorFilter filter) { final float scaleX = w / 24.0f; final float scaleY = h / 24.0f; mPath.reset(); mRenderPath.reset(); mFinalPathMatrix.setValues(new float[]{0.309017f, 0.95105654f, -3.120883f, -0.95105654f, 0.309017f, 19.704475f, 0.0f, 0.0f, 1.0f}); mFinalPathMatrix.postScale(scaleX, scaleY); mPath.moveTo(6.0f, 18.0f); mPath.rCubicTo(0.0f, 0.55f, 0.45f, 1.0f, 1.0f, 1.0f); mPath.rLineTo(1.0f, 0f); mPath.rLineTo(0f, 3.5f); mPath.rCubicTo(0.0f, 0.83f, 0.67f, 1.5f, 1.5f, 1.5f); mPath.rCubicTo(0.8299999f, 0.0f, 1.5f, -0.67f, 1.5f, -1.5f); mPath.lineTo(11.0f, 19.0f); mPath.rLineTo(2.0f, 0f); mPath.rLineTo(0f, 3.5f); mPath.rCubicTo(0.0f, 0.83f, 0.67f, 1.5f, 1.5f, 1.5f); mPath.rCubicTo(0.8299999f, 0.0f, 1.5f, -0.67f, 1.5f, -1.5f); mPath.lineTo(16.0f, 19.0f); mPath.rLineTo(1.0f, 0f); mPath.rCubicTo(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f); mPath.lineTo(18.0f, 8.0f); mPath.lineTo(6.0f, 8.0f); mPath.rLineTo(0f, 10.0f); mPath.close(); mPath.moveTo(6.0f, 18.0f); mPath.moveTo(3.5f, 8.0f); mPath.cubicTo(2.67f, 8.0f, 2.0f, 8.67f, 2.0f, 9.5f); mPath.rLineTo(0f, 7.0f); mPath.rCubicTo(0.0f, 0.83f, 0.67f, 1.5f, 1.5f, 1.5f); mPath.cubicTo(4.33f, 18.0f, 5.0f, 17.33f, 5.0f, 16.5f); mPath.rLineTo(0f, -7.0f); mPath.cubicTo(5.0f, 8.67f, 4.33f, 8.0f, 3.5f, 8.0f); mPath.close(); mPath.moveTo(3.5f, 8.0f); mPath.moveTo(20.5f, 8.0f); mPath.rCubicTo(-0.83f, 0.0f, -1.5f, 0.67f, -1.5f, 1.5f); mPath.rLineTo(0f, 7.0f); mPath.rCubicTo(0.0f, 0.83f, 0.67f, 1.5f, 1.5f, 1.5f); mPath.rCubicTo(0.8299999f, 0.0f, 1.5f, -0.67f, 1.5f, -1.5f); mPath.rLineTo(0f, -7.0f); mPath.rCubicTo(0.0f, -0.83f, -0.67f, -1.5f, -1.5f, -1.5f); mPath.close(); mPath.moveTo(20.5f, 8.0f); mPath.moveTo(15.53f, 2.16f); mPath.rLineTo(1.3f, -1.3f); mPath.rCubicTo(0.2f, -0.2f, 0.2f, -0.51f, 0.0f, -0.71f); mPath.rCubicTo(-0.2f, -0.2f, -0.51f, -0.2f, -0.71f, 0.0f); mPath.rLineTo(-1.48f, 1.48f); mPath.cubicTo(13.85f, 1.23f, 12.95f, 1.0f, 12.0f, 1.0f); mPath.rCubicTo(-0.96f, 0.0f, -1.86f, 0.23f, -2.66f, 0.63f); mPath.lineTo(7.85f, 0.15f); mPath.rCubicTo(-0.2f, -0.2f, -0.51f, -0.2f, -0.71f, 0.0f); mPath.rCubicTo(-0.2f, 0.2f, -0.2f, 0.51f, 0.0f, 0.71f); mPath.rLineTo(1.31f, 1.31f); mPath.cubicTo(6.97f, 3.26f, 6.0f, 5.01f, 6.0f, 7.0f); mPath.rLineTo(12.0f, 0f); mPath.rCubicTo(0.0f, -1.99f, -0.97f, -3.75f, -2.47f, -4.84f); mPath.close(); mPath.moveTo(15.53f, 2.16f); mPath.moveTo(10.0f, 5.0f); mPath.lineTo(9.0f, 5.0f); mPath.lineTo(9.0f, 4.0f); mPath.rLineTo(1.0f, 0f); mPath.rLineTo(0f, 1.0f); mPath.close(); mPath.moveTo(10.0f, 5.0f); mPath.moveTo(15.0f, 5.0f); mPath.rLineTo(-1.0f, 0f); mPath.lineTo(14.0f, 4.0f); mPath.rLineTo(1.0f, 0f); mPath.rLineTo(0f, 1.0f); mPath.close(); mPath.moveTo(15.0f, 5.0f); mRenderPath.addPath(mPath, mFinalPathMatrix); if (mFillPaint == null) { mFillPaint = new Paint(); mFillPaint.setStyle(Paint.Style.FILL); mFillPaint.setAntiAlias(true); } mFillPaint.setColor(applyAlpha(-65536, 1.0f)); mFillPaint.setColorFilter(filter); canvas.drawPath(mRenderPath, mFillPaint); } }
mitre-icarus/ICArUS-Challenge-Problem-Software-and-Data
src/main/java/org/mitre/icarus/cps/app/widgets/video/VideoControlPanel.java
<reponame>mitre-icarus/ICArUS-Challenge-Problem-Software-and-Data /* * NOTICE * This software was produced for the office of the Director of National Intelligence (ODNI) * Intelligence Advanced Research Projects Activity (IARPA) ICArUS program, * BAA number IARPA-BAA-10-04, under contract 2009-0917826-016, and is subject * to the Rights in Data-General Clause 52.227-14, Alt. IV (DEC 2007). * * This software and data is provided strictly to support demonstrations of ICArUS challenge problems * and to assist in the development of cognitive-neuroscience architectures. It is not intended to be used * in operational systems or environments. * * Copyright (C) 2015 The MITRE Corporation. All Rights Reserved. * */ package org.mitre.icarus.cps.app.widgets.video; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import org.mitre.icarus.cps.app.widgets.ImageManager; import uk.co.caprica.vlcj.player.MediaPlayer; import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter; /** * Panel with playback controls to control a video in a VideoPanel. * * @author <NAME> * */ public class VideoControlPanel extends JPanel { /** * */ private static final long serialVersionUID = -7815424134291524454L; private JButton restartButton; private JButton pauseButton; private JButton forwardButton; private JButton rewindButton; private JLabel timeLabel; private JSlider slider; private MediaPlayer mediaPlayer; private boolean forwarding; private boolean rewinding; private boolean sliderAccessed; private boolean paused = false; public VideoControlPanel(MediaPlayer mediaPlayer) { this.mediaPlayer = mediaPlayer; mediaPlayer.setVolume(200); mediaPlayer.addMediaPlayerEventListener(new MediaPlayerEventAdapter() { /* (non-Javadoc) * @see uk.co.caprica.vlcj.player.MediaPlayerEventAdapter#positionChanged(uk.co.caprica.vlcj.player.MediaPlayer, float) */ @Override public void positionChanged(MediaPlayer mediaPlayer, float newPosition) { if(!sliderAccessed) { //System.out.println("Should not be getting here"); long percentComplete = Math.round((double)mediaPlayer.getTime() / (double)mediaPlayer.getLength() * 100.00); slider.setValue((int)percentComplete); } String labelText = millisecondsToTimeStr((int)mediaPlayer.getTime()) + " / " + millisecondsToTimeStr((int)mediaPlayer.getLength()); timeLabel.setText(labelText); } }); this.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.fill = GridBagConstraints.BOTH; constraints.weightx = 1.0; constraints.weighty = 1.0; JPanel timePanel = new JPanel(); timePanel.setLayout(new FlowLayout()); timeLabel = new JLabel("--:-- / --:--"); timePanel.add(timeLabel); slider = new JSlider(); slider.addMouseListener(new MouseAdapter() { /* (non-Javadoc) * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent) */ @Override public void mousePressed(MouseEvent arg0) { sliderAccessed = true; } /* (non-Javadoc) * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent) */ @Override public void mouseReleased(MouseEvent event) { sliderAccessed = false; float percentage = (float)slider.getValue() / (float)slider.getMaximum(); getMediaPlayer().setPosition(percentage); } }); timePanel.add(slider); this.add(timePanel, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.fill = GridBagConstraints.BOTH; constraints.weightx = 1.0; constraints.weighty = 1.0; JPanel controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); restartButton = new JButton("Restart"); restartButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { getMediaPlayer().stop(); getMediaPlayer().play(); paused = false; pauseButton.setText("Pause"); pauseButton.setIcon(ImageManager.getImageIcon(ImageManager.CONTROL_PAUSE_ICON)); } }); pauseButton = new JButton("Pause"); pauseButton.setIcon(ImageManager.getImageIcon(ImageManager.CONTROL_PAUSE_ICON)); pauseButton.setPreferredSize(pauseButton.getPreferredSize()); pauseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { getMediaPlayer().pause(); paused = !paused; if(!paused) { pauseButton.setText("Pause"); pauseButton.setIcon(ImageManager.getImageIcon(ImageManager.CONTROL_PAUSE_ICON)); } else { pauseButton.setText("Play"); pauseButton.setIcon(ImageManager.getImageIcon(ImageManager.CONTROL_PLAY_ICON)); } } }); rewindButton = new JButton("Rewind"); rewindButton.setIcon(ImageManager.getImageIcon(ImageManager.CONTROL_REWIND_ICON)); rewindButton.addMouseListener(new MouseAdapter() { /* (non-Javadoc) * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent) */ @Override public void mousePressed(MouseEvent event) { rewinding = true; SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { //mediaPlayer.pause(); while(rewinding) { float updatedPosition = getMediaPlayer().getPosition() - .01f; if(updatedPosition < 0.0f) { updatedPosition = 0.0f; } getMediaPlayer().setPosition(updatedPosition); final int sliderPosition = Math.round(updatedPosition * 100); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { slider.setValue(sliderPosition); } }); Thread.sleep(25); } return null; } }; worker.execute(); } /* (non-Javadoc) * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent) */ @Override public void mouseReleased(MouseEvent event) { rewinding = false; } }); forwardButton = new JButton("Forward"); forwardButton.setIcon(ImageManager.getImageIcon(ImageManager.CONTROL_FAST_FORWARD_ICON)); forwardButton.addMouseListener(new MouseAdapter() { /* (non-Javadoc) * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent) */ @Override public void mousePressed(MouseEvent event) { forwarding = true; SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { //mediaPlayer.pause(); while(forwarding) { float updatedPosition = getMediaPlayer().getPosition() + .01f; if(updatedPosition > 1.0f) { updatedPosition = 1.0f; } getMediaPlayer().setPosition(updatedPosition); final int sliderPosition = Math.round(updatedPosition * 100); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { slider.setValue(sliderPosition); } }); Thread.sleep(25); } return null; } }; worker.execute(); } /* (non-Javadoc) * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent) */ @Override public void mouseReleased(MouseEvent event) { forwarding = false; } }); controlPanel.add(restartButton); controlPanel.add(pauseButton); controlPanel.add(rewindButton); controlPanel.add(forwardButton); this.add(controlPanel, constraints); } private String millisecondsToTimeStr(int milliseconds) { int minutes = milliseconds / 60000; int remainingMilliseconds = milliseconds % 60000; int seconds = remainingMilliseconds / 1000; String strMinutes = String.valueOf(minutes); if(minutes < 10) { strMinutes = "0" + strMinutes; } String strSeconds = String.valueOf(seconds); if(seconds < 10) { strSeconds = "0" + strSeconds; } return strMinutes + ":" + strSeconds; } /** * @return the mediaPlayer */ public MediaPlayer getMediaPlayer() { return mediaPlayer; } }
pia-foss/extension-chrome
src/js/chromesettings/webrtc.js
<filename>src/js/chromesettings/webrtc.js import ChromeSetting from '@chromesettings/chromesetting'; class WebRTCSetting extends ChromeSetting { constructor() { super(chrome.privacy.network.webRTCIPHandlingPolicy); // bindings this.init = this.init.bind(this); this.onChange = this.onChange.bind(this); // functions this.applySetting = this.createApplySetting( 'disable_non_proxied_udp', 'webrtc', 'block', ); this.clearSetting = this.createClearSetting( 'webrtc', 'unblock', ); // init this.settingID = 'preventwebrtcleak'; this.settingDefault = false; } init() { this.blockable = chrome.privacy.network.webRTCIPHandlingPolicy !== undefined; super.init(); } onChange(details) { this.levelOfControl = details.levelOfControl; this.blocked = (details.value === 'disable_non_proxied_udp'); } } export default WebRTCSetting;
llnforest/jt808
src/main/java/org/yzh/framework/mvc/AbstractHandlerMapping.java
<gh_stars>1-10 package org.yzh.framework.mvc; import org.apache.commons.lang3.StringUtils; import org.yzh.framework.mvc.annotation.AsyncBatch; import org.yzh.framework.mvc.annotation.Mapping; import org.yzh.framework.mvc.handler.AsyncBatchHandler; import org.yzh.framework.mvc.handler.Handler; import org.yzh.framework.mvc.handler.SimpleHandler; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * @author yezhihao * @home https://gitee.com/yezhihao/jt808-server */ public abstract class AbstractHandlerMapping implements HandlerMapping { private final Map<String, Handler> handlerMap = new HashMap(60); protected synchronized void registerHandlers(Object bean) { Class<?> beanClass = bean.getClass(); Method[] methods = beanClass.getDeclaredMethods(); if (methods == null) return; for (Method method : methods) { Mapping mapping = method.getAnnotation(Mapping.class); if (mapping != null) { String desc = mapping.desc(); String[] types = mapping.types(); AsyncBatch asyncBatch = method.getAnnotation(AsyncBatch.class); Handler handler; if (asyncBatch != null) { handler = new AsyncBatchHandler(bean, method, desc, asyncBatch.poolSize(), asyncBatch.maxElements(), asyncBatch.maxWait()); } else { handler = new SimpleHandler(bean, method, desc); } for (String type : types) { handlerMap.put(type, handler); } } } } public Handler getHandler(int messageId) { String msgId = "0x"+ StringUtils.leftPad(Integer.toHexString(messageId),4,"0"); return handlerMap.get("0x"+msgId); } public Handler getHandler(String messageId) { return handlerMap.get(messageId); } }
CyberSys/coreclr-mono
src/pal/tests/palsuite/common/pal_stdclib.h
<reponame>CyberSys/coreclr-mono // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*============================================================================ ** ** Source: pal_stdlib.h ** ** Purpose: ** ** **==========================================================================*/ #ifndef __PAL_STDCLIB_H__ #define __PAL_STDCLIB_H__ /* * <stdio.h> definitions & functions */ #define EOF (-1) #endif // __PAL_STDCLIB_H__
fieldkit/cloud
server/api/records.go
package api import ( "context" "errors" "goa.design/goa/v3/security" records "github.com/fieldkit/cloud/server/api/gen/records" "github.com/fieldkit/cloud/server/backend/repositories" "github.com/fieldkit/cloud/server/common" serrors "github.com/fieldkit/cloud/server/common/errors" "github.com/fieldkit/cloud/server/data" ) type RecordsService struct { options *ControllerOptions } func NewRecordsService(ctx context.Context, options *ControllerOptions) *RecordsService { return &RecordsService{ options: options, } } func (c *RecordsService) Data(ctx context.Context, payload *records.DataPayload) (*records.DataResult, error) { p, err := NewPermissions(ctx, c.options).Unwrap() if err != nil { return nil, err } dataRecords := make([]*data.DataRecord, 0) if err := c.options.Database.SelectContext(ctx, &dataRecords, ` SELECT id, provision_id, time, number, meta_record_id, ST_AsBinary(location) AS location, raw, pb FROM fieldkit.data_record WHERE (id = $1) `, payload.RecordID); err != nil { return nil, serrors.Structured(err, "data_record_id", payload.RecordID) } if len(dataRecords) == 0 { return nil, records.MakeNotFound(errors.New("not found")) } metaRecords := make([]*data.MetaRecord, 0) if err := c.options.Database.SelectContext(ctx, &metaRecords, ` SELECT * FROM fieldkit.meta_record WHERE (id = $1) `, dataRecords[0].MetaRecordID); err != nil { return nil, serrors.Structured(err, "meta_record_id", dataRecords[0].MetaRecordID) } if len(metaRecords) == 0 { obj := struct { Data *data.DataRecord `json:"data"` }{ dataRecords[0], } return &records.DataResult{ Object: obj, }, nil } _ = p obj := struct { Data *data.DataRecord `json:"data"` Meta *data.MetaRecord `json:"meta"` }{ data.SanitizeDataRecord(dataRecords[0]), data.SanitizeMetaRecord(metaRecords[0]), } return &records.DataResult{ Object: obj, }, nil } func (c *RecordsService) Meta(ctx context.Context, payload *records.MetaPayload) (*records.MetaResult, error) { p, err := NewPermissions(ctx, c.options).Unwrap() if err != nil { return nil, err } metaRecords := make([]*data.MetaRecord, 0) if err := c.options.Database.SelectContext(ctx, &metaRecords, `SELECT * FROM fieldkit.meta_record WHERE (id = $1)`, payload.RecordID); err != nil { return nil, err } if len(metaRecords) == 0 { return nil, records.MakeNotFound(errors.New("not found")) } _ = p obj := struct { Meta *data.MetaRecord `json:"meta"` }{ data.SanitizeMetaRecord(metaRecords[0]), } return &records.MetaResult{ Object: obj, }, nil } func (c *RecordsService) Resolved(ctx context.Context, payload *records.ResolvedPayload) (*records.ResolvedResult, error) { p, err := NewPermissions(ctx, c.options).Unwrap() if err != nil { return nil, err } dbDatas := make([]*data.DataRecord, 0) if err := c.options.Database.SelectContext(ctx, &dbDatas, ` SELECT id, provision_id, time, number, meta_record_id, ST_AsBinary(location) AS location, raw, pb FROM fieldkit.data_record WHERE (id = $1) `, payload.RecordID); err != nil { return nil, err } if len(dbDatas) == 0 { return nil, records.MakeNotFound(errors.New("not found")) } dbMetas := make([]*data.MetaRecord, 0) if err := c.options.Database.SelectContext(ctx, &dbMetas, ` SELECT * FROM fieldkit.meta_record WHERE (id = $1) `, dbDatas[0].MetaRecordID); err != nil { return nil, err } metaFactory := repositories.NewMetaFactory() for _, dbMeta := range dbMetas { _, err := metaFactory.Add(ctx, dbMeta, false) if err != nil { return nil, err } } filtered, err := metaFactory.Resolve(ctx, dbDatas[0], true, false) if err != nil { return nil, err } _ = p obj := struct { Data *data.DataRecord `json:"data"` Meta *data.MetaRecord `json:"meta"` Filtered *repositories.FilteredRecord `json:"filtered"` }{ data.SanitizeDataRecord(dbDatas[0]), data.SanitizeMetaRecord(dbMetas[0]), filtered, } return &records.ResolvedResult{ Object: obj, }, nil } func (s *RecordsService) JWTAuth(ctx context.Context, token string, scheme *security.JWTScheme) (context.Context, error) { return Authenticate(ctx, common.AuthAttempt{ Token: token, Scheme: scheme, Key: s.options.JWTHMACKey, NotFound: func(m string) error { return records.MakeNotFound(errors.New(m)) }, Unauthorized: func(m string) error { return records.MakeUnauthorized(errors.New(m)) }, Forbidden: func(m string) error { return records.MakeForbidden(errors.New(m)) }, }) }
martinmo/rolevm
rolevm-agent/src/main/java/rolevm/transform/IndyMethodAdapter.java
package rolevm.transform; import static org.objectweb.asm.Opcodes.ACONST_NULL; import static org.objectweb.asm.Opcodes.ASM5; import static org.objectweb.asm.Opcodes.H_INVOKESTATIC; import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import static org.objectweb.asm.Opcodes.POP; import static rolevm.transform.BootstrapConstants.BSM_CLASS; import static rolevm.transform.BootstrapConstants.BSM_DEFAULT_NAME; import static rolevm.transform.BootstrapConstants.BSM_PROCEED_NAME; import static rolevm.transform.BootstrapConstants.BSM_TYPE; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; /** * Rewrites {@code invokevirtual} and {@code invokeinterface} call sites to * equivalent {@code invokedynamic} call sites. Call sites representing * {@code proceed} calls are assigned a special bootstrap method, and calls to * the {@link rolevm.api.DispatchContext#proceed()} marker method are replaced * by no-ops. * * @author <NAME> */ public class IndyMethodAdapter extends MethodVisitor { private static final Handle DEFAULT_BSM = new Handle(H_INVOKESTATIC, BSM_CLASS, BSM_DEFAULT_NAME, BSM_TYPE, false); private static final Handle PROCEED_BSM = new Handle(H_INVOKESTATIC, BSM_CLASS, BSM_PROCEED_NAME, BSM_TYPE, false); private final MethodInfo info; public IndyMethodAdapter(MethodInfo info, MethodVisitor mv) { super(ASM5, mv); this.info = info; } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (opcode == INVOKEVIRTUAL || opcode == INVOKEINTERFACE) { rewriteInvokeInstruction(owner, name, desc); } else { super.visitMethodInsn(opcode, owner, name, desc, itf); } } private void rewriteInvokeInstruction(String owner, String name, String descriptor) { // System.err.printf("rewriteInvoke(%s, %s, %s)%n", owner, name, descriptor); if ("java/lang/invoke/MethodHandle".equals(owner) && "invoke".equals(name) && descriptor.startsWith("(Lrolevm/api/DispatchContext;")) { visitInvokeDynamicInsn(info.name, adaptDescriptor(owner, descriptor), PROCEED_BSM); } else if ("rolevm/api/DispatchContext".equals(owner) && "proceed".equals(name) && "()Ljava/lang/invoke/MethodHandle;".equals(descriptor)) { visitInsn(POP); visitInsn(ACONST_NULL); } else { visitInvokeDynamicInsn(name, adaptDescriptor(owner, descriptor), DEFAULT_BSM); } } /** * Adapts the method descriptor string to include the receiver type as the first * argument. */ static String adaptDescriptor(final String owner, final String desc) { final String ownerTypeDesc = owner.startsWith("[") ? owner : "L" + owner + ";"; return "(" + ownerTypeDesc + desc.substring(1); } }
SunYe1234/PDFNetNew
headers/C/PDF/OCG/TRN_OCGConfig.h
<filename>headers/C/PDF/OCG/TRN_OCGConfig.h //--------------------------------------------------------------------------------------- // Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved. // Consult legal.txt regarding legal and license information. //--------------------------------------------------------------------------------------- #ifndef PDFTRON_H_CPDFOCGOCGConfig #define PDFTRON_H_CPDFOCGOCGConfig #ifdef __cplusplus extern "C" { #endif #include <C/Common/TRN_Types.h> TRN_API TRN_OCGConfigCreateFromObj(TRN_Obj dict, TRN_OCGConfig* result); TRN_API TRN_OCGConfigCreate(TRN_PDFDoc pdfdoc, TRN_Bool default_config, TRN_OCGConfig* result); TRN_API TRN_OCGConfigCopy(const TRN_OCGConfig c, TRN_OCGConfig* result); TRN_API TRN_OCGConfigGetSDFObj (const TRN_OCGConfig c, TRN_Obj* result); TRN_API TRN_OCGConfigGetOrder(const TRN_OCGConfig c, TRN_Obj* result); TRN_API TRN_OCGConfigSetOrder(const TRN_OCGConfig c, TRN_Obj value); TRN_API TRN_OCGConfigGetName(const TRN_OCGConfig c, TRN_UString* result); TRN_API TRN_OCGConfigSetName(const TRN_OCGConfig c, TRN_UString value); TRN_API TRN_OCGConfigGetCreator(const TRN_OCGConfig c, TRN_UString* result); TRN_API TRN_OCGConfigSetCreator(const TRN_OCGConfig c, TRN_UString value); TRN_API TRN_OCGConfigGetInitBaseState(const TRN_OCGConfig c, const char** result); TRN_API TRN_OCGConfigSetInitBaseState(const TRN_OCGConfig c, const char* value); TRN_API TRN_OCGConfigGetCreator(const TRN_OCGConfig c, TRN_UString* result); TRN_API TRN_OCGConfigSetCreator(const TRN_OCGConfig c, TRN_UString value); TRN_API TRN_OCGConfigGetInitOnStates(const TRN_OCGConfig c, TRN_Obj* result); TRN_API TRN_OCGConfigSetInitOnStates(const TRN_OCGConfig c, TRN_Obj value); TRN_API TRN_OCGConfigGetInitOffStates(const TRN_OCGConfig c, TRN_Obj* result); TRN_API TRN_OCGConfigSetInitOffStates(const TRN_OCGConfig c, TRN_Obj value); TRN_API TRN_OCGConfigGetIntent(const TRN_OCGConfig c, TRN_Obj* result); TRN_API TRN_OCGConfigSetIntent(const TRN_OCGConfig c, TRN_Obj value); TRN_API TRN_OCGConfigGetLockedOCGs(const TRN_OCGConfig c, TRN_Obj* result); TRN_API TRN_OCGConfigSetLockedOCGs(const TRN_OCGConfig c, TRN_Obj value); #ifdef __cplusplus } #endif #endif // PDFTRON_H_CPDFOCGOCGConfig
AresSys/AresOperator
cmd/observer/cmd.go
package observer import ( "context" "fmt" "net/http" "ares-operator/cmd/server" "ares-operator/conf" "ares-operator/observer" "ares-operator/observer/handler" "github.com/go-logr/logr" "github.com/spf13/cobra" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/manager" ) func NewObserverCommand() *cobra.Command { opts := NewOption() cmd := &cobra.Command{ Use: "observer", Short: "The Ares Observer", RunE: func(cmd *cobra.Command, args []string) error { opts.Option = server.CommonOptions return run(opts, server.OperatorConfig) }, } opts.Bind(cmd.Flags()) return cmd } func run(opts *ObserverOption, config *conf.Configuration) error { setupLog := ctrl.Log.WithName("setup") setupLog.Info(" === [initializing...] === ") setupLog.Info(fmt.Sprintf("options: %s", opts.String())) // create manager restConfig, managerOpts := server.BuildManagerOptions(opts.Option, config) mgr, err := ctrl.NewManager(restConfig, managerOpts) if err != nil { setupLog.Error(err, "unable to start observer") return err } // create observer r := observer.NewObserver(mgr.GetClient()) if err = r.SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create observer") return err } r.Register() // add http server httpServer := func(ctx context.Context) error { svr := &http.Server{ Addr: fmt.Sprintf("0.0.0.0:%d", opts.Port), Handler: handler.InitRouter(config.Cache.Observer), } return serve(ctx, svr, setupLog) } mgr.Add(manager.RunnableFunc(httpServer)) // start setupLog.Info("starting observer") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running observer") return err } setupLog.Info(" === [terminated] === \n\n\n") return nil } func serve(ctx context.Context, svr *http.Server, log logr.Logger) error { errCh := make(chan error, 1) // start HTTP Server go func() { if err := svr.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Error(err, "failed to ListenAndServe") errCh <- err } }() select { case err := <-errCh: return err case <-ctx.Done(): return nil } }
jkandasa/kiali-qe-java
src/main/java/com/redhat/qe/kiali/model/Version.java
package com.redhat.qe.kiali.model; import lombok.Builder; import lombok.Data; import lombok.ToString; /** * @author <NAME> (jkandasa) */ @Data @Builder @ToString public class Version { private String name; private String version; }
lifenstein/fez-frontend
src/modules/Dashboard/index.js
export { default as Dashboard } from './containers/Dashboard';
ezmaxinc/eZmax-SDK-c
model/ezsigntemplatesignature_get_object_v1_response.h
/* * ezsigntemplatesignature_get_object_v1_response.h * * Response for GET /1/object/ezsigntemplatesignature/{pkiEzsigntemplatesignatureID} */ #ifndef _ezsigntemplatesignature_get_object_v1_response_H_ #define _ezsigntemplatesignature_get_object_v1_response_H_ #include <string.h> #include "../external/cJSON.h" #include "../include/list.h" #include "../include/keyValuePair.h" #include "../include/binary.h" typedef struct ezsigntemplatesignature_get_object_v1_response_t ezsigntemplatesignature_get_object_v1_response_t; #include "common_response.h" #include "common_response_obj_debug.h" #include "common_response_obj_debug_payload.h" #include "ezsigntemplatesignature_get_object_v1_response_all_of.h" #include "ezsigntemplatesignature_get_object_v1_response_m_payload.h" typedef struct ezsigntemplatesignature_get_object_v1_response_t { struct ezsigntemplatesignature_get_object_v1_response_m_payload_t *m_payload; //model struct common_response_obj_debug_payload_t *obj_debug_payload; //model struct common_response_obj_debug_t *obj_debug; //model } ezsigntemplatesignature_get_object_v1_response_t; ezsigntemplatesignature_get_object_v1_response_t *ezsigntemplatesignature_get_object_v1_response_create( ezsigntemplatesignature_get_object_v1_response_m_payload_t *m_payload, common_response_obj_debug_payload_t *obj_debug_payload, common_response_obj_debug_t *obj_debug ); void ezsigntemplatesignature_get_object_v1_response_free(ezsigntemplatesignature_get_object_v1_response_t *ezsigntemplatesignature_get_object_v1_response); ezsigntemplatesignature_get_object_v1_response_t *ezsigntemplatesignature_get_object_v1_response_parseFromJSON(cJSON *ezsigntemplatesignature_get_object_v1_responseJSON); cJSON *ezsigntemplatesignature_get_object_v1_response_convertToJSON(ezsigntemplatesignature_get_object_v1_response_t *ezsigntemplatesignature_get_object_v1_response); #endif /* _ezsigntemplatesignature_get_object_v1_response_H_ */
Twon/Morpheus
libraries/core/core/cpu.test.cpp
#define CATCH_CONFIG_MAIN #include <algorithm> #include <string> #include <vector> #include <catch2/catch.hpp> #include <core/cpu.hpp> namespace morpheus::test { TEST_CASE("Cpu can be queried for processor info", "[morpheus.core.cpu]") { cpu processor; // Lists of CPU and Virtual Machine vendors from https://en.wikipedia.org/wiki/CPUID const std::vector<std::string> expected_cpu_vendors{ "AMDisbetter!", "AuthenticAMD", "CentaurHauls", "CyrixInstead", "GenuineIntel", "TransmetaCPU", "GenuineTMx86", "Geode by NSC", "NexGenDriven", "RiseRiseRise", "SiS SiS SiS ", "UMC UMC UMC ", "VIA VIA VIA ", "Vortex86 SoC"}; const std::vector<std::string> expected_virtual_machine_vendors{"bhyve bhyve ", "KVMKVMKVM", "Microsoft Hv", " lrpepyh vr", "VMwareVMware", "XenVMMXenVMM"}; const bool isValidCpu = std::find(std::begin(expected_cpu_vendors), std::end(expected_cpu_vendors), processor.getVendorId()) != std::end(expected_cpu_vendors); const bool isValidVirtualMachine = std::find(std::begin(expected_virtual_machine_vendors), std::end(expected_virtual_machine_vendors), processor.getVendorId()) != std::end(expected_virtual_machine_vendors); REQUIRE((isValidCpu || isValidVirtualMachine)); // REQUIRE(processor.getVendorId().size() == 64); } } // namespace morpheus::test
YanAndreatta/Exercises-Java
ws-eclipse/Aula97/src/application/Program.java
package application; import java.util.Scanner; public class Program { public static void main(String[] args) { int a, b, c; Scanner t = new Scanner(System.in); a = t.nextInt(); b = t.nextInt(); int[][] mat = new int[a][b]; for (int i = 0; i < mat.length; i++) { // i = 0; i < mat.length ( 3 ); i++ for (int j = 0; j < mat[i].length; j++) { // i = 0; i < mat[0].length ( 4 ); i++ mat[i][j] = t.nextInt(); } } c = t.nextInt(); for (int i = 0; i < mat.length; i++) { for (int j = 1; j < mat[i].length; j++) { if (mat[i][j] == c) { System.out.printf("Position: %d,%d%n",i , j); if(j > 0) { System.out.printf("Left: %d%n", mat[i][j-1]); } if(i > 0) { System.out.printf("Up: %d%n",mat[i-1][j]); } if(j < mat[i].length - 1) { System.out.printf("Right: %d%n", mat[i][j+1]); } if (i < mat.length - 1) { System.out.printf("Down: %d%n", mat[i + 1][j]); } } } } t.close(); } }
lipingzhu/Zero-determinant
axelrod/tests/unit/test_match.py
<filename>axelrod/tests/unit/test_match.py<gh_stars>0 # -*- coding: utf-8 -*- import unittest import axelrod from axelrod import Actions C, D = Actions.C, Actions.D class TestMatch(unittest.TestCase): def test_init(self): p1, p2 = axelrod.Cooperator(), axelrod.Cooperator() match = axelrod.Match((p1, p2), 5) self.assertEqual(match.result, []) self.assertEqual(match._player1, p1) self.assertEqual(match._player2, p2) self.assertEqual( match._classes, (axelrod.Cooperator, axelrod.Cooperator)) self.assertEqual(match._turns, 5) self.assertEqual(match._cache, {}) self.assertEqual(match._cache_mutable, True) self.assertEqual(match._noise, 0) def test_stochastic(self): p1, p2 = axelrod.Cooperator(), axelrod.Cooperator() match = axelrod.Match((p1, p2), 5) self.assertFalse(match._stochastic) match = axelrod.Match((p1, p2), 5, noise=0.2) self.assertTrue(match._stochastic) p1 = axelrod.Random() match = axelrod.Match((p1, p2), 5) self.assertTrue(match._stochastic) def test_cache_update_required(self): p1, p2 = axelrod.Cooperator(), axelrod.Cooperator() match = axelrod.Match((p1, p2), 5, noise=0.2) self.assertFalse(match._cache_update_required) match = axelrod.Match((p1, p2), 5, cache_mutable=False) self.assertFalse(match._cache_update_required) match = axelrod.Match((p1, p2), 5) self.assertTrue(match._cache_update_required) p1 = axelrod.Random() match = axelrod.Match((p1, p2), 5) self.assertFalse(match._cache_update_required) def test_play(self): cache = {} players = (axelrod.Cooperator(), axelrod.Defector()) match = axelrod.Match(players, 3, cache) expected_result = [(C, D), (C, D), (C, D)] self.assertEqual(match.play(), expected_result) self.assertEqual( cache[(axelrod.Cooperator, axelrod.Defector)], expected_result) # a deliberately incorrect result so we can tell it came from the cache expected_result = [(C, C), (D, D), (D, C)] cache = {(axelrod.Cooperator, axelrod.Defector): expected_result} match = axelrod.Match(players, 3, cache) self.assertEqual(match.play(), expected_result) def test_sparklines(self): players = (axelrod.Cooperator(), axelrod.Alternator()) match = axelrod.Match(players, 4) match.play() expected_sparklines = u'████\n█ █ ' self.assertEqual(match.sparklines(), expected_sparklines) expected_sparklines = u'XXXX\nXYXY' self.assertEqual(match.sparklines('X', 'Y'), expected_sparklines)
brandnewbox/validates_accessibility
spec/validates_accessibility/warnings/h69_spec.rb
<gh_stars>0 RSpec.describe WarningValidator::Validator, "WCAG H69 Standards" do before do Document.validates_accessibility_of :body, only: [:h69] end # For each <object> element, note if there is nested content which provides # the text equivalent. it "should be valid if a document uses headers to separate content" do d = Document.new d.body = '<h1>dog</h1>' expect(d).to be_valid end it "should be invalid if a document does not use headers to separate content" do d = Document.new d.body = '<p>hello</p>' expect(d).to be_invalid end end
liaoyuke/EECS542_Final_Project_VQA
code/concept_extraction/lib/en/parser/nltk_lite/corpora/names.py
# Natural Language Toolkit: Names Corpus Reader # # Copyright (C) 2001-2006 University of Pennsylvania # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # URL: <http://nltk.sf.net> # For license information, see LICENSE.TXT """ Names Corpus, Version 1.3 (1994-03-29) Copyright (C) 1991 <NAME> Additions by <NAME> This corpus contains 5001 female names and 2943 male names, sorted alphabetically, one per line. (Used in NLTK with permission. See the README file for details.) """ from en.parser.nltk_lite.corpora import get_basedir import os items = ['female', 'male'] item_name = { 'female': 'Female names', 'male': 'Male names' } def raw(files = ['female', 'male']): if type(files) is str: files = (files,) for file in files: path = os.path.join(get_basedir(), "names", file+".txt") for word in open(path).readlines(): yield word.strip() def demo(): from en.parser.nltk_lite.corpora import names from random import shuffle from pprint import pprint print "20 female names" female = list(names.raw('female')) shuffle(female) pprint(female[:20]) print "20 male names" male = list(names.raw('male')) shuffle(male) pprint(male[:20]) if __name__ == '__main__': demo()
igorski/efflux-tracker
src/model/validators/instrument-validator.js
/** * The MIT License (MIT) * * <NAME> 2016-2021 - https://www.igorski.nl * * 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. */ export default { /** * queries whether given Object is a valid instrument. * * @see InstrumentFactory * * @public * @param {INSTRUMENT} instrument * @return {boolean} */ isValid( instrument ) { if ( !instrument ) { return false; } if ( !Array.isArray( instrument.oscillators )) { return false; } let i = instrument.oscillators.length, oscillator; while ( i-- ) { oscillator = instrument.oscillators[ i ]; if ( typeof oscillator.enabled !== "boolean" || typeof oscillator.waveform !== "string" || typeof oscillator.volume !== "number" || typeof oscillator.detune !== "number" || typeof oscillator.octaveShift !== "number" || typeof oscillator.fineShift !== "number" || ( typeof oscillator.adsr !== "object" || typeof oscillator.adsr.attack !== "number" || typeof oscillator.adsr.decay !== "number" || typeof oscillator.adsr.sustain !== "number" || typeof oscillator.adsr.release !== "number" ) && ( oscillator.table === 0 || Array.isArray( oscillator.table ))) { return false; } } return typeof instrument.index === "number" && typeof instrument.name === "string" && typeof instrument.volume === "number" && ( typeof instrument.filter === "object" && typeof instrument.filter.enabled === "boolean" && typeof instrument.filter.frequency === "number" && typeof instrument.filter.q === "number" && typeof instrument.filter.speed === "number" && typeof instrument.filter.depth === "number" && typeof instrument.filter.type === "string" && typeof instrument.filter.lfoType === "string" ) && ( typeof instrument.delay === "object" && typeof instrument.delay.enabled === "boolean" && typeof instrument.delay.type === "number" && typeof instrument.delay.time === "number" && typeof instrument.delay.feedback === "number" && typeof instrument.delay.cutoff === "number" && typeof instrument.delay.offset === "number" ); } };
dbastin/donkey
src/java/prod/org/burroloco/donkey/spit/http/KeyStores.java
package org.burroloco.donkey.spit.http; import edge.java.security.KeyStore; import org.burroloco.donkey.config.KeyStoreLocation; import org.burroloco.donkey.config.KeyStorePassword; public interface KeyStores { KeyStore nu(KeyStoreLocation l, KeyStorePassword p); }
6417/FridoWPI
src/test/java/ch/fridolins/fridowpi/Utils.java
<gh_stars>0 package ch.fridolins.fridowpi; import edu.wpi.first.wpilibj.DriverStation; import org.mockito.MockedStatic; import org.mockito.Mockito; public class Utils { public static void withRobotEnabled(Runnable function) { try (MockedStatic<DriverStation> utilities = Mockito.mockStatic(DriverStation.class)) { utilities.when(DriverStation::isEnabled).thenReturn(true); function.run(); } } }
jkdubr/Proj4
Pod/Classes/Projection/MOBProjectionEPSG37224.h
<filename>Pod/Classes/Projection/MOBProjectionEPSG37224.h #import "MOBProjection.h" @interface MOBProjectionEPSG37224 : MOBProjection @end
wibeasley/jbc-2016
1408-wallaby/Default User/go thunder! (figure ate)/src/main.c
<reponame>wibeasley/jbc-2016<gh_stars>0 #include <kipr/botball.h> int move(int speed_left,int speed_right,int duration){ motor(0,speed_left); motor(2,speed_right); msleep(duration); return 0; } int main(){ move( 50, 50, 3667); // forward move( 30, -30, 1250); // pivot right move( 50, 50, 3300); // forward move( -30, 30, 1250); // pivot right move( 50, 50, 3300); // forward move( -30, 30, 1250); // pivot right move( 50, 50, 3300); // forward move( -30, 30, 1250); // pivot right move( 50, 50, 3300); // forward move( -30, 30, 1250); // pivot right move( 50, 50, 3509); // forward move( 30, -30, 1250); // pivot left move( 50, 50, 3900); // forward return 0; }
TeamworkGuy2/JParserTools
src/twg2/parser/codeParser/codeStats/ParsedFileStats.java
package twg2.parser.codeParser.codeStats; import lombok.Getter; import twg2.collections.primitiveCollections.IntArrayList; import twg2.collections.primitiveCollections.IntList; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author TeamworkGuy2 * @since 2015-9-19 */ public final class ParsedFileStats { @Getter String srcId; @Getter int charCount; @JsonIgnore @Getter IntList whitespaceLineNumbers; @Getter int whitespaceLineCount; @JsonIgnore @Getter IntList commentLineNumbers; @Getter int commentLineCount; @Getter int totalLineCount; public ParsedFileStats() { } public ParsedFileStats(String srcId, int charCount, int whitespaceLineCount, int commentLineCount, int totalLineCount) { this.srcId = srcId; this.charCount = charCount; this.whitespaceLineCount = whitespaceLineCount; this.commentLineCount = commentLineCount; this.totalLineCount = totalLineCount; } public ParsedFileStats(String srcId, int charCount, IntList whitespaceLineNumbers, IntList commentLineNumbers, int totalLineCount) { this.srcId = srcId; this.charCount = charCount; this.whitespaceLineNumbers = whitespaceLineNumbers; this.whitespaceLineCount = whitespaceLineNumbers.size(); this.commentLineNumbers = commentLineNumbers; this.commentLineCount = commentLineNumbers.size(); this.totalLineCount = totalLineCount; } @JsonProperty("whitespaceLineNumbers") public int[] _getWhitespaceLineNumbers() { return whitespaceLineNumbers != null ? whitespaceLineNumbers.toArray() : null; } @JsonProperty("whitespaceLineNumbers") public void setWhitespaceLineNumbers(int[] whitespaceLineNumbers) { this.whitespaceLineNumbers = whitespaceLineNumbers != null ? IntArrayList.of(whitespaceLineNumbers) : null; } @JsonProperty("commentLineNumbers") public int[] _getCommentLineNumbers() { return commentLineNumbers != null ? commentLineNumbers.toArray() : null; } @JsonProperty("commentLineNumbers") public void setCommentLineNumbers(int[] commentLineNumbers) { this.commentLineNumbers = commentLineNumbers != null ? IntArrayList.of(commentLineNumbers) : null; } }
gurylev-nikita/devtools-course-practice
modules/btree_out_search/src/btree.cpp
<reponame>gurylev-nikita/devtools-course-practice  // Copyright 2021 <NAME> #include <malloc.h> #include "include/btree.h" tnode* addtree(tnode* tree, int val) { if (tree == nullptr) { tree = new tnode; tree->value = val; tree->left = tree->right = nullptr; } else if (val < tree->value) { tree->left = addtree(tree->left, val); } else { tree->right = addtree(tree->right, val); } return tree; } tnode* find(tnode* tree, int val) { if (tree == nullptr) { return nullptr; } if (tree->value == val) { return tree; } if (val <= tree->value) { if (tree->left != nullptr) { return find(tree->left, val); } else { return nullptr; } } else { if (tree->right) { return find(tree->right, val); } else { return nullptr; } } }
ist-dresden/composum-assets
commons/bundle/src/main/java/com/composum/assets/commons/image/RenditionWriter.java
/* * copyright (c) 2015 IST GmbH Dresden, Germany * * This software may be modified and distributed under the terms of the MIT license. */ package com.composum.assets.commons.image; import com.composum.assets.commons.config.RenditionConfig; import com.composum.assets.commons.handle.AssetRendition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; /** * */ public class RenditionWriter { private static final Logger LOG = LoggerFactory.getLogger(RenditionWriter.class); public InputStream writeImage(final AssetRendition rendition, final BufferedImage image, BuilderContext context) throws IOException { RenditionConfig config = rendition.getConfig(); String mimeType = rendition.getMimeType(); Double quality; final ImageWriter imageWriter = ImageIO.getImageWritersByMIMEType(mimeType).next(); final ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); if (imageWriteParam.canWriteCompressed() && (quality = config.getFile().getQuality()) != null) { imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality(quality.floatValue()); } final PipedOutputStream outputStream = new PipedOutputStream(); InputStream result = new PipedInputStream(outputStream); final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream); context.execute(new Runnable() { @Override public void run() { try { imageWriter.setOutput(imageOutputStream); imageWriter.write(null, new IIOImage(image, null, null), imageWriteParam); imageOutputStream.flush(); outputStream.flush(); imageWriter.dispose(); imageOutputStream.close(); outputStream.close(); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); } } }); return result; } /** * write direct to a given output stream * * @param rendition the rendition configuration (output file settings) * @param image the loaded and transformed image (the built rendition image) * @param outputStream the target stream (maybe the response output stream) */ public void writeImage(final AssetRendition rendition, final BufferedImage image, OutputStream outputStream) throws IOException { RenditionConfig config = rendition.getConfig(); String mimeType = rendition.getMimeType(); Double quality; final ImageWriter imageWriter = ImageIO.getImageWritersByMIMEType(mimeType).next(); final ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); if (imageWriteParam.canWriteCompressed() && (quality = config.getFile().getQuality()) != null) { imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality(quality.floatValue()); } try (final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream)) { imageWriter.setOutput(imageOutputStream); imageWriter.write(null, new IIOImage(image, null, null), imageWriteParam); imageOutputStream.flush(); outputStream.flush(); imageWriter.dispose(); } } }
837477/Python_Parallel
08_multi_processing/pipes.py
import os, sys import multiprocessing class ChildProcess(multiprocessing.Process): def __init__(self, pipein): super(ChildProcess, self).__init__() self.pipein = pipein def run(self): print("Attempting to pipein to pipe") self.pipein = os.fdopen(self.pipein, 'w') self.pipein.write("My Name is Elliot") self.pipein.close() def main(): pipeout, pipein = os.pipe() child = ChildProcess(pipein) child.start() child.join() os.close(pipein) pipeout = os.fdopen(pipeout) pipeContent = pipeout.read() print("Pipe: {}".format(pipeContent)) if __name__ == '__main__': main()
cviebig/lib-sql-text
include/sql/text/grammar/expr.hpp
<reponame>cviebig/lib-sql-text<gh_stars>1-10 #ifndef SQL_TEXT_GRAMMAR_EXPR_HPP #define SQL_TEXT_GRAMMAR_EXPR_HPP #include "sql/fusion/expr.hpp" #include <boost/optional.hpp> #include <boost/spirit/home/x3.hpp> namespace sql { namespace text { using boost::spirit::x3::rule; /////////////////////////////////////////////////////////////////////////// // Rule IDs /////////////////////////////////////////////////////////////////////////// struct bind_parameter_class; struct schema_column_identifier_class; struct table_column_identifier_class; struct simple_column_identifier_class; struct column_identifier_class; struct binary_operation_p1_class; struct binary_operation_p2_class; struct binary_operation_p3_class; struct binary_operation_p4_class; struct binary_operation_p5_class; struct binary_operation_p6_class; struct binary_operation_p7_class; struct binary_operation_p8_class; struct function_params_expr_list_class; struct function_params_none_class; struct function_params_row_class; struct function_params_class; struct function_call_class; struct expr_class; struct expr_list_class; /////////////////////////////////////////////////////////////////////////// // Rules /////////////////////////////////////////////////////////////////////////// const rule<bind_parameter_class, ast::bind_parameter> bind_parameter = "bind_parameter"; const rule<schema_column_identifier_class, ast::schema_column_identifier> schema_column_identifier = "schema_column_identifier"; const rule<table_column_identifier_class, ast::table_column_identifier> table_column_identifier = "table_column_identifier"; const rule<simple_column_identifier_class, ast::simple_column_identifier> simple_column_identifier = "simple_column_identifier"; const rule<function_params_expr_list_class, ast::function_params_expr_list> function_params_expr_list = "function_params_expr_list"; const rule<function_params_none_class, ast::function_params_none> function_params_none = "function_params_none"; const rule<function_params_row_class, ast::function_params_row> function_params_row = "function_params_row"; const rule<function_params_class, ast::function_params> function_params = "function_params"; const rule<function_call_class, ast::function_call> function_call = "function_call"; const rule<column_identifier_class, ast::column_identifier> column_identifier = "column_identifier"; const rule<binary_operation_p1_class, ast::binary_operation> binary_operation_p1 = "binary_operation_p1"; const rule<binary_operation_p2_class, ast::binary_operation> binary_operation_p2 = "binary_operation_p2"; const rule<binary_operation_p3_class, ast::binary_operation> binary_operation_p3 = "binary_operation_p3"; const rule<binary_operation_p4_class, ast::binary_operation> binary_operation_p4 = "binary_operation_p4"; const rule<binary_operation_p5_class, ast::binary_operation> binary_operation_p5 = "binary_operation_p5"; const rule<binary_operation_p6_class, ast::binary_operation> binary_operation_p6 = "binary_operation_p6"; const rule<binary_operation_p7_class, ast::binary_operation> binary_operation_p7 = "binary_operation_p7"; const rule<binary_operation_p8_class, ast::binary_operation> binary_operation_p8 = "binary_operation_p8"; const rule<expr_class, ast::expr> expr = "expr"; const rule<expr_list_class, ast::expr_list> expr_list = "expr_list"; }} #endif //SQL_TEXT_GRAMMAR_EXPR_HPP
ptwb3/metasploit-framework
modules/exploits/windows/fileformat/openoffice_ole.rb
<reponame>ptwb3/metasploit-framework ## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class MetasploitModule < Msf::Exploit::Remote Rank = NormalRanking include Msf::Exploit::FILEFORMAT def initialize(info={}) super(update_info(info, 'Name' => "OpenOffice OLE Importer DocumentSummaryInformation Stream Handling Overflow", 'Description' => %q{ This module exploits a vulnerability in OpenOffice 2.3.1 and 2.3.0 on Microsoft Windows XP SP3. By supplying a OLE file with a malformed DocumentSummaryInformation stream, an attacker can gain control of the execution flow, which results arbitrary code execution under the context of the user. }, 'License' => MSF_LICENSE, 'Author' => [ 'Marsu <<EMAIL>>', # Vulnerability discovery and PoC '<NAME>' # Metasploit module ], 'References' => [ ['CVE', '2008-0320'], ['BID', '28819'], ['EDB', '5584'], ['URL', 'http://www.verisigninc.com/en_US/products-and-services/network-intelligence-availability/idefense/public-vulnerability-reports/articles/index.xhtml?id=694'] ], 'Payload' => { 'Space' => 407 }, 'DefaultOptions' => { 'EXITFUNC' => 'process', 'DisablePayloadHandler' => 'true' }, 'Platform' => 'win', 'Targets' => [ [ 'OpenOffice 2.3.1 / 2.3.0 on Windows XP SP3', { 'Ret' => 0x609345fe, # add esp, ebx # ... # ret from tl680mi 'EBX' => 0xffffefa8, # EBX value 'JmpEsp' => 0x60915cbd, # push esp # ret from tl680mi } ], ], 'Privileged' => false, 'DisclosureDate' => "Apr 17 2008", 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [true, 'The filename', 'msf.doc']) ], self.class) end def exploit path = File.join(Msf::Config.install_root, 'data', 'exploits', 'CVE-2008-0320.doc') f = File.open(path, 'rb') template = f.read f.close my_payload = payload.encoded template[115717, 4] = [target['Ret']].pack("V") template[115725, 4] = [target['EBX']].pack("V") template[115729, 4] = [target['JmpEsp']].pack("V") template[115808, my_payload.length] = my_payload file_create(template) end end
blackjyn/flex-sdk
modules/thirdparty/velocity/src/java/org/apache/flex/forks/velocity/test/TemplateTestSuite.java
<reponame>blackjyn/flex-sdk package org.apache.flex.forks.velocity.test; /* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.FileInputStream; import java.util.Properties; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import org.apache.flex.forks.velocity.app.Velocity; import junit.framework.TestSuite; /** * Test suite for Templates. * * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME>.</a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Id: TemplateTestSuite.java,v 1.6.8.1 2004/03/03 23:23:04 geirm Exp $ */ public class TemplateTestSuite extends TestSuite implements TemplateTestBase { private Properties testProperties; /** * Creates an instace of the Apache Velocity test suite. */ public TemplateTestSuite() { try { Velocity.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH); Velocity.setProperty(Velocity.RUNTIME_LOG_ERROR_STACKTRACE, "true"); Velocity.setProperty(Velocity.RUNTIME_LOG_WARN_STACKTRACE, "true"); Velocity.setProperty(Velocity.RUNTIME_LOG_INFO_STACKTRACE, "true"); Velocity.init(); testProperties = new Properties(); testProperties.load(new FileInputStream(TEST_CASE_PROPERTIES)); } catch (Exception e) { System.err.println("Cannot setup TemplateTestSuite!"); e.printStackTrace(); System.exit(1); } addTemplateTestCases(); } /** * Adds the template test cases to run to this test suite. Template test * cases are listed in the <code>TEST_CASE_PROPERTIES</code> file. */ private void addTemplateTestCases() { String template; for (int i = 1 ;; i++) { template = testProperties.getProperty(getTemplateTestKey(i)); if (template != null) { System.out.println("Adding TemplateTestCase : " + template); addTest(new TemplateTestCase(template)); } else { // Assume we're done adding template test cases. break; } } } /** * Macro which returns the properties file key for the specified template * test number. * * @param nbr The template test number to return a property key for. * @return The property key. */ private static final String getTemplateTestKey(int nbr) { return ("test.template." + nbr); } }
waltzofpearls/sawmill
vendor/github.com/basho/riak-go-client/crdt_commands.go
<gh_stars>0 package riak import ( "fmt" "reflect" "time" rpbRiakDT "github.com/basho/riak-go-client/rpb/riak_dt" rpbRiakKV "github.com/basho/riak-go-client/rpb/riak_kv" proto "github.com/golang/protobuf/proto" ) // UpdateCounter // DtUpdateReq // DtUpdateResp // UpdateCounterCommand is used to increment or decrement a counter data type in Riak KV type UpdateCounterCommand struct { commandImpl timeoutImpl retryableCommandImpl Response *UpdateCounterResponse protobuf proto.Message isLegacy bool } // Name identifies this command func (cmd *UpdateCounterCommand) Name() string { return cmd.getName("UpdateCounter") } func (cmd *UpdateCounterCommand) constructPbRequest() (proto.Message, error) { return cmd.protobuf, nil } func (cmd *UpdateCounterCommand) onSuccess(msg proto.Message) error { cmd.success = true if msg != nil { // For legacy counters, the response may be different if rpbDtUpdateResp, is_DtUpdateResp := msg.(*rpbRiakDT.DtUpdateResp); is_DtUpdateResp && !cmd.isLegacy { cmd.Response = &UpdateCounterResponse{ GeneratedKey: string(rpbDtUpdateResp.GetKey()), CounterValue: rpbDtUpdateResp.GetCounterValue(), } } else if rpbCounterUpdateResp, is_RpbCounterUpdateResp := msg.(*rpbRiakKV.RpbCounterUpdateResp); is_RpbCounterUpdateResp && cmd.isLegacy { cmd.Response = &UpdateCounterResponse{ CounterValue: rpbCounterUpdateResp.GetValue(), } } else { return fmt.Errorf("[UpdateCounterCommand] could not convert %v to DtUpdateResp / RpbCounterUpdateResp, isLegacy: %v", reflect.TypeOf(msg), cmd.isLegacy) } } return nil } func (cmd *UpdateCounterCommand) getRequestCode() byte { if cmd.isLegacy { return rpbCode_RpbCounterUpdateReq } return rpbCode_DtUpdateReq } func (cmd *UpdateCounterCommand) getResponseCode() byte { if cmd.isLegacy { return rpbCode_RpbCounterUpdateResp } return rpbCode_DtUpdateResp } func (cmd *UpdateCounterCommand) getResponseProtobufMessage() proto.Message { if cmd.isLegacy { return &rpbRiakKV.RpbCounterUpdateResp{} } return &rpbRiakDT.DtUpdateResp{} } // UpdateCounterResponse is the object containing the response type UpdateCounterResponse struct { GeneratedKey string CounterValue int64 } // UpdateCounterCommandBuilder type is required for creating new instances of UpdateCounterCommand // // command := NewUpdateCounterCommandBuilder(). // WithBucketType("myBucketType"). // WithBucket("myBucket"). // WithKey("myKey"). // WithIncrement(1). // Build() type UpdateCounterCommandBuilder struct { bucketType string bucket string key string increment int64 w uint32 dw uint32 pw uint32 returnBody bool timeout time.Duration } // NewUpdateCounterCommandBuilder is a factory function for generating the command builder struct func NewUpdateCounterCommandBuilder() *UpdateCounterCommandBuilder { return &UpdateCounterCommandBuilder{} } // WithBucketType sets the bucket-type to be used by the command. If omitted, 'default' is used func (builder *UpdateCounterCommandBuilder) WithBucketType(bucketType string) *UpdateCounterCommandBuilder { builder.bucketType = bucketType return builder } // WithBucket sets the bucket to be used by the command func (builder *UpdateCounterCommandBuilder) WithBucket(bucket string) *UpdateCounterCommandBuilder { builder.bucket = bucket return builder } // WithKey sets the key to be used by the command to read / write values func (builder *UpdateCounterCommandBuilder) WithKey(key string) *UpdateCounterCommandBuilder { builder.key = key return builder } // WithIncrement defines the increment the Counter value is to be increased / decreased by func (builder *UpdateCounterCommandBuilder) WithIncrement(increment int64) *UpdateCounterCommandBuilder { builder.increment = increment return builder } // WithW sets the number of nodes that must report back a successful write in order for then // command operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateCounterCommandBuilder) WithW(w uint32) *UpdateCounterCommandBuilder { builder.w = w return builder } // WithPw sets the number of primary nodes (N) that must report back a successful write in order for // the command operation to be considered a success by Riak. If ommitted, the bucket default is // used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateCounterCommandBuilder) WithPw(pw uint32) *UpdateCounterCommandBuilder { builder.pw = pw return builder } // WithDw (durable writes) sets the number of nodes that must report back a successful write to // backend storage in order for the command operation to be considered a success by Riak // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateCounterCommandBuilder) WithDw(dw uint32) *UpdateCounterCommandBuilder { builder.dw = dw return builder } // WithReturnBody sets Riak to return the value within its response after completing the write // operation func (builder *UpdateCounterCommandBuilder) WithReturnBody(returnBody bool) *UpdateCounterCommandBuilder { builder.returnBody = returnBody return builder } // WithTimeout sets a timeout to be used for this command operation func (builder *UpdateCounterCommandBuilder) WithTimeout(timeout time.Duration) *UpdateCounterCommandBuilder { builder.timeout = timeout return builder } // Build validates the configuration options provided then builds the command func (builder *UpdateCounterCommandBuilder) Build() (Command, error) { var isLegacy = false var timeout time.Duration var protobuf proto.Message = nil if builder.bucketType == defaultBucketType && builder.returnBody == true { isLegacy = true rpbCounterUpdateReq := &rpbRiakKV.RpbCounterUpdateReq{ Amount: &builder.increment, W: &builder.w, Dw: &builder.dw, Pw: &builder.pw, Returnvalue: &builder.returnBody, } // NB: strings must be handled this way to ensure that nil slices // are in the PB msg, rather than 0-len ones if builder.bucket != "" { rpbCounterUpdateReq.Bucket = []byte(builder.bucket) } if builder.key != "" { rpbCounterUpdateReq.Key = []byte(builder.key) } protobuf = rpbCounterUpdateReq } else { timeout = builder.timeout timeoutMilliseconds := uint32(builder.timeout / time.Millisecond) dtUpdateReq := &rpbRiakDT.DtUpdateReq{ W: &builder.w, Dw: &builder.dw, Pw: &builder.pw, ReturnBody: &builder.returnBody, Timeout: &timeoutMilliseconds, Op: &rpbRiakDT.DtOp{ CounterOp: &rpbRiakDT.CounterOp{ Increment: &builder.increment, }, }, } // NB: strings must be handled this way to ensure that nil slices // are in the PB msg, rather than 0-len ones if builder.bucketType != "" { dtUpdateReq.Type = []byte(builder.bucketType) } if builder.bucket != "" { dtUpdateReq.Bucket = []byte(builder.bucket) } if builder.key != "" { dtUpdateReq.Key = []byte(builder.key) } protobuf = dtUpdateReq } if err := validateLocatable(protobuf); err != nil { return nil, err } return &UpdateCounterCommand{ timeoutImpl: timeoutImpl{ timeout: timeout, }, protobuf: protobuf, isLegacy: isLegacy, }, nil } // FetchCounter // DtFetchReq // DtFetchResp // FetchCounterCommand fetches a counter CRDT from Riak type FetchCounterCommand struct { commandImpl timeoutImpl retryableCommandImpl Response *FetchCounterResponse protobuf *rpbRiakDT.DtFetchReq } // Name identifies this command func (cmd *FetchCounterCommand) Name() string { return cmd.getName("FetchCounter") } func (cmd *FetchCounterCommand) constructPbRequest() (proto.Message, error) { return cmd.protobuf, nil } func (cmd *FetchCounterCommand) onSuccess(msg proto.Message) error { cmd.success = true if msg != nil { if rpbDtFetchResp, ok := msg.(*rpbRiakDT.DtFetchResp); ok { response := &FetchCounterResponse{} rpbValue := rpbDtFetchResp.GetValue() if rpbValue == nil { response.IsNotFound = true } else { response.CounterValue = rpbValue.GetCounterValue() } cmd.Response = response } else { return fmt.Errorf("[FetchCounterCommand] could not convert %v to DtFetchResp", reflect.TypeOf(msg)) } } return nil } func (cmd *FetchCounterCommand) getRequestCode() byte { return rpbCode_DtFetchReq } func (cmd *FetchCounterCommand) getResponseCode() byte { return rpbCode_DtFetchResp } func (cmd *FetchCounterCommand) getResponseProtobufMessage() proto.Message { return &rpbRiakDT.DtFetchResp{} } // FetchCounterResponse contains the response data for a FetchCounterCommand type FetchCounterResponse struct { IsNotFound bool CounterValue int64 } // FetchCounterCommandBuilder type is required for creating new instances of FetchCounterCommand // // command := NewFetchCounterCommandBuilder(). // WithBucketType("myBucketType"). // WithBucket("myBucket"). // WithKey("myKey"). // Build() type FetchCounterCommandBuilder struct { timeout time.Duration protobuf *rpbRiakDT.DtFetchReq } // NewFetchCounterCommandBuilder is a factory function for generating the command builder struct func NewFetchCounterCommandBuilder() *FetchCounterCommandBuilder { return &FetchCounterCommandBuilder{protobuf: &rpbRiakDT.DtFetchReq{}} } // WithBucketType sets the bucket-type to be used by the command. If omitted, 'default' is used func (builder *FetchCounterCommandBuilder) WithBucketType(bucketType string) *FetchCounterCommandBuilder { builder.protobuf.Type = []byte(bucketType) return builder } // WithBucket sets the bucket to be used by the command func (builder *FetchCounterCommandBuilder) WithBucket(bucket string) *FetchCounterCommandBuilder { builder.protobuf.Bucket = []byte(bucket) return builder } // WithKey sets the key to be used by the command to read / write values func (builder *FetchCounterCommandBuilder) WithKey(key string) *FetchCounterCommandBuilder { builder.protobuf.Key = []byte(key) return builder } // WithR sets the number of nodes that must report back a successful read in order for the // command operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *FetchCounterCommandBuilder) WithR(r uint32) *FetchCounterCommandBuilder { builder.protobuf.R = &r return builder } // WithPr sets the number of primary nodes (N) that must be read from in order for the command // operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *FetchCounterCommandBuilder) WithPr(pr uint32) *FetchCounterCommandBuilder { builder.protobuf.Pr = &pr return builder } // WithNotFoundOk sets notfound_ok, whether to treat notfounds as successful reads for the purposes // of R // // See http://basho.com/posts/technical/riaks-config-behaviors-part-3/ func (builder *FetchCounterCommandBuilder) WithNotFoundOk(notFoundOk bool) *FetchCounterCommandBuilder { builder.protobuf.NotfoundOk = &notFoundOk return builder } // WithBasicQuorum sets basic_quorum, whether to return early in some failure cases (eg. when r=1 // and you get 2 errors and a success basic_quorum=true would return an error) // // See http://basho.com/posts/technical/riaks-config-behaviors-part-3/ func (builder *FetchCounterCommandBuilder) WithBasicQuorum(basicQuorum bool) *FetchCounterCommandBuilder { builder.protobuf.BasicQuorum = &basicQuorum return builder } // WithTimeout sets a timeout to be used for this command operation func (builder *FetchCounterCommandBuilder) WithTimeout(timeout time.Duration) *FetchCounterCommandBuilder { timeoutMilliseconds := uint32(timeout / time.Millisecond) builder.timeout = timeout builder.protobuf.Timeout = &timeoutMilliseconds return builder } // Build validates the configuration options provided then builds the command func (builder *FetchCounterCommandBuilder) Build() (Command, error) { if builder.protobuf == nil { panic("builder.protobuf must not be nil") } if err := validateLocatable(builder.protobuf); err != nil { return nil, err } return &FetchCounterCommand{ timeoutImpl: timeoutImpl{ timeout: builder.timeout, }, protobuf: builder.protobuf, }, nil } // UpdateSet // DtUpdateReq // DtUpdateResp // UpdateSetCommand stores or updates a set CRDT in Riak type UpdateSetCommand struct { commandImpl timeoutImpl retryableCommandImpl Response *UpdateSetResponse protobuf *rpbRiakDT.DtUpdateReq } // Name identifies this command func (cmd *UpdateSetCommand) Name() string { return cmd.getName("UpdateSet") } func (cmd *UpdateSetCommand) constructPbRequest() (proto.Message, error) { return cmd.protobuf, nil } func (cmd *UpdateSetCommand) onSuccess(msg proto.Message) error { cmd.success = true if msg != nil { if rpbDtUpdateResp, ok := msg.(*rpbRiakDT.DtUpdateResp); ok { response := &UpdateSetResponse{ GeneratedKey: string(rpbDtUpdateResp.GetKey()), Context: rpbDtUpdateResp.GetContext(), SetValue: rpbDtUpdateResp.GetSetValue(), } cmd.Response = response } else { return fmt.Errorf("[UpdateSetCommand] could not convert %v to DtUpdateResp", reflect.TypeOf(msg)) } } return nil } func (cmd *UpdateSetCommand) getRequestCode() byte { return rpbCode_DtUpdateReq } func (cmd *UpdateSetCommand) getResponseCode() byte { return rpbCode_DtUpdateResp } func (cmd *UpdateSetCommand) getResponseProtobufMessage() proto.Message { return &rpbRiakDT.DtUpdateResp{} } // UpdateSetResponse contains the response data for a UpdateSetCommand type UpdateSetResponse struct { GeneratedKey string Context []byte SetValue [][]byte } // UpdateSetCommandBuilder type is required for creating new instances of UpdateSetCommand // // adds := [][]byte{ // []byte("a1"), // []byte("a2"), // []byte("a3"), // []byte("a4"), // } // // command := NewUpdateSetCommandBuilder(). // WithBucketType("myBucketType"). // WithBucket("myBucket"). // WithKey("myKey"). // WithContext(setContext). // WithAdditions(adds). // Build() type UpdateSetCommandBuilder struct { timeout time.Duration protobuf *rpbRiakDT.DtUpdateReq } // NewUpdateSetCommandBuilder is a factory function for generating the command builder struct func NewUpdateSetCommandBuilder() *UpdateSetCommandBuilder { return &UpdateSetCommandBuilder{ protobuf: &rpbRiakDT.DtUpdateReq{ Op: &rpbRiakDT.DtOp{ SetOp: &rpbRiakDT.SetOp{}, }, }, } } // WithBucketType sets the bucket-type to be used by the command. If omitted, 'default' is used func (builder *UpdateSetCommandBuilder) WithBucketType(bucketType string) *UpdateSetCommandBuilder { builder.protobuf.Type = []byte(bucketType) return builder } // WithBucket sets the bucket to be used by the command func (builder *UpdateSetCommandBuilder) WithBucket(bucket string) *UpdateSetCommandBuilder { builder.protobuf.Bucket = []byte(bucket) return builder } // WithKey sets the key to be used by the command to read / write values func (builder *UpdateSetCommandBuilder) WithKey(key string) *UpdateSetCommandBuilder { builder.protobuf.Key = []byte(key) return builder } // WithContext sets the causal context needed to identify the state of the set when removing elements func (builder *UpdateSetCommandBuilder) WithContext(context []byte) *UpdateSetCommandBuilder { builder.protobuf.Context = context return builder } // WithAdditions sets the set elements to be added to the CRDT set via this update operation func (builder *UpdateSetCommandBuilder) WithAdditions(adds ...[]byte) *UpdateSetCommandBuilder { opAdds := builder.protobuf.Op.SetOp.Adds opAdds = append(opAdds, adds...) builder.protobuf.Op.SetOp.Adds = opAdds return builder } // WithRemovals sets the set elements to be removed from the CRDT set via this update operation func (builder *UpdateSetCommandBuilder) WithRemovals(removals ...[]byte) *UpdateSetCommandBuilder { opRemoves := builder.protobuf.Op.SetOp.Removes opRemoves = append(opRemoves, removals...) builder.protobuf.Op.SetOp.Removes = opRemoves return builder } // WithW sets the number of nodes that must report back a successful write in order for then // command operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateSetCommandBuilder) WithW(w uint32) *UpdateSetCommandBuilder { builder.protobuf.W = &w return builder } // WithPw sets the number of primary nodes (N) that must report back a successful write in order for // the command operation to be considered a success by Riak. If ommitted, the bucket default is // used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateSetCommandBuilder) WithPw(pw uint32) *UpdateSetCommandBuilder { builder.protobuf.Pw = &pw return builder } // WithDw (durable writes) sets the number of nodes that must report back a successful write to // backend storage in order for the command operation to be considered a success by Riak. If // ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateSetCommandBuilder) WithDw(dw uint32) *UpdateSetCommandBuilder { builder.protobuf.Dw = &dw return builder } // WithReturnBody sets Riak to return the value within its response after completing the write // operation func (builder *UpdateSetCommandBuilder) WithReturnBody(returnBody bool) *UpdateSetCommandBuilder { builder.protobuf.ReturnBody = &returnBody return builder } // WithTimeout sets a timeout to be used for this command operation func (builder *UpdateSetCommandBuilder) WithTimeout(timeout time.Duration) *UpdateSetCommandBuilder { timeoutMilliseconds := uint32(timeout / time.Millisecond) builder.timeout = timeout builder.protobuf.Timeout = &timeoutMilliseconds return builder } // Build validates the configuration options provided then builds the command func (builder *UpdateSetCommandBuilder) Build() (Command, error) { if builder.protobuf == nil { panic("builder.protobuf must not be nil") } if err := validateLocatable(builder.protobuf); err != nil { return nil, err } return &UpdateSetCommand{ timeoutImpl: timeoutImpl{ timeout: builder.timeout, }, protobuf: builder.protobuf, }, nil } // FetchSet // DtFetchReq // DtFetchResp // FetchSetCommand fetches a set CRDT from Riak type FetchSetCommand struct { commandImpl timeoutImpl retryableCommandImpl Response *FetchSetResponse protobuf *rpbRiakDT.DtFetchReq } // Name identifies this command func (cmd *FetchSetCommand) Name() string { return cmd.getName("FetchSet") } func (cmd *FetchSetCommand) constructPbRequest() (proto.Message, error) { return cmd.protobuf, nil } func (cmd *FetchSetCommand) onSuccess(msg proto.Message) error { cmd.success = true if msg != nil { if rpbDtFetchResp, ok := msg.(*rpbRiakDT.DtFetchResp); ok { response := &FetchSetResponse{ Context: rpbDtFetchResp.GetContext(), } rpbValue := rpbDtFetchResp.GetValue() if rpbValue == nil { response.IsNotFound = true } else { response.SetValue = rpbValue.GetSetValue() } cmd.Response = response } else { return fmt.Errorf("[FetchSetCommand] could not convert %v to DtFetchResp", reflect.TypeOf(msg)) } } return nil } func (cmd *FetchSetCommand) getRequestCode() byte { return rpbCode_DtFetchReq } func (cmd *FetchSetCommand) getResponseCode() byte { return rpbCode_DtFetchResp } func (cmd *FetchSetCommand) getResponseProtobufMessage() proto.Message { return &rpbRiakDT.DtFetchResp{} } // FetchSetResponse contains the response data for a FetchSetCommand type FetchSetResponse struct { IsNotFound bool Context []byte SetValue [][]byte } // FetchSetCommandBuilder type is required for creating new instances of FetchSetCommand // // command := NewFetchSetCommandBuilder(). // WithBucketType("myBucketType"). // WithBucket("myBucket"). // WithKey("myKey"). // Build() type FetchSetCommandBuilder struct { timeout time.Duration protobuf *rpbRiakDT.DtFetchReq } // NewFetchSetCommandBuilder is a factory function for generating the command builder struct func NewFetchSetCommandBuilder() *FetchSetCommandBuilder { return &FetchSetCommandBuilder{protobuf: &rpbRiakDT.DtFetchReq{}} } // WithBucketType sets the bucket-type to be used by the command. If omitted, 'default' is used func (builder *FetchSetCommandBuilder) WithBucketType(bucketType string) *FetchSetCommandBuilder { builder.protobuf.Type = []byte(bucketType) return builder } // WithBucket sets the bucket to be used by the command func (builder *FetchSetCommandBuilder) WithBucket(bucket string) *FetchSetCommandBuilder { builder.protobuf.Bucket = []byte(bucket) return builder } // WithKey sets the key to be used by the command to read / write values func (builder *FetchSetCommandBuilder) WithKey(key string) *FetchSetCommandBuilder { builder.protobuf.Key = []byte(key) return builder } // WithR sets the number of nodes that must report back a successful read in order for the // command operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *FetchSetCommandBuilder) WithR(r uint32) *FetchSetCommandBuilder { builder.protobuf.R = &r return builder } // WithPr sets the number of primary nodes (N) that must be read from in order for the command // operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *FetchSetCommandBuilder) WithPr(pr uint32) *FetchSetCommandBuilder { builder.protobuf.Pr = &pr return builder } // WithNotFoundOk sets notfound_ok, whether to treat notfounds as successful reads for the purposes // of R // // See http://basho.com/posts/technical/riaks-config-behaviors-part-3/ func (builder *FetchSetCommandBuilder) WithNotFoundOk(notFoundOk bool) *FetchSetCommandBuilder { builder.protobuf.NotfoundOk = &notFoundOk return builder } // WithBasicQuorum sets basic_quorum, whether to return early in some failure cases (eg. when r=1 // and you get 2 errors and a success basic_quorum=true would return an error) // // See http://basho.com/posts/technical/riaks-config-behaviors-part-3/ func (builder *FetchSetCommandBuilder) WithBasicQuorum(basicQuorum bool) *FetchSetCommandBuilder { builder.protobuf.BasicQuorum = &basicQuorum return builder } // WithTimeout sets a timeout to be used for this command operation func (builder *FetchSetCommandBuilder) WithTimeout(timeout time.Duration) *FetchSetCommandBuilder { timeoutMilliseconds := uint32(timeout / time.Millisecond) builder.timeout = timeout builder.protobuf.Timeout = &timeoutMilliseconds return builder } // Build validates the configuration options provided then builds the command func (builder *FetchSetCommandBuilder) Build() (Command, error) { if builder.protobuf == nil { panic("builder.protobuf must not be nil") } if err := validateLocatable(builder.protobuf); err != nil { return nil, err } return &FetchSetCommand{ timeoutImpl: timeoutImpl{ timeout: builder.timeout, }, protobuf: builder.protobuf, }, nil } // UpdateMap // DtUpdateReq // DtUpdateResp // UpdateMapCommand updates a map CRDT in Riak type UpdateMapCommand struct { commandImpl timeoutImpl retryableCommandImpl Response *UpdateMapResponse op *MapOperation protobuf *rpbRiakDT.DtUpdateReq } // Name identifies this command func (cmd *UpdateMapCommand) Name() string { return cmd.getName("UpdateMap") } func (cmd *UpdateMapCommand) constructPbRequest() (proto.Message, error) { pbMapOp := &rpbRiakDT.MapOp{} populate(cmd.op, pbMapOp) cmd.protobuf.Op = &rpbRiakDT.DtOp{ MapOp: pbMapOp, } return cmd.protobuf, nil } func (cmd *UpdateMapCommand) onSuccess(msg proto.Message) error { cmd.success = true if msg != nil { if rpbDtUpdateResp, ok := msg.(*rpbRiakDT.DtUpdateResp); ok { response := &UpdateMapResponse{ GeneratedKey: string(rpbDtUpdateResp.GetKey()), Context: rpbDtUpdateResp.GetContext(), Map: parsePbResponse(rpbDtUpdateResp.GetMapValue()), } cmd.Response = response } else { return fmt.Errorf("[UpdateMapCommand] could not convert %v to DtUpdateResp", reflect.TypeOf(msg)) } } return nil } func (cmd *UpdateMapCommand) getRequestCode() byte { return rpbCode_DtUpdateReq } func (cmd *UpdateMapCommand) getResponseCode() byte { return rpbCode_DtUpdateResp } func (cmd *UpdateMapCommand) getResponseProtobufMessage() proto.Message { return &rpbRiakDT.DtUpdateResp{} } func addMapUpdate(pbMapOp *rpbRiakDT.MapOp, update *rpbRiakDT.MapUpdate) { pbMapOp.Updates = append(pbMapOp.Updates, update) } func addMapRemove(pbMapOp *rpbRiakDT.MapOp, field *rpbRiakDT.MapField) { pbMapOp.Removes = append(pbMapOp.Removes, field) } func populate(mapOp *MapOperation, pbMapOp *rpbRiakDT.MapOp) { if mapOp.hasRemoves(false) { for name := range mapOp.removeCounters { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_COUNTER.Enum(), } addMapRemove(pbMapOp, field) } for name := range mapOp.removeSets { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_SET.Enum(), } addMapRemove(pbMapOp, field) } for name := range mapOp.removeMaps { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_MAP.Enum(), } addMapRemove(pbMapOp, field) } for name := range mapOp.removeRegisters { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_REGISTER.Enum(), } addMapRemove(pbMapOp, field) } for name := range mapOp.removeFlags { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_FLAG.Enum(), } addMapRemove(pbMapOp, field) } } for name, increment := range mapOp.incrementCounters { i := increment field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_COUNTER.Enum(), } counterOp := &rpbRiakDT.CounterOp{ Increment: &i, } update := &rpbRiakDT.MapUpdate{ Field: field, CounterOp: counterOp, } addMapUpdate(pbMapOp, update) } for name, adds := range mapOp.addToSets { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_SET.Enum(), } setOp := &rpbRiakDT.SetOp{ Adds: make([][]byte, len(adds)), } for i, add := range adds { setOp.Adds[i] = add } update := &rpbRiakDT.MapUpdate{ Field: field, SetOp: setOp, } addMapUpdate(pbMapOp, update) } for name, removes := range mapOp.removeFromSets { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_SET.Enum(), } setOp := &rpbRiakDT.SetOp{ Removes: make([][]byte, len(removes)), } for i, remove := range removes { setOp.Removes[i] = remove } update := &rpbRiakDT.MapUpdate{ Field: field, SetOp: setOp, } addMapUpdate(pbMapOp, update) } for name, register := range mapOp.registersToSet { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_REGISTER.Enum(), } update := &rpbRiakDT.MapUpdate{ Field: field, RegisterOp: register, } addMapUpdate(pbMapOp, update) } for name, flag := range mapOp.flagsToSet { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_FLAG.Enum(), } var flagOp rpbRiakDT.MapUpdate_FlagOp if flag { flagOp = rpbRiakDT.MapUpdate_ENABLE } else { flagOp = rpbRiakDT.MapUpdate_DISABLE } update := &rpbRiakDT.MapUpdate{ Field: field, FlagOp: flagOp.Enum(), } addMapUpdate(pbMapOp, update) } for name, mapOp := range mapOp.maps { field := &rpbRiakDT.MapField{ Name: []byte(name), Type: rpbRiakDT.MapField_MAP.Enum(), } nestedMapOp := &rpbRiakDT.MapOp{} populate(mapOp, nestedMapOp) update := &rpbRiakDT.MapUpdate{ Field: field, MapOp: nestedMapOp, } addMapUpdate(pbMapOp, update) } } // MapOperation contains the instructions to send to Riak what updates to the Map you want to complete type MapOperation struct { incrementCounters map[string]int64 removeCounters map[string]bool addToSets map[string][][]byte removeFromSets map[string][][]byte removeSets map[string]bool registersToSet map[string][]byte removeRegisters map[string]bool flagsToSet map[string]bool removeFlags map[string]bool maps map[string]*MapOperation removeMaps map[string]bool } // IncrementCounter increments a child counter CRDT of the map at the specified key func (mapOp *MapOperation) IncrementCounter(key string, increment int64) *MapOperation { if mapOp.removeCounters != nil { delete(mapOp.removeCounters, key) } if mapOp.incrementCounters == nil { mapOp.incrementCounters = make(map[string]int64) } mapOp.incrementCounters[key] += increment return mapOp } // RemoveCounter removes a child counter CRDT from the map at the specified key func (mapOp *MapOperation) RemoveCounter(key string) *MapOperation { if mapOp.incrementCounters != nil { delete(mapOp.incrementCounters, key) } if mapOp.removeCounters == nil { mapOp.removeCounters = make(map[string]bool) } mapOp.removeCounters[key] = true return mapOp } // AddToSet adds an element to the child set CRDT of the map at the specified key func (mapOp *MapOperation) AddToSet(key string, value []byte) *MapOperation { if mapOp.removeSets != nil { delete(mapOp.removeSets, key) } if mapOp.addToSets == nil { mapOp.addToSets = make(map[string][][]byte) } mapOp.addToSets[key] = append(mapOp.addToSets[key], value) return mapOp } // RemoveFromSet removes elements from the child set CRDT of the map at the specified key func (mapOp *MapOperation) RemoveFromSet(key string, value []byte) *MapOperation { if mapOp.removeSets != nil { delete(mapOp.removeSets, key) } if mapOp.removeFromSets == nil { mapOp.removeFromSets = make(map[string][][]byte) } mapOp.removeFromSets[key] = append(mapOp.removeFromSets[key], value) return mapOp } // RemoveSet removes the child set CRDT from the map func (mapOp *MapOperation) RemoveSet(key string) *MapOperation { if mapOp.addToSets != nil { delete(mapOp.addToSets, key) } if mapOp.removeFromSets != nil { delete(mapOp.removeFromSets, key) } if mapOp.removeSets == nil { mapOp.removeSets = make(map[string]bool) } mapOp.removeSets[key] = true return mapOp } // SetRegister sets a register CRDT on the map with the provided value func (mapOp *MapOperation) SetRegister(key string, value []byte) *MapOperation { if mapOp.removeRegisters != nil { delete(mapOp.removeRegisters, key) } if mapOp.registersToSet == nil { mapOp.registersToSet = make(map[string][]byte) } mapOp.registersToSet[key] = value return mapOp } // RemoveRegister removes a register CRDT from the map func (mapOp *MapOperation) RemoveRegister(key string) *MapOperation { if mapOp.registersToSet != nil { delete(mapOp.registersToSet, key) } if mapOp.removeRegisters == nil { mapOp.removeRegisters = make(map[string]bool) } mapOp.removeRegisters[key] = true return mapOp } // SetFlag sets a flag CRDT on the map func (mapOp *MapOperation) SetFlag(key string, value bool) *MapOperation { if mapOp.removeFlags != nil { delete(mapOp.removeFlags, key) } if mapOp.flagsToSet == nil { mapOp.flagsToSet = make(map[string]bool) } mapOp.flagsToSet[key] = value return mapOp } // RemoveFlag removes a flag CRDT from the map func (mapOp *MapOperation) RemoveFlag(key string) *MapOperation { if mapOp.flagsToSet != nil { delete(mapOp.flagsToSet, key) } if mapOp.removeFlags == nil { mapOp.removeFlags = make(map[string]bool) } mapOp.removeFlags[key] = true return mapOp } // Map returns a nested map operation for manipulation func (mapOp *MapOperation) Map(key string) *MapOperation { if mapOp.removeMaps != nil { delete(mapOp.removeMaps, key) } if mapOp.maps == nil { mapOp.maps = make(map[string]*MapOperation) } innerMapOp, ok := mapOp.maps[key] if ok { return innerMapOp } innerMapOp = &MapOperation{} mapOp.maps[key] = innerMapOp return innerMapOp } // RemoveMap removes a nested map from the map func (mapOp *MapOperation) RemoveMap(key string) *MapOperation { if mapOp.maps != nil { delete(mapOp.maps, key) } if mapOp.removeMaps == nil { mapOp.removeMaps = make(map[string]bool) } mapOp.removeMaps[key] = true return mapOp } func (mapOp *MapOperation) hasRemoves(includeRemoveFromSets bool) bool { nestedHaveRemoves := false for _, m := range mapOp.maps { if m.hasRemoves(false) { nestedHaveRemoves = true break } } rv := nestedHaveRemoves || len(mapOp.removeCounters) > 0 || len(mapOp.removeSets) > 0 || len(mapOp.removeRegisters) > 0 || len(mapOp.removeFlags) > 0 || len(mapOp.removeMaps) > 0 if includeRemoveFromSets { rv = rv || len(mapOp.removeFromSets) > 0 } return rv } func parsePbResponse(pbMapEntries []*rpbRiakDT.MapEntry) *Map { m := &Map{} for _, mapEntry := range pbMapEntries { mapField := mapEntry.GetField() key := string(mapField.GetName()) switch mapField.GetType() { case rpbRiakDT.MapField_COUNTER: if m.Counters == nil { m.Counters = make(map[string]int64) } m.Counters[key] = mapEntry.GetCounterValue() case rpbRiakDT.MapField_SET: if m.Sets == nil { m.Sets = make(map[string][][]byte) } m.Sets[key] = mapEntry.SetValue case rpbRiakDT.MapField_REGISTER: if m.Registers == nil { m.Registers = make(map[string][]byte) } m.Registers[key] = mapEntry.GetRegisterValue() case rpbRiakDT.MapField_FLAG: if m.Flags == nil { m.Flags = make(map[string]bool) } m.Flags[key] = mapEntry.GetFlagValue() case rpbRiakDT.MapField_MAP: if m.Maps == nil { m.Maps = make(map[string]*Map) } m.Maps[key] = parsePbResponse(mapEntry.MapValue) } } return m } // Map object represents the Riak Map object and is returned within the Response objects for both // UpdateMapCommand and FetchMapCommand type Map struct { Counters map[string]int64 Sets map[string][][]byte Registers map[string][]byte Flags map[string]bool Maps map[string]*Map } // UpdateMapResponse contains the response data for a UpdateMapCommand type UpdateMapResponse struct { GeneratedKey string Context []byte Map *Map } // UpdateMapCommandBuilder type is required for creating new instances of UpdateMapCommand // // mapOp := &MapOperation{} // mapOp.SetRegister("register_1", []byte("register_value_1")) // // command := NewUpdateMapCommandBuilder(). // WithBucketType("myBucketType"). // WithBucket("myBucket"). // WithKey("myKey"). // WithMapOperation(mapOp). // Build() type UpdateMapCommandBuilder struct { mapOperation *MapOperation timeout time.Duration protobuf *rpbRiakDT.DtUpdateReq } // NewUpdateMapCommandBuilder is a factory function for generating the command builder struct func NewUpdateMapCommandBuilder() *UpdateMapCommandBuilder { return &UpdateMapCommandBuilder{protobuf: &rpbRiakDT.DtUpdateReq{}} } // WithBucketType sets the bucket-type to be used by the command. If omitted, 'default' is used func (builder *UpdateMapCommandBuilder) WithBucketType(bucketType string) *UpdateMapCommandBuilder { builder.protobuf.Type = []byte(bucketType) return builder } // WithBucket sets the bucket to be used by the command func (builder *UpdateMapCommandBuilder) WithBucket(bucket string) *UpdateMapCommandBuilder { builder.protobuf.Bucket = []byte(bucket) return builder } // WithKey sets the key to be used by the command to read / write values func (builder *UpdateMapCommandBuilder) WithKey(key string) *UpdateMapCommandBuilder { builder.protobuf.Key = []byte(key) return builder } // WithContext sets the causal context needed to identify the state of the map when removing elements func (builder *UpdateMapCommandBuilder) WithContext(context []byte) *UpdateMapCommandBuilder { builder.protobuf.Context = context return builder } // WithMapOperation provides the details of what is supposed to be updated on the map func (builder *UpdateMapCommandBuilder) WithMapOperation(mapOperation *MapOperation) *UpdateMapCommandBuilder { builder.mapOperation = mapOperation return builder } // WithW sets the number of nodes that must report back a successful write in order for then // command operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateMapCommandBuilder) WithW(w uint32) *UpdateMapCommandBuilder { builder.protobuf.W = &w return builder } // WithPw sets the number of primary nodes (N) that must report back a successful write in order for // the command operation to be considered a success by Riak. If ommitted, the bucket default is // used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateMapCommandBuilder) WithPw(pw uint32) *UpdateMapCommandBuilder { builder.protobuf.Pw = &pw return builder } // WithDw (durable writes) sets the number of nodes that must report back a successful write to // backend storage in order for the command operation to be considered a success by Riak. If // ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *UpdateMapCommandBuilder) WithDw(dw uint32) *UpdateMapCommandBuilder { builder.protobuf.Dw = &dw return builder } // WithReturnBody sets Riak to return the value within its response after completing the write // operation func (builder *UpdateMapCommandBuilder) WithReturnBody(returnBody bool) *UpdateMapCommandBuilder { builder.protobuf.ReturnBody = &returnBody return builder } // WithTimeout sets a timeout in milliseconds to be used for this command operation func (builder *UpdateMapCommandBuilder) WithTimeout(timeout time.Duration) *UpdateMapCommandBuilder { timeoutMilliseconds := uint32(timeout / time.Millisecond) builder.timeout = timeout builder.protobuf.Timeout = &timeoutMilliseconds return builder } // Build validates the configuration options provided then builds the command func (builder *UpdateMapCommandBuilder) Build() (Command, error) { if builder.protobuf == nil { panic("builder.protobuf must not be nil") } if err := validateLocatable(builder.protobuf); err != nil { return nil, err } if builder.mapOperation == nil { return nil, newClientError("UpdateMapCommandBuilder requires non-nil MapOperation. Use WithMapOperation()", nil) } if builder.mapOperation.hasRemoves(true) && builder.protobuf.GetContext() == nil { return nil, newClientError("When doing any removes a context must be provided.", nil) } return &UpdateMapCommand{ timeoutImpl: timeoutImpl{ timeout: builder.timeout, }, protobuf: builder.protobuf, op: builder.mapOperation, }, nil } // FetchMap // DtFetchReq // DtFetchResp // FetchMapCommand fetches a map CRDT from Riak type FetchMapCommand struct { commandImpl timeoutImpl retryableCommandImpl Response *FetchMapResponse protobuf *rpbRiakDT.DtFetchReq } // Name identifies this command func (cmd *FetchMapCommand) Name() string { return cmd.getName("FetchMap") } func (cmd *FetchMapCommand) constructPbRequest() (proto.Message, error) { return cmd.protobuf, nil } func (cmd *FetchMapCommand) onSuccess(msg proto.Message) error { cmd.success = true if msg != nil { if rpbDtFetchResp, ok := msg.(*rpbRiakDT.DtFetchResp); ok { response := &FetchMapResponse{ Context: rpbDtFetchResp.GetContext(), } rpbValue := rpbDtFetchResp.GetValue() if rpbValue == nil { response.IsNotFound = true } else { rpbMapValue := rpbValue.GetMapValue() if rpbMapValue == nil { response.IsNotFound = true } else { response.Map = parsePbResponse(rpbMapValue) } } cmd.Response = response } else { return fmt.Errorf("[FetchMapCommand] could not convert %v to DtFetchResp", reflect.TypeOf(msg)) } } return nil } func (cmd *FetchMapCommand) getRequestCode() byte { return rpbCode_DtFetchReq } func (cmd *FetchMapCommand) getResponseCode() byte { return rpbCode_DtFetchResp } func (cmd *FetchMapCommand) getResponseProtobufMessage() proto.Message { return &rpbRiakDT.DtFetchResp{} } // FetchMapResponse contains the response data for a FetchMapCommand type FetchMapResponse struct { IsNotFound bool Context []byte Map *Map } // FetchMapCommandBuilder type is required for creating new instances of FetchMapCommand // // command := NewFetchMapCommandBuilder(). // WithBucketType("myBucketType"). // WithBucket("myBucket"). // WithKey("myKey"). // Build() type FetchMapCommandBuilder struct { timeout time.Duration protobuf *rpbRiakDT.DtFetchReq } // NewFetchMapCommandBuilder is a factory function for generating the command builder struct func NewFetchMapCommandBuilder() *FetchMapCommandBuilder { return &FetchMapCommandBuilder{protobuf: &rpbRiakDT.DtFetchReq{}} } // WithBucketType sets the bucket-type to be used by the command. If omitted, 'default' is used func (builder *FetchMapCommandBuilder) WithBucketType(bucketType string) *FetchMapCommandBuilder { builder.protobuf.Type = []byte(bucketType) return builder } // WithBucket sets the bucket to be used by the command func (builder *FetchMapCommandBuilder) WithBucket(bucket string) *FetchMapCommandBuilder { builder.protobuf.Bucket = []byte(bucket) return builder } // WithKey sets the key to be used by the command to read / write values func (builder *FetchMapCommandBuilder) WithKey(key string) *FetchMapCommandBuilder { builder.protobuf.Key = []byte(key) return builder } // WithR sets the number of nodes that must report back a successful read in order for the // command operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *FetchMapCommandBuilder) WithR(r uint32) *FetchMapCommandBuilder { builder.protobuf.R = &r return builder } // WithPr sets the number of primary nodes (N) that must be read from in order for the command // operation to be considered a success by Riak. If ommitted, the bucket default is used. // // See http://basho.com/posts/technical/riaks-config-behaviors-part-2/ func (builder *FetchMapCommandBuilder) WithPr(pr uint32) *FetchMapCommandBuilder { builder.protobuf.Pr = &pr return builder } // WithNotFoundOk sets notfound_ok, whether to treat notfounds as successful reads for the purposes // of R // // See http://basho.com/posts/technical/riaks-config-behaviors-part-3/ func (builder *FetchMapCommandBuilder) WithNotFoundOk(notFoundOk bool) *FetchMapCommandBuilder { builder.protobuf.NotfoundOk = &notFoundOk return builder } // WithBasicQuorum sets basic_quorum, whether to return early in some failure cases (eg. when r=1 // and you get 2 errors and a success basic_quorum=true would return an error) // // See http://basho.com/posts/technical/riaks-config-behaviors-part-3/ func (builder *FetchMapCommandBuilder) WithBasicQuorum(basicQuorum bool) *FetchMapCommandBuilder { builder.protobuf.BasicQuorum = &basicQuorum return builder } // WithTimeout sets a timeout in milliseconds to be used for this command operation func (builder *FetchMapCommandBuilder) WithTimeout(timeout time.Duration) *FetchMapCommandBuilder { timeoutMilliseconds := uint32(timeout / time.Millisecond) builder.timeout = timeout builder.protobuf.Timeout = &timeoutMilliseconds return builder } // Build validates the configuration options provided then builds the command func (builder *FetchMapCommandBuilder) Build() (Command, error) { if builder.protobuf == nil { panic("builder.protobuf must not be nil") } if err := validateLocatable(builder.protobuf); err != nil { return nil, err } return &FetchMapCommand{ timeoutImpl: timeoutImpl{ timeout: builder.timeout, }, protobuf: builder.protobuf, }, nil }
dotJEM/angular-lessons
src/assets/lib/bower/dotjem-angular-routing/dev/files.js
<gh_stars>0 if (exports) { var files = { 'src': [ 'src/prefix', 'build/src/common.js', 'build/src/route.js', 'build/src/stateTransition.js', 'build/src/state.js', 'build/src/resolve.js', 'build/src/template.js', 'build/src/view.js', 'build/src/scroll.js', 'build/src/inject.js', 'build/src/state/state.js', 'build/src/state/stateBrowser.js', 'build/src/state/stateComparer.js', 'build/src/state/stateFactory.js', 'build/src/state/stateRules.js', 'build/src/state/stateUrlBuilder.js', 'build/src/state/transition/commands.js', 'build/src/state/transition/context.js', 'build/src/directives/jemView.js', 'build/src/directives/jemAnchor.js', 'build/src/directives/jemLink.js', 'src/suffix' ], 'legacy': [ 'src/legacy/prefix', 'build/src/legacy/templateDecorator.js', 'src/legacy/suffix' ] }; exports.files = files; }
AlexandreMorinvil/music_paradigm
music_paradigm_web/src/store-helper/sound-generator.module-helper/default-state.js
<filename>music_paradigm_web/src/store-helper/sound-generator.module-helper/default-state.js const FIRST_AUDIO_RESSOURCE_NAME = 'audio-1'; const SECOND_AUDIO_RESSOURCE_NAME = 'audio-2'; function EMPTY_RESSOURCE_STATE() { return { // Loading information isLoading: false, // Content information fileName: '', arrayStream: null, processedContent: null, }; } function DEFAULT_SOUND_GENERATOR_STATE() { const defaultState = { isInitialized: false, audioContext: null, instrument: null, }; defaultState[FIRST_AUDIO_RESSOURCE_NAME] = EMPTY_RESSOURCE_STATE(); defaultState[SECOND_AUDIO_RESSOURCE_NAME] = EMPTY_RESSOURCE_STATE(); return defaultState; } export default { FIRST_AUDIO_RESSOURCE_NAME, SECOND_AUDIO_RESSOURCE_NAME, EMPTY_RESSOURCE_STATE, DEFAULT_SOUND_GENERATOR_STATE, };
mosoft521/appfuse
web/gwt/src/main/java/org/appfuse/webapp/client/ui/users/active/ActiveUsersActivity.java
/** * */ package org.appfuse.webapp.client.ui.users.active; import java.util.List; import org.appfuse.webapp.client.application.Application; import org.appfuse.webapp.client.application.base.activity.AbstractBaseActivity; import org.appfuse.webapp.client.proxies.UserProxy; import org.appfuse.webapp.client.ui.home.HomePlace; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.ColumnSortEvent; import com.google.gwt.user.cellview.client.ColumnSortEvent.Handler; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.inject.Inject; import com.google.web.bindery.requestfactory.shared.Receiver; /** * @author ivangsa * */ public class ActiveUsersActivity extends AbstractBaseActivity implements ActiveUsersView.Delegate { private final ActiveUsersView view; private Handler clientSideSortHandler; @Inject public ActiveUsersActivity(final Application application, final ActiveUsersView view) { super(application); setTitle(i18n.activeUsers_title()); this.view = view; } @Override public void start(final AcceptsOneWidget panel, final EventBus eventBus) { view.setDelegate(this); panel.setWidget(view); setDocumentTitleAndBodyAttributtes(); final CellTable<UserProxy> cellTable = view.getCellTable(); requests.userRequest().getActiveUsers().fire(new Receiver<List<UserProxy>>() { @Override public void onSuccess(final List<UserProxy> activeUsers) { clientSideSortHandler = new ColumnSortEvent.ListHandler<UserProxy>(activeUsers); cellTable.addColumnSortHandler(clientSideSortHandler); cellTable.setRowData(activeUsers); cellTable.setPageSize(25); } }); } @Override public void cancelClicked() { placeController.goTo(new HomePlace()); } }
Francis777/agents
tf_agents/tf_agents_api_test.py
<gh_stars>1000+ # coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests TF-Agents API root.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tf_agents class RootAPITest(tf.test.TestCase): def test_entries(self): # Ensure that some of the basics exist # pylint: disable=pointless-statement tf_agents.agents tf_agents.experimental tf_agents.policies tf_agents.networks tf_agents.bandits.agents tf_agents.bandits.policies tf_agents.bandits.networks # pylint: disable=pointless-statement if __name__ == '__main__': tf.test.main()
kongaraju/antkorp
3party/gtk+-3.12.1/gtk/a11y/gtkscrolledwindowaccessible.c
<filename>3party/gtk+-3.12.1/gtk/a11y/gtkscrolledwindowaccessible.c /* GTK+ - accessibility implementations * Copyright 2001, 2002, 2003 Sun Microsystems Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <gtk/gtk.h> #include "gtkscrolledwindowaccessible.h" G_DEFINE_TYPE (GtkScrolledWindowAccessible, gtk_scrolled_window_accessible, GTK_TYPE_CONTAINER_ACCESSIBLE) static void visibility_changed (GObject *object, GParamSpec *pspec, gpointer user_data) { if (!g_strcmp0 (pspec->name, "visible")) { gint index; gint n_children; gboolean child_added = FALSE; GList *children; AtkObject *child; GtkWidget *widget; GtkScrolledWindow *scrolled_window; GtkWidget *hscrollbar, *vscrollbar; GtkAccessible *accessible = GTK_ACCESSIBLE (user_data); widget = gtk_accessible_get_widget (user_data); if (widget == NULL) return; scrolled_window = GTK_SCROLLED_WINDOW (widget); children = gtk_container_get_children (GTK_CONTAINER (widget)); index = n_children = g_list_length (children); g_list_free (children); hscrollbar = gtk_scrolled_window_get_hscrollbar (scrolled_window); vscrollbar = gtk_scrolled_window_get_vscrollbar (scrolled_window); if ((gpointer) object == (gpointer) (hscrollbar)) { if (gtk_scrolled_window_get_hscrollbar (scrolled_window)) child_added = TRUE; child = gtk_widget_get_accessible (hscrollbar); } else if ((gpointer) object == (gpointer) (vscrollbar)) { if (gtk_scrolled_window_get_vscrollbar (scrolled_window)) child_added = TRUE; child = gtk_widget_get_accessible (vscrollbar); if (gtk_scrolled_window_get_hscrollbar (scrolled_window)) index = n_children + 1; } else { g_assert_not_reached (); return; } if (child_added) g_signal_emit_by_name (accessible, "children-changed::add", index, child, NULL); else g_signal_emit_by_name (accessible, "children-changed::remove", index, child, NULL); } } static void gtk_scrolled_window_accessible_initialize (AtkObject *obj, gpointer data) { GtkScrolledWindow *window; ATK_OBJECT_CLASS (gtk_scrolled_window_accessible_parent_class)->initialize (obj, data); window = GTK_SCROLLED_WINDOW (data); g_signal_connect_data (gtk_scrolled_window_get_hscrollbar (window), "notify::visible", G_CALLBACK (visibility_changed), obj, NULL, FALSE); g_signal_connect_data (gtk_scrolled_window_get_vscrollbar (window), "notify::visible", G_CALLBACK (visibility_changed), obj, NULL, FALSE); obj->role = ATK_ROLE_SCROLL_PANE; } static gint gtk_scrolled_window_accessible_get_n_children (AtkObject *object) { GtkWidget *widget; GtkScrolledWindow *scrolled_window; GList *children; gint n_children; widget = gtk_accessible_get_widget (GTK_ACCESSIBLE (object)); if (widget == NULL) return 0; scrolled_window = GTK_SCROLLED_WINDOW (widget); children = gtk_container_get_children (GTK_CONTAINER (widget)); n_children = g_list_length (children); g_list_free (children); if (gtk_scrolled_window_get_hscrollbar (scrolled_window)) n_children++; if (gtk_scrolled_window_get_vscrollbar (scrolled_window)) n_children++; return n_children; } static AtkObject * gtk_scrolled_window_accessible_ref_child (AtkObject *obj, gint child) { GtkWidget *widget; GtkScrolledWindow *scrolled_window; GtkWidget *hscrollbar, *vscrollbar; GList *children, *tmp_list; gint n_children; AtkObject *accessible = NULL; g_return_val_if_fail (child >= 0, NULL); widget = gtk_accessible_get_widget (GTK_ACCESSIBLE (obj)); if (widget == NULL) return NULL; scrolled_window = GTK_SCROLLED_WINDOW (widget); hscrollbar = gtk_scrolled_window_get_hscrollbar (scrolled_window); vscrollbar = gtk_scrolled_window_get_vscrollbar (scrolled_window); children = gtk_container_get_children (GTK_CONTAINER (widget)); n_children = g_list_length (children); if (child == n_children) { if (gtk_scrolled_window_get_hscrollbar (scrolled_window)) accessible = gtk_widget_get_accessible (hscrollbar); else if (gtk_scrolled_window_get_vscrollbar (scrolled_window)) accessible = gtk_widget_get_accessible (vscrollbar); } else if (child == n_children + 1 && gtk_scrolled_window_get_hscrollbar (scrolled_window) && gtk_scrolled_window_get_vscrollbar (scrolled_window)) accessible = gtk_widget_get_accessible (vscrollbar); else if (child < n_children) { tmp_list = g_list_nth (children, child); if (tmp_list) accessible = gtk_widget_get_accessible (GTK_WIDGET (tmp_list->data)); } g_list_free (children); if (accessible) g_object_ref (accessible); return accessible; } static void gtk_scrolled_window_accessible_class_init (GtkScrolledWindowAccessibleClass *klass) { AtkObjectClass *class = ATK_OBJECT_CLASS (klass); class->get_n_children = gtk_scrolled_window_accessible_get_n_children; class->ref_child = gtk_scrolled_window_accessible_ref_child; class->initialize = gtk_scrolled_window_accessible_initialize; } static void gtk_scrolled_window_accessible_init (GtkScrolledWindowAccessible *window) { }
washad/ControlPyWeb
build/lib/controlpyweb/webio_module.py
from controlpyweb.errors import ControlPyWebAddressNotFoundError from controlpyweb.reader_writer import ReaderWriter import datetime from controlpyweb.io_definitions.single_io import SingleIO class WebIOModule(ReaderWriter): def __init__(self, url: str, demand_address_exists: bool = True): super().__init__(url, demand_address_exists) self.members = [] all_members = [d for d in dir(self) if not d.startswith('__')] for member in all_members: try: attr = getattr(self, member) if not isinstance(attr, SingleIO): continue attr._reader_writer = self self.members.append(member) except AttributeError: pass def _read_safe(self, addr: str): try: return self.read(addr) except ControlPyWebAddressNotFoundError: return None @property def serial_number(self) -> str: return self._read_safe("serialNumber") @property def vin(self) -> float: response = self._read_safe("vin") if response is None: return -1 return float(response) @property def time_of_read(self): response = self._read_safe("utcTime") if response is None: return datetime.datetime.min return datetime.datetime.fromtimestamp(int(response)) if __name__ == '__main__': pass
Intro-to-Software-Team-9a/Estate-Plan-R
client/src/utils/format.js
<reponame>Intro-to-Software-Team-9a/Estate-Plan-R export function formatCurrency(amountInCents) { return `$${(amountInCents / 100).toFixed(2)}`; } export default formatCurrency;
ZHAOZhengyi-tgx/BE-Supporter_2016
BE_Supporter/MtnAlgo/MTNCALC/H/poly7_bnd.h
//The MIT License (MIT) // //Copyright (c) 2016 ZHAOZhengyi-tgx // //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. // (c)All right reserved, <EMAIL> #pragma once #define POLY_7(k0, k1, k2, k3, k4, k5, k6, k7, x) (k0 + x*(k1 + x*(k2 + x*(k3 + x*(k4 + x* (k5 + x* (k6 + x * k7))))))) // 20081013 typedef struct { unsigned int TimeT_ini; double dDist; double dVelIni; double dVelEnd; double dAccIni; double dAccEnd; double dJerkIni; double dJerkEnd; }POLY7_CALC_K_BY_TIME_INPUT; typedef struct { unsigned int TimeT_ini; double dDist; double dVelIni; double dVelEnd; double dAccIni; double dAccEnd; double dJerkIni; double dJerkEnd; double dK4; double dK5; double dK6; double dK7; }POLY7_CALC_K_BY_TIME_OUTPUT; #define NUM_ROW_MATRIX 4 #define NUM_COL_MATRIX 4 typedef struct { double aMatrix[NUM_ROW_MATRIX * NUM_COL_MATRIX]; double aInvMatrix[NUM_ROW_MATRIX * NUM_COL_MATRIX]; double aRHS[NUM_ROW_MATRIX]; double aSolution[NUM_ROW_MATRIX]; }POLY7_CALC_K_BY_TIME_DEBUG; int poly7_calc_k_by_time(POLY7_CALC_K_BY_TIME_INPUT *stpInput, POLY7_CALC_K_BY_TIME_OUTPUT *stpOutput, POLY7_CALC_K_BY_TIME_DEBUG *stpDebug); typedef struct { unsigned int TimeT_ini; double dDist; double dVelIni; double dVelEnd; double dAccIni; double dAccEnd; double dJerkIni; double dJerkEnd; double dK4; double dK5; double dK6; double dK7; }POLY7_GEN_PROF_INPUT; typedef struct { double *pdDistProf; double *pdVelProf; double *pdAccProf; double *pdJerkProf; }POLY7_GEN_PROF_OUTPUT; void poly7_generate_prof(POLY7_GEN_PROF_INPUT *stpInput, POLY7_GEN_PROF_OUTPUT *stpOutput); void poly7_generate_vel_prof(POLY7_GEN_PROF_INPUT *stpInput, POLY7_GEN_PROF_OUTPUT *stpOutput); unsigned int get_time_prof7_verify_looping_vel_not_change_sign(POLY7_CALC_K_BY_TIME_INPUT *stpInput, unsigned int uiTimeT_min, unsigned int uiTimeT_max);
KingDragon08/Labi-Android
client/src/main/java/cn/wildfirechat/model/NullGroupInfo.java
package cn.wildfirechat.model; public class NullGroupInfo extends GroupInfo { public NullGroupInfo(String groupId) { this.target = groupId; this.name = "<" + groupId + ">"; } }
itaffy/antd-vue-admin-pro
src/project/system/api/param.js
import request from '@/api/index' // APP版本列表 export function appVersionList(params) { return request.get('/appversions', params) } // 添加APP版本 export function addAppVersion(params) { return request.post('/appversion', params) } // 编辑APP版本 export function editAppVersion(params, id) { return request.putJson('/appversion/' + id, params) } // 删除APP版本 export function deleteAppVersion(id) { return request.delete('/appversion/' + id) } // 首页模块列表 export function getHomeListAPI(params) { return request.get('/homeModules', params) } // 首页模块列表 export function setHomeStatusAPI(params) { return request.patchJson('/homeModule/enable', params) } // 首页模块列表-获取栏目列表 export function getHomeColumnListAPI(params) { return request.get('/JumpColumnList', params) } // 首页模块列表-编辑入口设置 export function updateHomeEntryAPI(params, id) { return request.putJson('/homeModule/' + id, params) }
tgoprince/menthor-editor
net.menthor.editor/src/net/menthor/editor/v2/ui/popupmenu/TabPopupMenu.java
package net.menthor.editor.v2.ui.popupmenu; /** * ============================================================================================ * Menthor Editor -- Copyright (c) 2015 * * This file is part of Menthor Editor. Menthor Editor is based on TinyUML and as so it is * distributed under the same license terms. * * Menthor Editor is free software; you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * Menthor Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Menthor Editor; * if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301 USA * ============================================================================================ */ import java.awt.Component; import net.menthor.editor.v2.commands.ICommandListener; import net.menthor.editor.v2.ui.generic.GenericPopupMenu; import net.menthor.editor.v2.commands.CommandType; /** * Pop-up shown when right-clicking a tab. * Context: Tab being clicked. * */ public class TabPopupMenu extends GenericPopupMenu<Component> { private static final long serialVersionUID = 8404322926387805476L; public TabPopupMenu(ICommandListener listener, Component tab) { super(listener,tab); createMenuItem("Close This Tab", null, CommandType.CLOSE_THIS); createMenuItem("Close All Other Tabs", null, CommandType.CLOSE_OTHER); createMenuItem("Close All Tabs", null, CommandType.CLOSE_ALL); } }
perfectmak/udacity-devops-capstone
frontend/src/components/TitleValueInfo.js
import React from 'react'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/styles'; const useStyles = makeStyles(theme => ({ root: { padding: theme.spacing(2), }, })); export const TitleValueInfo = ({ title, value }) => { const classes = useStyles(); return (<div className={classes.root}> <Typography variant="h6">{title}</Typography> <Typography variant="body1">{value}</Typography> </div>); };
dxichen/beam
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/AssignWindowsParDoFnFactory.java
<reponame>dxichen/beam /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.dataflow.worker; import static com.google.common.base.Preconditions.checkState; import static org.apache.beam.runners.dataflow.util.Structs.getBytes; import com.google.api.services.dataflow.model.SideInputInfo; import com.google.common.collect.Iterables; import java.util.Collection; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.runners.dataflow.util.CloudObject; import org.apache.beam.runners.dataflow.util.PropertyNames; import org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoFn; import org.apache.beam.runners.dataflow.worker.util.common.worker.Receiver; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.WindowFn; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.WindowingStrategy; import org.joda.time.Instant; /** * A {@link ParDoFnFactory} to create instances of AssignWindowsDoFn according to specifications * from the Dataflow service. */ class AssignWindowsParDoFnFactory implements ParDoFnFactory { @Override public ParDoFn create( PipelineOptions options, CloudObject cloudUserFn, List<SideInputInfo> sideInputInfos, TupleTag<?> mainOutputTag, Map<TupleTag<?>, Integer> outputTupleTagsToReceiverIndices, DataflowExecutionContext<?> executionContext, DataflowOperationContext operationContext) throws Exception { byte[] encodedWindowingStrategy = getBytes(cloudUserFn, PropertyNames.SERIALIZED_FN); WindowingStrategy<?, ?> deserializedWindowingStrategy = GroupAlsoByWindowParDoFnFactory.deserializeWindowingStrategy(encodedWindowingStrategy); @SuppressWarnings("unchecked") WindowingStrategy<Object, BoundedWindow> windowingStrategy = (WindowingStrategy<Object, BoundedWindow>) deserializedWindowingStrategy; return new AssignWindowsParDoFn<>( windowingStrategy.getWindowFn(), executionContext.getStepContext(operationContext)); } private static class AssignWindowsParDoFn<T, W extends BoundedWindow> implements ParDoFn { private final DataflowExecutionContext.DataflowStepContext stepContext; private final WindowFn<T, W> windowFn; @Nullable private Receiver receiver; AssignWindowsParDoFn( WindowFn<T, W> windowFn, DataflowExecutionContext.DataflowStepContext stepContext) { this.stepContext = stepContext; this.windowFn = windowFn; } @Override public void startBundle(Receiver... receivers) throws Exception { checkState( receivers.length == 1, "%s.startBundle() called with %s receivers, expected exactly 1. " + "This is a bug in the Dataflow service", getClass().getSimpleName(), receivers.length); receiver = receivers[0]; } @Override @SuppressWarnings("unchecked") public void processElement(Object untypedElem) throws Exception { WindowedValue<T> elem = (WindowedValue<T>) untypedElem; Collection<W> windows = windowFn.assignWindows( windowFn.new AssignContext() { @Override public T element() { return elem.getValue(); } @Override public Instant timestamp() { return elem.getTimestamp(); } @Override public BoundedWindow window() { return Iterables.getOnlyElement(elem.getWindows()); } }); WindowedValue<T> res = WindowedValue.of(elem.getValue(), elem.getTimestamp(), windows, elem.getPane()); receiver.process(res); } @Override public void processTimers() throws Exception { // Nothing. } @Override public void finishBundle() throws Exception { receiver = null; } @Override public void abort() throws Exception { receiver = null; } } }
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-personalize/include/aws/personalize/model/RecommenderConfig.h
<reponame>perfectrecall/aws-sdk-cpp /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/personalize/Personalize_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Personalize { namespace Model { /** * <p>The configuration details of the recommender.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/RecommenderConfig">AWS * API Reference</a></p> */ class AWS_PERSONALIZE_API RecommenderConfig { public: RecommenderConfig(); RecommenderConfig(Aws::Utils::Json::JsonView jsonValue); RecommenderConfig& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetItemExplorationConfig() const{ return m_itemExplorationConfig; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline bool ItemExplorationConfigHasBeenSet() const { return m_itemExplorationConfigHasBeenSet; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline void SetItemExplorationConfig(const Aws::Map<Aws::String, Aws::String>& value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig = value; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline void SetItemExplorationConfig(Aws::Map<Aws::String, Aws::String>&& value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig = std::move(value); } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& WithItemExplorationConfig(const Aws::Map<Aws::String, Aws::String>& value) { SetItemExplorationConfig(value); return *this;} /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& WithItemExplorationConfig(Aws::Map<Aws::String, Aws::String>&& value) { SetItemExplorationConfig(std::move(value)); return *this;} /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& AddItemExplorationConfig(const Aws::String& key, const Aws::String& value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig.emplace(key, value); return *this; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& AddItemExplorationConfig(Aws::String&& key, const Aws::String& value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig.emplace(std::move(key), value); return *this; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& AddItemExplorationConfig(const Aws::String& key, Aws::String&& value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig.emplace(key, std::move(value)); return *this; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& AddItemExplorationConfig(Aws::String&& key, Aws::String&& value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig.emplace(std::move(key), std::move(value)); return *this; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& AddItemExplorationConfig(const char* key, Aws::String&& value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig.emplace(key, std::move(value)); return *this; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& AddItemExplorationConfig(Aws::String&& key, const char* value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig.emplace(std::move(key), value); return *this; } /** * <p>Specifies the exploration configuration hyperparameters, including * <code>explorationWeight</code> and <code>explorationItemAgeCutOff</code>, you * want to use to configure the amount of item exploration Amazon Personalize uses * when recommending items. Provide <code>itemExplorationConfig</code> data only if * your recommenders generate personalized recommendations for a user (not popular * items or similar items).</p> */ inline RecommenderConfig& AddItemExplorationConfig(const char* key, const char* value) { m_itemExplorationConfigHasBeenSet = true; m_itemExplorationConfig.emplace(key, value); return *this; } private: Aws::Map<Aws::String, Aws::String> m_itemExplorationConfig; bool m_itemExplorationConfigHasBeenSet; }; } // namespace Model } // namespace Personalize } // namespace Aws
max-vorabhol-zipmex/express-app
packages/ui/src/helpers/depositHelper.js
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const digits = '0123456789'; const all = letters + digits; const getRandomCharInSet = set => set.charAt(Math.floor(Math.random() * set.length)); // Reference is composed of 10 random characters among uppercase letters and digits. // Freshcanvas scrapper required that at least one of the characters is a letter and at least one is a digit // The returned reference will always start with a digit and finish with an uppercase letter export const getUniqueReference = () => { let result = getRandomCharInSet(digits); for (var i = 0; i < 8; i++) { result += getRandomCharInSet(all); } result += getRandomCharInSet(letters); return result; };
kuuhaku86/design-patterns
Factory Method/Ruby/ILogger.rb
class ILogger def print(message) raise NotImplementedError end end
MicrohexHQ/nacl_contracts
src/shared/platform/win/time_win.cc
/* * Copyright (c) 2011 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // Make sure that winmm.lib is added to the linker's input. #pragma comment(lib, "winmm.lib") #include "native_client/src/include/portability.h" #include <mmsystem.h> #include <windows.h> #include "native_client/src/include/checked_cast.h" #include "native_client/src/shared/platform/win/time.h" #include "native_client/src/shared/platform/win/lock.h" namespace { // From MSDN, FILETIME "Contains a 64-bit value representing the number of // 100-nanosecond intervals since January 1, 1601 (UTC)." int64_t FileTimeToMicroseconds(const FILETIME& ft) { // Need to nacl_bit_cast to fix alignment, then divide by 10 to convert // 100-nanoseconds to milliseconds. This only works on little-endian // machines. return nacl_bit_cast<int64_t, FILETIME>(ft) / 10; } void MicrosecondsToFileTime(int64_t us, FILETIME* ft) { /* DCHECK(us >= 0) << "Time is less than 0, negative values are not " * "representable in FILETIME"; */ // Multiply by 10 to convert milliseconds to 100-nanoseconds. Nacl_bit_cast // will handle alignment problems. This only works on little-endian machines. *ft = nacl_bit_cast<FILETIME, int64_t>(us * 10); } } // namespace // Time ----------------------------------------------------------------------- // The internal representation of Time uses FILETIME, whose epoch is 1601-01-01 // 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the // number of leap year days between 1601 and 1970: (1970-1601)/4 excluding // 1700, 1800, and 1900. // static const int64_t NaCl::Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000); // static int64_t NaCl::Time::CurrentWallclockMicroseconds() { FILETIME ft; ::GetSystemTimeAsFileTime(&ft); return FileTimeToMicroseconds(ft); } // static NaCl::Time NaCl::Time::FromFileTime(FILETIME ft) { return Time(FileTimeToMicroseconds(ft)); } FILETIME NaCl::Time::ToFileTime() const { FILETIME utc_ft; MicrosecondsToFileTime(us_, &utc_ft); return utc_ft; } // static NaCl::Time NaCl::Time::FromExploded(bool is_local, const Exploded& exploded) { // Create the system struct representing our exploded time. It will either be // in local time or UTC. SYSTEMTIME st; st.wYear = nacl::assert_cast<WORD>(exploded.year); st.wMonth = nacl::assert_cast<WORD>(exploded.month); st.wDayOfWeek = nacl::assert_cast<WORD>(exploded.day_of_week); st.wDay = nacl::assert_cast<WORD>(exploded.day_of_month); st.wHour = nacl::assert_cast<WORD>(exploded.hour); st.wMinute = nacl::assert_cast<WORD>(exploded.minute); st.wSecond = nacl::assert_cast<WORD>(exploded.second); st.wMilliseconds = nacl::assert_cast<WORD>(exploded.millisecond); // Convert to FILETIME. FILETIME ft; if (!SystemTimeToFileTime(&st, &ft)) { // NOTREACHED() << "Unable to convert time"; return Time(0); } // Ensure that it's in UTC. if (is_local) { FILETIME utc_ft; LocalFileTimeToFileTime(&ft, &utc_ft); return Time(FileTimeToMicroseconds(utc_ft)); } return Time(FileTimeToMicroseconds(ft)); } void NaCl::Time::Explode(bool is_local, Exploded* exploded) const { // FILETIME in UTC. FILETIME utc_ft; MicrosecondsToFileTime(us_, &utc_ft); // FILETIME in local time if necessary. BOOL success = TRUE; FILETIME ft; if (is_local) success = FileTimeToLocalFileTime(&utc_ft, &ft); else ft = utc_ft; // FILETIME in SYSTEMTIME (exploded). SYSTEMTIME st; if (!success || !FileTimeToSystemTime(&ft, &st)) { // NOTREACHED() << "Unable to convert time, don't know why"; ZeroMemory(exploded, sizeof(*exploded)); return; } exploded->year = st.wYear; exploded->month = st.wMonth; exploded->day_of_week = st.wDayOfWeek; exploded->day_of_month = st.wDay; exploded->hour = st.wHour; exploded->minute = st.wMinute; exploded->second = st.wSecond; exploded->millisecond = st.wMilliseconds; } // TimeTicks ------------------------------------------------------------------ NaCl::TimeTicks::TickFunction NaCl::TimeTicks::tick_function_= reinterpret_cast<TickFunction>(&timeGetTime); // static NaCl::TimeTicks NaCl::TimeTicks::Now() { // Uses the multimedia timers on Windows to get a higher resolution clock. // timeGetTime() provides a resolution which is variable depending on // hardware and system configuration. It can also be changed by other // apps. This class does not attempt to change the resolution of the // timer, because we don't want to affect other applications. // timeGetTime() should at least be accurate to ~5ms on all systems. // timeGetTime() returns a 32-bit millisecond counter which has rollovers // every ~49 days. static DWORD last_tick_count = 0; static int64_t tick_rollover_accum = 0; static Lock* tick_lock = NULL; // To protect during rollover periods. // Lazily create the lock we use. if (!tick_lock) { Lock* new_lock = new Lock; if (InterlockedCompareExchangePointer( reinterpret_cast<PVOID*>(&tick_lock), new_lock, NULL)) { delete new_lock; } } // Atomically protect the low and high 32bit values for time. // In the future we may be able to optimize with // InterlockedCompareExchange64, but that doesn't work on XP. DWORD tick_count; int64_t rollover_count; /* lint complains about this, ignore */{ AutoLock lock(*tick_lock); tick_count = tick_function_(); if (tick_count < last_tick_count) tick_rollover_accum += GG_INT64_C(0x100000000); last_tick_count = tick_count; rollover_count = tick_rollover_accum; } // GetTickCount returns milliseconds, we want microseconds. return TimeTicks((tick_count + rollover_count) * Time::kMicrosecondsPerMillisecond); } // Overview of time counters: // (1) CPU cycle counter. (Retrieved via RDTSC) // The CPU counter provides the highest resolution time stamp and is the least // expensive to retrieve. However, the CPU counter is unreliable and should not // be used in production. Its biggest issue is that it is per processor and it // is not synchronized between processors. Also, on some computers, the counters // will change frequency due to thermal and power changes, and stop in some // states. // // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high- // resolution (100 nanoseconds) time stamp but is comparatively more expensive // to retrieve. What QueryPerformanceCounter actually does is up to the HAL. // (with some help from ACPI). // According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx // in the worst case, it gets the counter from the rollover interrupt on the // programmable interrupt timer. In best cases, the HAL may conclude that the // RDTSC counter runs at a constant frequency, then it uses that instead. On // multiprocessor machines, it will try to verify the values returned from // RDTSC on each processor are consistent with each other, and apply a handful // of workarounds for known buggy hardware. In other words, QPC is supposed to // give consistent result on a multiprocessor computer, but it is unreliable in // reality due to bugs in BIOS or HAL on some, especially old computers. // With recent updates on HAL and newer BIOS, QPC is getting more reliable but // it should be used with caution. // // (3) System time. The system time provides a low-resolution (typically 10ms // to 55 milliseconds) time stamp but is comparatively less expensive to // retrieve and more reliable. // static NaCl::TimeTicks NaCl::TimeTicks::UnreliableHighResNow() { // Cached clock frequency -> microseconds. This assumes that the clock // frequency is faster than one microsecond (which is 1MHz, should be OK). static int64_t ticks_per_microsecond = 0; if (ticks_per_microsecond == 0) { LARGE_INTEGER ticks_per_sec = { 0, 0 }; if (!QueryPerformanceFrequency(&ticks_per_sec)) return TimeTicks(0); // Broken, we don't guarantee this function works. ticks_per_microsecond = ticks_per_sec.QuadPart / Time::kMicrosecondsPerSecond; } LARGE_INTEGER now; QueryPerformanceCounter(&now); return TimeTicks(now.QuadPart / ticks_per_microsecond); }
cbp44/hadatac
app/org/hadatac/data/loader/SpreadsheetFileRecord.java
<filename>app/org/hadatac/data/loader/SpreadsheetFileRecord.java package org.hadatac.data.loader; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; public class SpreadsheetFileRecord implements Record { Row row; public SpreadsheetFileRecord(Row row) { this.row = row; } @Override public String getValueByColumnName(String colomnName) { String value = ""; try { value = row.getCell(getColomnIndexByName(colomnName)).toString(); } catch (Exception e) { System.out.println("row " + row.getRowNum() + ", column name " + colomnName + " not found!"); } return value; } @Override public String getValueByColumnIndex(int index) { String value = ""; try { value = row.getCell(index).toString(); } catch (Exception e) { System.out.println("row " + row.getRowNum() + ", column index " + index + " not valid!"); } return value; } @Override public int size() { return row.getLastCellNum() + 1; } private int getColomnIndexByName(String colomnName) { Sheet sheet = row.getSheet(); Row firstRow = sheet.getRow(sheet.getFirstRowNum()); for(int i = firstRow.getFirstCellNum(); i <= firstRow.getLastCellNum(); i++) { if (firstRow.getCell(i).toString().equals(colomnName)) { return i; } } return -1; } }
Brest-Java-Course-2021-2/Aliaksandr-Remizau-Municipal-service
service-rest/src/test/java/com/epam/brest/service/rest/RepairServiceRestTest.java
<gh_stars>0 package com.epam.brest.service.rest; import com.epam.brest.model.Repair; import com.epam.brest.model.type.LevelOfDifficulty; import com.epam.brest.model.type.RepairType; import com.epam.brest.service.rest.config.ServiceRestTestConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.client.ExpectedCount; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @ExtendWith(SpringExtension.class) @Import({ServiceRestTestConfig.class}) class RepairServiceRestTest { private final Logger log = LogManager.getLogger(RepairServiceRestTest.class); public static final LocalDate START_LIMIT_DATE = LocalDate.parse("2022-01-12"); public static final LocalDate END_LIMIT_DATE = LocalDate.parse("2022-01-20"); public static final String REPAIRS_URL = "http://localhost:8088/repairs"; public static final String URL_FILTER = "http://localhost:8088/repairs/filter?startLimitDate=2022-01-12&endLimitDate=2022-01-20"; @Autowired RestTemplate restTemplate; private MockRestServiceServer mockServer; private ObjectMapper objectMapper = JsonMapper.builder() .addModule(new JavaTimeModule()) .build(); private RepairServiceRest repairServiceRest; @BeforeEach void setUp() { mockServer = MockRestServiceServer.createServer(restTemplate); repairServiceRest = new RepairServiceRest(REPAIRS_URL,restTemplate); } @Test void shouldFindAll() throws Exception { log.debug("shouldFindAll()"); // GIVEN mockServer.expect(ExpectedCount.once(), requestTo(new URI(REPAIRS_URL))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString(Arrays.asList(createTestedRepair(0), createTestedRepair(1)))) ); //WHEN List<Repair> repairs = repairServiceRest.findAll(); //THEN mockServer.verify(); assertNotNull(repairs ); assertFalse(repairs.isEmpty()); assertTrue(repairs .size() == 2); } @Test void shouldGetRepairById() throws Exception { log.debug("getRepairById()"); //GIVEN Integer id = 1; Repair repair = createTestedRepair(id); mockServer.expect(ExpectedCount.once(), requestTo(new URI(REPAIRS_URL + "/" + id))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString(repair)) ); // WHEN Repair testRepair= repairServiceRest.getRepairById(id); //THEN mockServer.verify(); assertNotNull(testRepair); assertEquals(testRepair.getRepairId(), id); assertEquals(testRepair.getRepairType(), repair.getRepairType()); assertEquals(testRepair.getPreferenceDate(),repair.getPreferenceDate()); assertEquals(testRepair.getDifficultyLevel(),repair.getDifficultyLevel()); assertEquals(testRepair.getClientId(),repair.getClientId()); } @Test void shouldCreate() throws Exception{ log.debug("shouldCreate()"); //GIVEN int index = 5; Repair repair = new Repair(); mockServer.expect(ExpectedCount.once(), requestTo(new URI(REPAIRS_URL))) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString("5")) ); //WHEN Integer id = repairServiceRest.create(createTestedRepair(index)); //THEN mockServer.verify(); assertNotNull(id); assertEquals(id,index); } @Test void shouldUpdate() throws Exception{ log.debug("shouldUpdate()"); //GIVEN Integer id = 2; Repair repair = createTestedRepair(id); mockServer.expect(ExpectedCount.once(), requestTo(new URI(REPAIRS_URL))) .andExpect(method(HttpMethod.PUT)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString("2")) ); mockServer.expect(ExpectedCount.once(), requestTo(new URI(REPAIRS_URL+ "/" + id))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString(repair)) ); //WHEN int result = repairServiceRest.update(repair); Repair testRepair= repairServiceRest.getRepairById(id); //THEN mockServer.verify(); assertTrue(2 == result); assertNotNull(testRepair); assertEquals(testRepair.getRepairId(), id); assertEquals(testRepair.getRepairType(), repair.getRepairType()); assertEquals(testRepair.getPreferenceDate(),repair.getPreferenceDate()); assertEquals(testRepair.getDifficultyLevel(),repair.getDifficultyLevel()); assertEquals(testRepair.getClientId(),repair.getClientId()); } @Test void shouldDelete() throws Exception{ log.debug("shouldDelete()"); //GIVEN Integer id = 1; mockServer.expect(ExpectedCount.once(), requestTo(new URI(REPAIRS_URL + "/" + id))) .andExpect(method(HttpMethod.DELETE)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString("1")) ); //WHEN int result = repairServiceRest.delete(id); //THEN mockServer.verify(); assertTrue(1 == result); } @Test void shouldCount() throws Exception { log.debug("shouldCount()"); mockServer.expect(ExpectedCount.once(), requestTo(new URI(REPAIRS_URL + "/count"))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString("1")) ); //WHEN int result = repairServiceRest.count(); //THEN mockServer.verify(); assertTrue(result> 0); } @Test void filterRepairByPreferenceDate()throws Exception { log.debug("filterRepairByPreferenceDate()"); //GIVEN mockServer.expect(ExpectedCount.once(), requestTo(new URI(URL_FILTER))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(objectMapper.writeValueAsString(Arrays.asList(createTestedRepair(1))))); //WHEN List<Repair> list = repairServiceRest.filterRepairByPreferenceDate(START_LIMIT_DATE, END_LIMIT_DATE); //THEN mockServer.verify(); assertNotNull(list); assertTrue(list.size() == 1); } private Repair createTestedRepair(int index) { Repair testedRepair = new Repair(); LocalDate preferenceDate = LocalDate.parse("2022-01-15"); testedRepair.setRepairId(index); testedRepair.setRepairType(RepairType.ANOTHER); testedRepair.setAddress("Moskovskaya 250-1" + index); testedRepair.setDifficultyLevel(LevelOfDifficulty.HARD); testedRepair.setPreferenceDate(preferenceDate.minusDays(index)); testedRepair.setClientId(index + 1); return testedRepair; } }
youyouqiu/hybrid-development
clbs/src/main/java/com/zw/api/controller/modules/SwaggerMediaController.java
<reponame>youyouqiu/hybrid-development<filename>clbs/src/main/java/com/zw/api/controller/modules/SwaggerMediaController.java<gh_stars>1-10 package com.zw.api.controller.modules; import com.zw.api.domain.MediaInfo; import com.zw.api.domain.ResultBean; import com.zw.api.service.SwaggerMediaService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.Authorization; import io.swagger.annotations.AuthorizationScope; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.time.Duration; import java.time.LocalDateTime; import java.util.List; @Controller @RequestMapping("/swagger/m/media") @Api(tags = { "多媒体信息" }, description = "多媒体信息相关API接口") public class SwaggerMediaController { private static final Logger log = LogManager.getLogger(SwaggerMediaController.class); @Autowired private SwaggerMediaService swaggerMediaService; @ApiOperation(value = "获取指定监控对象在指定日期上传的多媒体信息URL列表", authorizations = { @Authorization(value = com.zw.api.config.SwaggerConfig.securitySchemaOAuth2, scopes = { @AuthorizationScope(scope = "read", description = "des") }) }) @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorName", value = "监控对象名称", paramType = "query", dataType = "string", required = true), @ApiImplicitParam(name = "start", value = "查询开始日期,格式为yyyy-MM-dd HH:mm:ss", paramType = "query", dataType = "LocalDate", required = true), @ApiImplicitParam(name = "end", value = "查询结束日期,格式为yyyy-MM-dd HH:mm:ss", paramType = "query", dataType = "LocalDate", required = true) }) @ApiResponse(code = 200, message = "true 成功, 其它为错误, 返回格式:{success: true, msg: '', data: []}") @RequestMapping(value = "/", method = RequestMethod.GET) @ResponseBody public ResultBean<List<MediaInfo>> list(@RequestParam String monitorName, @RequestParam LocalDateTime start, @RequestParam LocalDateTime end) { if (Duration.between(start, end).toDays() > 6) { return new ResultBean<>(false, "查询时间间隔不能超过7天"); } List<MediaInfo> mediaUrls = swaggerMediaService.listMonitorMedia(monitorName, start, end); return new ResultBean<>(true, "", mediaUrls); } @ExceptionHandler(Exception.class) @ResponseBody public ResultBean<?> handleException(Exception e) { return new ResultBean<>(false, e.getMessage()); } }
xwang1024/bomblab
lib/controller/index.js
<reponame>xwang1024/bomblab 'use strict'; exports.index = function(req, res, next) { res.redirect('/activity'); };
LaudateCorpus1/oneview-chef
spec/unit/resources/enclosure_group/create_if_missing_spec.rb
require_relative './../../../spec_helper' describe 'oneview_test::enclosure_group_create_if_missing' do let(:resource_name) { 'enclosure_group' } include_context 'chef context' it 'accepts a logical_interconnect_groups parameter' do expect_any_instance_of(OneviewSDK::EnclosureGroup).to receive(:add_logical_interconnect_group).and_return(true) expect_any_instance_of(OneviewSDK::EnclosureGroup).to receive(:exists?).and_return(false) expect_any_instance_of(OneviewSDK::EnclosureGroup).to receive(:create).and_return(true) expect(real_chef_run).to create_oneview_enclosure_group_if_missing('EnclosureGroup2') end end
foxdonut/meiosis-examples
examples/custom-elements/hybrids/src/conditions/view.js
<reponame>foxdonut/meiosis-examples import { html } from "hybrids" import { bootstrap } from "../util" const conditionsOption = ({ state, id, actions, value, label }) => html` <label class="radio-inline"> <input type="radio" name="conditions" value=${value} checked=${state[id].sky === value} onchange=${(_, evt) => actions.changeSky(id, evt.target.value)} /> ${label} </label> ` export const Conditions = { state: null, actions: null, render: ({ state, id, actions }) => html` ${bootstrap} <div> <label class="checkbox-inline"> <input type="checkbox" checked=${state[id].precipitations} onchange=${(_, evt) => actions.togglePrecipitations(id, evt.target.checked)} /> Precipitations </label> <div> ${conditionsOption({ state, id, actions, value: "SUNNY", label: "Sunny" })} ${conditionsOption({ state, id, actions, value: "CLOUDY", label: "Cloudy" })} ${conditionsOption({ state, id, actions, value: "MIX", label: "Mix of sun and clouds" })} </div> </div> ` }
phpyandong/opentaobao
model/product/TaobaoItemSellerGetResponse.go
package product import ( "encoding/xml" "github.com/bububa/opentaobao/model" ) /* 获取单个商品详细信息 APIResponse taobao.item.seller.get 获取单个商品的全部信息 <br/><strong><a href="https://console.open.taobao.com/dingWeb.htm?from=itemapi" target="_blank">点击查看更多商品API说明</a></strong> */ type TaobaoItemSellerGetAPIResponse struct { model.CommonResponse TaobaoItemSellerGetResponse } type TaobaoItemSellerGetResponse struct { XMLName xml.Name `xml:"item_seller_get_response"` RequestId string `json:"request_id,omitempty" xml:"request_id,omitempty"` // 平台颁发的每次请求访问的唯一标识 // 商品详细信息 Item *Item `json:"item,omitempty" xml:"item,omitempty"` }
Dnmrk4/codewars-7kyu-part2
Remove duplication.js
<reponame>Dnmrk4/codewars-7kyu-part2<filename>Remove duplication.js /* Description: Write a function that accepts an array of number as parameter, and it returns array after removing all duplicated numbers. Example removeDuplication([1,2,3,2,4,6,2,6,7]) Output [1,3,4,7]. Here 2 ,6 are duplicated in array , so we should remove all numbers that are duplicated. The output will be 1,3,4,7 after removing 2,6. Input : [1,2,1,2,1,1,2,2] , Output : []. Input : [2,5,6,7,5,2,6] , Output: [7]. */ function removeDuplication(arr){ return arr.filter(v=>arr.indexOf(v)!==arr.lastIndexOf(v)); }
motiver/motiver_fi
motiverFi/src/com/delect/motiver/server/jdo/MeasurementValue.java
<gh_stars>1-10 /******************************************************************************* * Copyright 2011 <NAME> * * This file is part of Motiver.fi. * Motiver.fi is licensed under one open source license and one commercial license. * * Commercial license: This is the appropriate option if you want to use Motiver.fi in * commercial purposes. Contact <EMAIL> for licensing options. * * Open source license: This is the appropriate option if you are creating an open source * application with a license compatible with the GNU GPL license v3. Although the GPLv3 has * many terms, the most important is that you must provide the source code of your application * to your users so they can be free to modify your application for their own needs. ******************************************************************************/ package com.delect.motiver.server.jdo; import java.util.Date; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; import org.json.simple.JSONObject; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.delect.motiver.shared.MeasurementValueModel; @PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true") public class MeasurementValue { /** * Converts server object to client side object * @param model : server side model * @return Client side model */ public static MeasurementValueModel getClientModel(MeasurementValue model) { if(model == null) { return null; } MeasurementValueModel modelClient = new MeasurementValueModel(); modelClient.setId(model.getId().longValue()); modelClient.setValue(model.getValue()); modelClient.setDate(model.getDate()); modelClient.setUid(model.getUid()); return modelClient; } /** * Converts client object to server side object * @param model : client side model * @return Server side model */ public static MeasurementValue getServerModel(MeasurementValueModel model) { if(model == null) { return null; } MeasurementValue modelServer = new MeasurementValue(); modelServer.setId(model.getId()); modelServer.setValue(model.getValue()); modelServer.setDate(model.getDate()); return modelServer; } @Persistent private Date date; @Persistent private Measurement measurement; @Persistent private Long uid; @Persistent public String openId; @Persistent private Double value; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) protected Key id; public MeasurementValue() { } public Date getDate() { return date; } public Long getId() { if(id != null) { return id.getId(); } else { return 0L; } } public Key getKey() { return id; } public Measurement getMeasurement() { return measurement; } public String getUid() { if(openId != null) { return openId; } else { return ""; } } public Double getValue() { return value; } public void setDate(Date date) { this.date = date; } public void setId(Long id) { Key k = null; if(id != null && id != 0) { k = KeyFactory.createKey(MeasurementValue.class.getSimpleName(), id); } if(k != null) { this.id = k; } else { this.id = null; } } public void setUid(String openId) { this.openId = openId; } public void setValue(Double value) { this.value = value; } public Long getUidOld() { return uid; } @SuppressWarnings("unchecked") public JSONObject getJson() { JSONObject obj=new JSONObject(); obj.put("date",(getDate() != null)? getDate().toString() : null); obj.put("id", getId()); obj.put("value", getValue()); return obj; } }
ivansukach/protobuf
test/deterministic/deterministic_test.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2018, The GoGo Authors. All rights reserved. // http://github.com/ivansukach/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // 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. package deterministic import ( "bytes" "github.com/ivansukach/protobuf/proto" "testing" ) func getTestMap() map[string]string { return map[string]string{ "a": "1", "b": "2", "c": "3", "d": "4", "e": "5", "f": "6", "g": "7", "h": "8", "i": "9", "j": "10", "k": "11", "l": "12", "m": "13", "n": "14", } } func TestOrderedMap(t *testing.T) { var b proto.Buffer m := getTestMap() in := &OrderedMap{ StringMap: m, } if err := b.Marshal(in); err != nil { t.Fatalf("Marshal failed: %v", err) } data1 := b.Bytes() out := &OrderedMap{} if err := proto.Unmarshal(data1, out); err != nil { t.Fatal(err) } if err := in.VerboseEqual(out); err != nil { t.Fatal(err) } data2, err := proto.Marshal(in) if err != nil { t.Fatal(err) } if bytes.Compare(data1, data2) != 0 { t.Fatal("byte arrays are not the same\n", data1, "\n", data2) } } func TestUnorderedMap(t *testing.T) { m := getTestMap() in := &UnorderedMap{ StringMap: m, } var b proto.Buffer b.SetDeterministic(true) if err := b.Marshal(in); err == nil { t.Fatalf("Expected Marshal to return error rejecting deterministic flag") } } func TestMapNoMarshaler(t *testing.T) { m := getTestMap() in := &MapNoMarshaler{ StringMap: m, } var b1 proto.Buffer b1.SetDeterministic(true) if err := b1.Marshal(in); err != nil { t.Fatalf("Marshal failed: %v", err) } data1 := b1.Bytes() out := &MapNoMarshaler{} err := proto.Unmarshal(data1, out) if err != nil { t.Fatal(err) } if err := in.VerboseEqual(out); err != nil { t.Fatal(err) } var b2 proto.Buffer b2.SetDeterministic(true) if err := b2.Marshal(in); err != nil { t.Fatalf("Marshal failed: %v", err) } data2 := b2.Bytes() if bytes.Compare(data1, data2) != 0 { t.Fatal("byte arrays are not the same:\n", data1, "\n", data2) } } func TestOrderedNestedMap(t *testing.T) { var b proto.Buffer in := &NestedOrderedMap{ StringMap: getTestMap(), NestedMap: &NestedMap1{ NestedStringMap: getTestMap(), }, } if err := b.Marshal(in); err != nil { t.Fatalf("Marshal failed: %v", err) } data1 := b.Bytes() out := &NestedOrderedMap{} if err := proto.Unmarshal(data1, out); err != nil { t.Fatal(err) } if err := in.VerboseEqual(out); err != nil { t.Fatal(err) } data2, err := proto.Marshal(in) if err != nil { t.Fatal(err) } if bytes.Compare(data1, data2) != 0 { t.Fatal("byte arrays are not the same\n", data1, "\n", data2) } } func TestUnorderedNestedMap(t *testing.T) { in := &NestedUnorderedMap{ StringMap: getTestMap(), NestedMap: &NestedMap2{ NestedStringMap: getTestMap(), }, } var b proto.Buffer b.SetDeterministic(true) if err := b.Marshal(in); err == nil { t.Fatalf("Expected Marshal to return error rejecting deterministic flag") } } func TestOrderedNestedStructMap(t *testing.T) { var b proto.Buffer m := getTestMap() in := &NestedMap1{ NestedStringMap: m, } if err := b.Marshal(in); err != nil { t.Fatalf("Marshal failed: %v", err) } data1 := b.Bytes() out := &NestedMap1{} if err := proto.Unmarshal(data1, out); err != nil { t.Fatal(err) } if err := in.VerboseEqual(out); err != nil { t.Fatal(err) } data2, err := proto.Marshal(in) if err != nil { t.Fatal(err) } if bytes.Compare(data1, data2) != 0 { t.Fatal("byte arrays are not the same\n", data1, "\n", data2) } } func TestUnorderedNestedStructMap(t *testing.T) { m := getTestMap() in := &NestedMap2{ NestedStringMap: m, } var b proto.Buffer b.SetDeterministic(true) if err := b.Marshal(in); err == nil { t.Fatalf("Expected Marshal to return error rejecting deterministic flag") } }
katapultmedia/daedalus
source/renderer/app/ipc/loadAsset.js
<gh_stars>1000+ // @flow import { RendererIpcChannel } from './lib/RendererIpcChannel'; import { LOAD_ASSET_CHANNEL } from '../../../common/ipc/api'; import type { LoadAssetRendererRequest, LoadAssetMainResponse, } from '../../../common/ipc/api'; // IpcChannel<Incoming, Outgoing> export const loadAssetChannel: RendererIpcChannel< LoadAssetMainResponse, LoadAssetRendererRequest > = new RendererIpcChannel(LOAD_ASSET_CHANNEL);
isabella232/tessapi
3.05.02/search/files_c.js
var searchData= [ ['ndminx_2eh',['ndminx.h',['../a00548.html',1,'']]], ['neural_5fnet_2ecpp',['neural_net.cpp',['../a01220.html',1,'']]], ['neural_5fnet_2eh',['neural_net.h',['../a01223.html',1,'']]], ['neuron_2ecpp',['neuron.cpp',['../a01226.html',1,'']]], ['neuron_2eh',['neuron.h',['../a01229.html',1,'']]], ['normalis_2ecpp',['normalis.cpp',['../a00305.html',1,'']]], ['normalis_2eh',['normalis.h',['../a00308.html',1,'']]], ['normfeat_2ecpp',['normfeat.cpp',['../a00779.html',1,'']]], ['normfeat_2eh',['normfeat.h',['../a00782.html',1,'']]], ['normmatch_2ecpp',['normmatch.cpp',['../a00785.html',1,'']]], ['normmatch_2eh',['normmatch.h',['../a00788.html',1,'']]], ['normstrngs_2ecpp',['normstrngs.cpp',['../a01553.html',1,'']]], ['normstrngs_2eh',['normstrngs.h',['../a01556.html',1,'']]], ['nwmain_2eh',['nwmain.h',['../a00551.html',1,'']]] ];
d3fc0n6/TeamFortress2
tf2_src/game/server/tf/tf_projectile_energy_ball.cpp
<reponame>d3fc0n6/TeamFortress2 //========= Copyright Valve Corporation, All rights reserved. ============// // // TF Energy Ball // //============================================================================= #include "cbase.h" #include "tf_projectile_energy_ball.h" #include "soundent.h" #include "tf_fx.h" #include "props.h" #include "baseobject_shared.h" #include "SpriteTrail.h" #include "IEffects.h" #include "te_effect_dispatch.h" #include "collisionutils.h" #include "bone_setup.h" #include "decals.h" #include "tf_player.h" #include "te_effect_dispatch.h" #include "tf_gamerules.h" #include "tf_weapon_rocketlauncher.h" //============================================================================= // // TF Energy Ball Projectile functions (Server specific). // #define ENERGY_BALL_MODEL "models/weapons/w_models/w_drg_ball.mdl" #define ARROW_GRAVITY 0.3f #define ENERGY_BALL_THINK_CONTEXT "CTFProjectile_EnergyBallThink" //----------------------------------------------------------------------------- LINK_ENTITY_TO_CLASS( tf_projectile_energy_ball, CTFProjectile_EnergyBall ); PRECACHE_WEAPON_REGISTER( tf_projectile_energy_ball ); IMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_EnergyBall, DT_TFProjectile_EnergyBall ) BEGIN_NETWORK_TABLE( CTFProjectile_EnergyBall, DT_TFProjectile_EnergyBall ) SendPropBool( SENDINFO( m_bChargedShot ) ), SendPropVector( SENDINFO( m_vColor1 ), 8, 0, 0, 1 ), SendPropVector( SENDINFO( m_vColor2 ), 8, 0, 0, 1 ) END_NETWORK_TABLE() BEGIN_DATADESC( CTFProjectile_EnergyBall ) //DEFINE_THINKFUNC( ImpactThink ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFProjectile_EnergyBall::CTFProjectile_EnergyBall() { m_bChargedShot = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFProjectile_EnergyBall::~CTFProjectile_EnergyBall() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFProjectile_EnergyBall *CTFProjectile_EnergyBall::Create( const Vector &vecOrigin, const QAngle &vecAngles, const float fSpeed, const float fGravity, CBaseEntity *pOwner, CBaseEntity *pScorer ) { CTFProjectile_EnergyBall *pBall = static_cast<CTFProjectile_EnergyBall*>( CBaseEntity::Create( "tf_projectile_energy_ball", vecOrigin, vecAngles, pOwner ) ); if ( pBall ) { pBall->InitEnergyBall( vecOrigin, vecAngles, fSpeed, fGravity, pOwner, pScorer ); } return pBall; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::InitEnergyBall( const Vector &vecOrigin, const QAngle &vecAngles, const float fSpeed, const float fGravity, CBaseEntity *pOwner, CBaseEntity *pScorer ) { // Initialize the owner. SetOwnerEntity( pOwner ); // Set team. ChangeTeam( pOwner->GetTeamNumber() ); // Spawn. Spawn(); SetGravity( fGravity ); SetCritical( true ); // Setup the initial velocity. Vector vecForward, vecRight, vecUp; AngleVectors( vecAngles, &vecForward, &vecRight, &vecUp ); Vector vecVelocity = vecForward * fSpeed; SetAbsVelocity( vecVelocity ); SetupInitialTransmittedGrenadeVelocity( vecVelocity ); // Setup the initial angles. QAngle angles; VectorAngles( vecVelocity, angles ); SetAbsAngles( angles ); // Save the scoring player. SetScorer( pScorer ); if ( pScorer ) { SetTruceValidForEnt( pScorer->IsTruceValidForEnt() ); } m_flInitTime = gpGlobals->curtime; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::Spawn() { SetModel( ENERGY_BALL_MODEL ); BaseClass::Spawn(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::Precache() { PrecacheParticleSystem( "drg_cow_rockettrail_charged" ); PrecacheParticleSystem( "drg_cow_rockettrail_charged_blue" ); PrecacheParticleSystem( "drg_cow_rockettrail_normal" ); PrecacheParticleSystem( "drg_cow_rockettrail_normal_blue" ); PrecacheModel( ENERGY_BALL_MODEL ); PrecacheScriptSound( "Weapon_CowMangler.Explode" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::SetScorer( CBaseEntity *pScorer ) { m_Scorer = pScorer; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CBasePlayer *CTFProjectile_EnergyBall::GetScorer( void ) { return dynamic_cast<CBasePlayer *>( m_Scorer.Get() ); } //----------------------------------------------------------------------------- // Purpose: Plays an impact sound. Louder for the attacker. //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::ImpactSound( const char *pszSoundName, bool bLoudForAttacker ) { CTFPlayer *pAttacker = ToTFPlayer( GetScorer() ); if ( !pAttacker ) return; if ( bLoudForAttacker ) { float soundlen = 0; EmitSound_t params; params.m_flSoundTime = 0; params.m_pSoundName = pszSoundName; params.m_pflSoundDuration = &soundlen; CPASFilter filter( GetAbsOrigin() ); filter.RemoveRecipient( ToTFPlayer(pAttacker) ); EmitSound( filter, entindex(), params ); CSingleUserRecipientFilter attackerFilter( ToTFPlayer(pAttacker) ); EmitSound( attackerFilter, pAttacker->entindex(), params ); } else { EmitSound( pszSoundName ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::FadeOut( int iTime ) { SetMoveType( MOVETYPE_NONE ); SetAbsVelocity( vec3_origin ); AddSolidFlags( FSOLID_NOT_SOLID ); AddEffects( EF_NODRAW ); // Start remove timer. SetContextThink( &CTFProjectile_EnergyBall::RemoveThink, gpGlobals->curtime + iTime, "ENERGY_BALL_REMOVE_THINK" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::RemoveThink( void ) { UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: Arrow was deflected. //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir ) { CTFPlayer *pTFDeflector = ToTFPlayer( pDeflectedBy ); if ( !pTFDeflector ) return; ChangeTeam( pTFDeflector->GetTeamNumber() ); SetLauncher( pTFDeflector->GetActiveWeapon() ); CTFPlayer* pOldOwner = ToTFPlayer( GetOwnerEntity() ); SetOwnerEntity( pTFDeflector ); if ( pOldOwner ) { pOldOwner->SpeakConceptIfAllowed( MP_CONCEPT_DEFLECTED, "projectile:1,victim:1" ); } if ( pTFDeflector->m_Shared.IsCritBoosted() ) { SetCritical( true ); } CTFWeaponBase::SendObjectDeflectedEvent( pTFDeflector, pOldOwner, GetWeaponID(), this ); IncrementDeflected(); SetScorer( pTFDeflector ); // Change particle color data. if ( GetTeamNumber() == TF_TEAM_BLUE ) { m_vColor1 = TF_PARTICLE_WEAPON_BLUE_1; m_vColor2 = TF_PARTICLE_WEAPON_BLUE_2; } else { m_vColor1 = TF_PARTICLE_WEAPON_RED_1; m_vColor2 = TF_PARTICLE_WEAPON_RED_2; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_EnergyBall::Explode( trace_t *pTrace, CBaseEntity *pOther ) { if ( ShouldNotDetonate() ) { Destroy( true ); return; } // Save this entity as enemy, they will take 100% damage. m_hEnemy = pOther; // Invisible. SetModelName( NULL_STRING ); AddSolidFlags( FSOLID_NOT_SOLID ); m_takedamage = DAMAGE_NO; // Pull out a bit. if ( pTrace->fraction != 1.0 ) { SetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) ); } // Particle (oriented) Vector vecOrigin = GetAbsOrigin(); CPVSFilter filter( vecOrigin ); QAngle angExplosion( 0.f, 0.f, 0.f ); VectorAngles( pTrace->plane.normal, angExplosion ); TE_TFParticleEffect( filter, 0.f, GetExplosionParticleName(), vecOrigin, pTrace->plane.normal, angExplosion, NULL ); // Screenshake if ( m_bChargedShot ) { UTIL_ScreenShake( WorldSpaceCenter(), 25.0, 150.0, 1.0, 750, SHAKE_START ); } // Sound ImpactSound( "Weapon_CowMangler.Explode" ); CSoundEnt::InsertSound ( SOUND_COMBAT, vecOrigin, 1024, 3.0 ); // Damage. CBaseEntity *pAttacker = GetOwnerEntity(); IScorer *pScorerInterface = dynamic_cast<IScorer*>( pAttacker ); if ( pScorerInterface ) { pAttacker = pScorerInterface->GetScorer(); } float flRadius = GetRadius(); if ( pAttacker ) // No attacker, deal no damage. Otherwise we could potentially kill teammates. { CTFPlayer *pTarget = ToTFPlayer( GetEnemy() ); if ( pTarget ) { // Rocket Specialist CheckForStunOnImpact( pTarget ); if ( pTarget->GetTeamNumber() != pAttacker->GetTeamNumber() ) { IGameEvent *event = gameeventmanager->CreateEvent( "projectile_direct_hit" ); if ( event ) { event->SetInt( "attacker", pAttacker->entindex() ); event->SetInt( "victim", pTarget->entindex() ); item_definition_index_t ownerWeaponDefIndex = INVALID_ITEM_DEF_INDEX; CTFWeaponBase *pWeapon = dynamic_cast< CTFWeaponBase * >( GetOriginalLauncher() ); if ( pWeapon ) { ownerWeaponDefIndex = pWeapon->GetAttributeContainer()->GetItem()->GetItemDefIndex(); } event->SetInt( "weapon_def_index", ownerWeaponDefIndex ); gameeventmanager->FireEvent( event, true ); } } } CTakeDamageInfo info( this, pAttacker, m_hLauncher, vec3_origin, vecOrigin, GetDamage(), GetDamageType(), GetDamageCustom() ); CTFRadiusDamageInfo radiusinfo( &info, vecOrigin, flRadius, NULL, m_bChargedShot ? TF_ROCKET_RADIUS_FOR_RJS*1.33 : TF_ROCKET_RADIUS_FOR_RJS ); TFGameRules()->RadiusDamage( radiusinfo ); } // Don't decal players with scorch. if ( !pOther->IsPlayer() ) { UTIL_DecalTrace( pTrace, "Scorch" ); } // Remove the rocket. UTIL_Remove( this ); return; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CTFProjectile_EnergyBall::GetExplosionParticleName( void ) { if ( m_bChargedShot ) { return ( GetTeamNumber() == TF_TEAM_RED ) ? "drg_cow_explosioncore_charged" : "drg_cow_explosioncore_charged_blue"; } else { return ( GetTeamNumber() == TF_TEAM_RED ) ? "drg_cow_explosioncore_normal" : "drg_cow_explosioncore_normal_blue"; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CTFProjectile_EnergyBall::GetDamage() { return m_flDamage; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFProjectile_EnergyBall::GetDamageType() { int iDamageType; if ( m_bChargedShot ) { iDamageType = DMG_BLAST | DMG_HALF_FALLOFF | DMG_USEDISTANCEMOD | DMG_IGNITE; } else { iDamageType = DMG_BLAST | DMG_HALF_FALLOFF | DMG_USEDISTANCEMOD; } return iDamageType; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFProjectile_EnergyBall::GetDamageCustom() { return m_bChargedShot ? TF_DMG_CUSTOM_PLASMA_CHARGED : TF_DMG_CUSTOM_PLASMA; }
vicenteam/hyxt
guns-admin/src/main/java/com/stylefeng/guns/modular/main/service/IBaMedicalService.java
package com.stylefeng.guns.modular.main.service; import com.stylefeng.guns.modular.system.model.BaMedical; import com.baomidou.mybatisplus.service.IService; /** * <p> * 健康状态表 服务类 * </p> * * @author stylefeng * @since 2018-08-17 */ public interface IBaMedicalService extends IService<BaMedical> { }
tfg13/u-root
cmds/core/elvish/parse/error.go
<reponame>tfg13/u-root package parse import ( "bytes" "fmt" "github.com/u-root/u-root/cmds/core/elvish/util" ) // ErrorEntry represents one parse error. type ErrorEntry struct { Message string Context util.SourceRange } // Error stores multiple ErrorEntry's and can pretty print them. type Error struct { Entries []*ErrorEntry } func (pe *Error) Add(msg string, ctx *util.SourceRange) { pe.Entries = append(pe.Entries, &ErrorEntry{msg, *ctx}) } func (pe *Error) Error() string { switch len(pe.Entries) { case 0: return "no parse error" case 1: e := pe.Entries[0] return fmt.Sprintf("parse error: %d-%d in %s: %s", e.Context.Begin, e.Context.End, e.Context.Name, e.Message) default: buf := new(bytes.Buffer) // Contexts of parse error entries all have the same name fmt.Fprintf(buf, "multiple parse errors in %s: ", pe.Entries[0].Context.Name) for i, e := range pe.Entries { if i > 0 { fmt.Fprint(buf, "; ") } fmt.Fprintf(buf, "%d-%d: %s", e.Context.Begin, e.Context.End, e.Message) } return buf.String() } } func (pe *Error) Pprint(indent string) string { buf := new(bytes.Buffer) switch len(pe.Entries) { case 0: return "no parse error" case 1: e := pe.Entries[0] fmt.Fprintf(buf, "Parse error: \033[31;1m%s\033[m\n", e.Message) buf.WriteString(e.Context.PprintCompact(indent + " ")) default: fmt.Fprint(buf, "Multiple parse errors:") for _, e := range pe.Entries { buf.WriteString("\n" + indent + " ") fmt.Fprintf(buf, "\033[31;1m%s\033[m\n", e.Message) buf.WriteString(indent + " ") buf.WriteString(e.Context.Pprint(indent + " ")) } } return buf.String() }
weiliy/yoroi-frontend
packages/yoroi-extension/app/components/wallet/staking/dashboard-revamp/StakePool/StakePool.js
<reponame>weiliy/yoroi-frontend<filename>packages/yoroi-extension/app/components/wallet/staking/dashboard-revamp/StakePool/StakePool.js<gh_stars>0 // @flow import type { Node } from 'react'; import TwitterIcon from '../../../../../assets/images/social/revamp/twitter.inline.svg'; import TelegramIcon from '../../../../../assets/images/social/revamp/telegram.inline.svg'; import FbIcon from '../../../../../assets/images/social/revamp/facebook.inline.svg'; import YoutubeIcon from '../../../../../assets/images/social/revamp/youtube.inline.svg'; import TwitchIcon from '../../../../../assets/images/social/revamp/twitch.inline.svg'; import DiscordIcon from '../../../../../assets/images/social/revamp/discord.inline.svg'; import GithubIcon from '../../../../../assets/images/social/revamp/github.inline.svg'; import PersonalIcon from '../../../../../assets/images/social/revamp/personal.inline.svg'; import { List, StyledLink } from './StakePool.styles'; import { Tooltip, Typography } from '@mui/material'; import { Box } from '@mui/system'; import QuestionMarkIcon from '../../../../../assets/images/question-mark.inline.svg'; import type { SocialLinks } from '../../../../../containers/wallet/staking/SeizaFetcher'; // eslint-disable-next-line react/require-default-props type Props = {| socialLinks?: SocialLinks, websiteUrl?: string, +color: string |}; const SocialExternalLink = ({ href, children }: {| href: string, children: Node |}): Node => ( <StyledLink href={href} target="_blank" rel="noreferrer noopener"> {children} </StyledLink> ); export const SocialMediaStakePool = ({ socialLinks, websiteUrl, color }: Props): Node => { const twitter = socialLinks?.tw; const telegram = socialLinks?.tg; const facebook = socialLinks?.fb; const youtube = socialLinks?.yt; const twitch = socialLinks?.tc; const discord = socialLinks?.di; const github = socialLinks?.gh; return ( <List color={color}> {twitter != null ? ( <SocialExternalLink href={`https://twitter.com/${twitter}`}> <TwitterIcon /> </SocialExternalLink> ) : null} {telegram != null ? ( <SocialExternalLink href={`https://t.me/${telegram}`}> <TelegramIcon />{' '} </SocialExternalLink> ) : null} {facebook != null ? ( <SocialExternalLink href={`https://fb.me/${facebook}`}> <FbIcon /> </SocialExternalLink> ) : null} {youtube != null ? ( <SocialExternalLink href={`https://youtube.com/${youtube}`}> <YoutubeIcon /> </SocialExternalLink> ) : null} {twitch != null ? ( <SocialExternalLink href={`https://twitch.com/${twitch}`}> <TwitchIcon /> </SocialExternalLink> ) : null} {discord != null ? ( <SocialExternalLink href={`https://discord.gg/${discord}`}> <DiscordIcon /> </SocialExternalLink> ) : null} {github != null ? ( <SocialExternalLink href={`https://github.com/${github}`}> <GithubIcon /> </SocialExternalLink> ) : null} {websiteUrl != null ? ( <SocialExternalLink href={websiteUrl}> <PersonalIcon /> </SocialExternalLink> ) : null} </List> ); }; type HelperTooltipProps = {| +message: string, |}; export const HelperTooltip = ({ message }: HelperTooltipProps): Node => { return ( <Tooltip title={<Typography variant="body2">{message}</Typography>} arrow placement="right"> <Box display="inline-flex"> <QuestionMarkIcon /> </Box> </Tooltip> ); };
DexSinis/NSXcode
NSXcode/Classes/Libs/SDAutoLayout/UITableView+SDAutoTableViewCellHeight.h
// // UITableView+SDAutoTableViewCellHeight.h // SDAutoLayout 测试 Demo // // Created by aier on 15/11/1. // Copyright © 2015年 gsd. All rights reserved. // /* ********************************************************************************* * * * 在您使用此自动布局库的过程中如果出现bug请及时以以下任意一种方式联系我们,我们会及时修复bug并 * * 帮您解决问题。 * * QQ : 2689718696(gsdios) * * Email : <EMAIL> * * GitHub: https://github.com/gsdios * * 新浪微博:GSD_iOS * * * ********************************************************************************* */ #import <UIKit/UIKit.h> @interface UITableViewCell (SDAutoHeight) @property (nonatomic) CGFloat autoHeight; @property (nonatomic) UIView *sd_bottomView; @property (nonatomic) CGFloat sd_bottomViewBottomMargin; - (void)setupAutoHeightWithBottomView:(UIView *)bottomView bottomMargin:(CGFloat)bottomMargin; @end @interface SDCellAutoHeightManager : NSObject @property (nonatomic, assign) CGFloat contentViewWidth; @property (nonatomic, assign) Class cellClass; @property (nonatomic, assign) CGFloat cellHeight; - (void)clearHeightCache; - (CGFloat)cellHeightForIndexPath:(NSIndexPath *)indexPath model:(id)model keyPath:(NSString *)keyPath; - (instancetype)initWithCellClass:(Class)cellClass; + (instancetype)managerWithCellClass:(Class)cellClass; @end @interface UITableView (SDAutoTableViewCellHeight) - (void)startAutoCellHeightWithCellClass:(Class)cellClass contentViewWidth:(CGFloat)contentViewWidth; - (CGFloat)cellHeightForIndexPath:(NSIndexPath *)indexPath model:(id)model keyPath:(NSString *)keyPath; @property (nonatomic, strong) SDCellAutoHeightManager *cellAutoHeightManager; @end
egotter/egotter
app/workers/create_greeting_good_evening_message_worker.rb
<gh_stars>10-100 class CreateGreetingGoodEveningMessageWorker include Sidekiq::Worker include ReportErrorHandler sidekiq_options queue: 'messaging', retry: 0, backtrace: false MESSAGE = <<~TEXT こんばんは。 TEXT def unique_key(uid, options = {}) uid end def unique_in(*args) 3.seconds end # options: def perform(uid, options = {}) User.egotter.api_client.create_direct_message_event(uid, MESSAGE + Kaomoji::KAWAII.sample) rescue => e unless ignorable_report_error?(e) logger.warn "#{e.inspect} uid=#{uid} options=#{options.inspect}" end end end
basil/elastest-plugin
src/main/java/jenkins/plugins/elastest/action/ElasTestItemMenuAction.java
<reponame>basil/elastest-plugin<gh_stars>0 /* * The MIT License * * (C) Copyright 2017-2019 ElasTest (http://elastest.io/) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.plugins.elastest.action; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import hudson.model.Action; import hudson.model.Actionable; import hudson.model.Run; import jenkins.plugins.elastest.ElasTestService; import jenkins.plugins.elastest.Messages; /** * This class creates the icon that allows access to the Job execution in * ElasTest * * @author <NAME> * */ public class ElasTestItemMenuAction extends Actionable implements Action { private final static Logger LOG = LoggerFactory .getLogger(ElasTestItemMenuAction.class); private static final String ICON_IMAGE = "/plugin/elastest/images/icon.png"; private String elasTestLogAnalyzerUrl = "http://localhost:4200/#/logmanager"; private String elasTestTJobExecutionUrl = ""; public ElasTestItemMenuAction(@SuppressWarnings("rawtypes") Run<?, ?> build, String elasTestLogAnalyzerUrl, String elasTestTJobExecutionUrl) { super(); LOG.debug("[elastest-plugin]: ElasTest Log Analayser URL: {}", elasTestLogAnalyzerUrl); LOG.debug("[elastest-plugin]: ElasTest TJob execution URL: {}", elasTestTJobExecutionUrl); this.elasTestLogAnalyzerUrl = elasTestLogAnalyzerUrl; this.elasTestTJobExecutionUrl = elasTestTJobExecutionUrl; } public static void addActionToMenu(Run<?, ?> build) { ElasTestService elasTestService = ElasTestService.getInstance(); ElasTestItemMenuAction action = new ElasTestItemMenuAction(build, elasTestService.getExternalJobByBuildFullName( build.getFullDisplayName()).getLogAnalyzerUrl(), elasTestService.getExternalJobByBuildFullName( build.getFullDisplayName()).getExecutionUrl()); build.addAction(action); } @Override public String getDisplayName() { return Messages.MenuItemLabel(); } @Override public String getSearchUrl() { return null; } @Override public String getIconFileName() { return ICON_IMAGE; } @Override public String getUrlName() { return elasTestTJobExecutionUrl; } public String getElasTestLogAnalyzerUrl() { return elasTestLogAnalyzerUrl; } public void setElasTestLogAnalyzerUrl(String elasTestLogAnalyzerUrl) { this.elasTestLogAnalyzerUrl = elasTestLogAnalyzerUrl; } public String getElasTestTJobExecutionUrl() { return elasTestTJobExecutionUrl; } public void setElasTestTJobExecutionUrl(String elasTestTJobExecutionUrl) { this.elasTestTJobExecutionUrl = elasTestTJobExecutionUrl; } }